hexsha
stringlengths
40
40
repo
stringlengths
5
114
path
stringlengths
4
295
license
listlengths
1
10
language
stringclasses
5 values
identifier
stringlengths
1
116
original_docstring
stringlengths
133
7.85k
docstring
stringlengths
7
2.1k
docstring_tokens
listlengths
3
399
code
stringlengths
350
22.6k
code_tokens
listlengths
20
3.22k
short_docstring
stringlengths
0
1.32k
short_docstring_tokens
listlengths
0
359
comment
listlengths
0
1.22k
parameters
listlengths
0
13
docstring_params
dict
has_error
bool
1 class
ast_depth
int64
13
29
code_length
int64
151
3k
original_docstring_length
int64
76
449
3e90b9b5a4c5f3462d84cbf07d2358a3e8cc12a6
kirapoetica974/smallUml
UML/src/uml/activities/impl/DecisionNodeImpl.java
[ "MIT" ]
Java
DecisionNodeImpl
/** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Decision Node</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link uml.activities.impl.DecisionNodeImpl#getDecisionInput <em>Decision Input</em>}</li> * <li>{@link uml.activities.impl.DecisionNodeImpl#getDecisionInputFlow <em>Decision Input Flow</em>}</li> * </ul> * * @generated */
An implementation of the model object 'Decision Node'.
[ "An", "implementation", "of", "the", "model", "object", "'", "Decision", "Node", "'", "." ]
public class DecisionNodeImpl extends ControlNodeImpl implements DecisionNode { /** * The cached value of the '{@link #getDecisionInput() <em>Decision Input</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDecisionInput() * @generated * @ordered */ protected Behavior decisionInput; /** * The cached value of the '{@link #getDecisionInputFlow() <em>Decision Input Flow</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getDecisionInputFlow() * @generated * @ordered */ protected ObjectFlow decisionInputFlow; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DecisionNodeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return ActivitiesPackage.Literals.DECISION_NODE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Behavior getDecisionInput() { if (decisionInput != null && decisionInput.eIsProxy()) { InternalEObject oldDecisionInput = (InternalEObject)decisionInput; decisionInput = (Behavior)eResolveProxy(oldDecisionInput); if (decisionInput != oldDecisionInput) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, ActivitiesPackage.DECISION_NODE__DECISION_INPUT, oldDecisionInput, decisionInput)); } } return decisionInput; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Behavior basicGetDecisionInput() { return decisionInput; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDecisionInput(Behavior newDecisionInput) { Behavior oldDecisionInput = decisionInput; decisionInput = newDecisionInput; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ActivitiesPackage.DECISION_NODE__DECISION_INPUT, oldDecisionInput, decisionInput)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ObjectFlow getDecisionInputFlow() { if (decisionInputFlow != null && decisionInputFlow.eIsProxy()) { InternalEObject oldDecisionInputFlow = (InternalEObject)decisionInputFlow; decisionInputFlow = (ObjectFlow)eResolveProxy(oldDecisionInputFlow); if (decisionInputFlow != oldDecisionInputFlow) { if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.RESOLVE, ActivitiesPackage.DECISION_NODE__DECISION_INPUT_FLOW, oldDecisionInputFlow, decisionInputFlow)); } } return decisionInputFlow; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ObjectFlow basicGetDecisionInputFlow() { return decisionInputFlow; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setDecisionInputFlow(ObjectFlow newDecisionInputFlow) { ObjectFlow oldDecisionInputFlow = decisionInputFlow; decisionInputFlow = newDecisionInputFlow; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, ActivitiesPackage.DECISION_NODE__DECISION_INPUT_FLOW, oldDecisionInputFlow, decisionInputFlow)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case ActivitiesPackage.DECISION_NODE__DECISION_INPUT: if (resolve) return getDecisionInput(); return basicGetDecisionInput(); case ActivitiesPackage.DECISION_NODE__DECISION_INPUT_FLOW: if (resolve) return getDecisionInputFlow(); return basicGetDecisionInputFlow(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case ActivitiesPackage.DECISION_NODE__DECISION_INPUT: setDecisionInput((Behavior)newValue); return; case ActivitiesPackage.DECISION_NODE__DECISION_INPUT_FLOW: setDecisionInputFlow((ObjectFlow)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case ActivitiesPackage.DECISION_NODE__DECISION_INPUT: setDecisionInput((Behavior)null); return; case ActivitiesPackage.DECISION_NODE__DECISION_INPUT_FLOW: setDecisionInputFlow((ObjectFlow)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case ActivitiesPackage.DECISION_NODE__DECISION_INPUT: return decisionInput != null; case ActivitiesPackage.DECISION_NODE__DECISION_INPUT_FLOW: return decisionInputFlow != null; } return super.eIsSet(featureID); } }
[ "public", "class", "DecisionNodeImpl", "extends", "ControlNodeImpl", "implements", "DecisionNode", "{", "/**\n\t * The cached value of the '{@link #getDecisionInput() <em>Decision Input</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @see #getDecisionInput()\n\t * @generated\n\t * @ordered\n\t */", "protected", "Behavior", "decisionInput", ";", "/**\n\t * The cached value of the '{@link #getDecisionInputFlow() <em>Decision Input Flow</em>}' reference.\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @see #getDecisionInputFlow()\n\t * @generated\n\t * @ordered\n\t */", "protected", "ObjectFlow", "decisionInputFlow", ";", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "protected", "DecisionNodeImpl", "(", ")", "{", "super", "(", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "@", "Override", "protected", "EClass", "eStaticClass", "(", ")", "{", "return", "ActivitiesPackage", ".", "Literals", ".", "DECISION_NODE", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "Behavior", "getDecisionInput", "(", ")", "{", "if", "(", "decisionInput", "!=", "null", "&&", "decisionInput", ".", "eIsProxy", "(", ")", ")", "{", "InternalEObject", "oldDecisionInput", "=", "(", "InternalEObject", ")", "decisionInput", ";", "decisionInput", "=", "(", "Behavior", ")", "eResolveProxy", "(", "oldDecisionInput", ")", ";", "if", "(", "decisionInput", "!=", "oldDecisionInput", ")", "{", "if", "(", "eNotificationRequired", "(", ")", ")", "eNotify", "(", "new", "ENotificationImpl", "(", "this", ",", "Notification", ".", "RESOLVE", ",", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT", ",", "oldDecisionInput", ",", "decisionInput", ")", ")", ";", "}", "}", "return", "decisionInput", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "Behavior", "basicGetDecisionInput", "(", ")", "{", "return", "decisionInput", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "void", "setDecisionInput", "(", "Behavior", "newDecisionInput", ")", "{", "Behavior", "oldDecisionInput", "=", "decisionInput", ";", "decisionInput", "=", "newDecisionInput", ";", "if", "(", "eNotificationRequired", "(", ")", ")", "eNotify", "(", "new", "ENotificationImpl", "(", "this", ",", "Notification", ".", "SET", ",", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT", ",", "oldDecisionInput", ",", "decisionInput", ")", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "ObjectFlow", "getDecisionInputFlow", "(", ")", "{", "if", "(", "decisionInputFlow", "!=", "null", "&&", "decisionInputFlow", ".", "eIsProxy", "(", ")", ")", "{", "InternalEObject", "oldDecisionInputFlow", "=", "(", "InternalEObject", ")", "decisionInputFlow", ";", "decisionInputFlow", "=", "(", "ObjectFlow", ")", "eResolveProxy", "(", "oldDecisionInputFlow", ")", ";", "if", "(", "decisionInputFlow", "!=", "oldDecisionInputFlow", ")", "{", "if", "(", "eNotificationRequired", "(", ")", ")", "eNotify", "(", "new", "ENotificationImpl", "(", "this", ",", "Notification", ".", "RESOLVE", ",", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT_FLOW", ",", "oldDecisionInputFlow", ",", "decisionInputFlow", ")", ")", ";", "}", "}", "return", "decisionInputFlow", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "ObjectFlow", "basicGetDecisionInputFlow", "(", ")", "{", "return", "decisionInputFlow", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "public", "void", "setDecisionInputFlow", "(", "ObjectFlow", "newDecisionInputFlow", ")", "{", "ObjectFlow", "oldDecisionInputFlow", "=", "decisionInputFlow", ";", "decisionInputFlow", "=", "newDecisionInputFlow", ";", "if", "(", "eNotificationRequired", "(", ")", ")", "eNotify", "(", "new", "ENotificationImpl", "(", "this", ",", "Notification", ".", "SET", ",", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT_FLOW", ",", "oldDecisionInputFlow", ",", "decisionInputFlow", ")", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "@", "Override", "public", "Object", "eGet", "(", "int", "featureID", ",", "boolean", "resolve", ",", "boolean", "coreType", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT", ":", "if", "(", "resolve", ")", "return", "getDecisionInput", "(", ")", ";", "return", "basicGetDecisionInput", "(", ")", ";", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT_FLOW", ":", "if", "(", "resolve", ")", "return", "getDecisionInputFlow", "(", ")", ";", "return", "basicGetDecisionInputFlow", "(", ")", ";", "}", "return", "super", ".", "eGet", "(", "featureID", ",", "resolve", ",", "coreType", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "@", "Override", "public", "void", "eSet", "(", "int", "featureID", ",", "Object", "newValue", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT", ":", "setDecisionInput", "(", "(", "Behavior", ")", "newValue", ")", ";", "return", ";", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT_FLOW", ":", "setDecisionInputFlow", "(", "(", "ObjectFlow", ")", "newValue", ")", ";", "return", ";", "}", "super", ".", "eSet", "(", "featureID", ",", "newValue", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "@", "Override", "public", "void", "eUnset", "(", "int", "featureID", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT", ":", "setDecisionInput", "(", "(", "Behavior", ")", "null", ")", ";", "return", ";", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT_FLOW", ":", "setDecisionInputFlow", "(", "(", "ObjectFlow", ")", "null", ")", ";", "return", ";", "}", "super", ".", "eUnset", "(", "featureID", ")", ";", "}", "/**\n\t * <!-- begin-user-doc -->\n\t * <!-- end-user-doc -->\n\t * @generated\n\t */", "@", "Override", "public", "boolean", "eIsSet", "(", "int", "featureID", ")", "{", "switch", "(", "featureID", ")", "{", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT", ":", "return", "decisionInput", "!=", "null", ";", "case", "ActivitiesPackage", ".", "DECISION_NODE__DECISION_INPUT_FLOW", ":", "return", "decisionInputFlow", "!=", "null", ";", "}", "return", "super", ".", "eIsSet", "(", "featureID", ")", ";", "}", "}" ]
<!-- begin-user-doc --> An implementation of the model object '<em><b>Decision Node</b></em>'.
[ "<!", "--", "begin", "-", "user", "-", "doc", "--", ">", "An", "implementation", "of", "the", "model", "object", "'", "<em", ">", "<b", ">", "Decision", "Node<", "/", "b", ">", "<", "/", "em", ">", "'", "." ]
[]
[ { "param": "ControlNodeImpl", "type": null }, { "param": "DecisionNode", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ControlNodeImpl", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "DecisionNode", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
1,242
117
2c2ebe42c669fbdcd1f25636e7f0415eb3ef896c
tkonopka/Exp3p
src/exp3p/RichRegions.java
[ "Apache-2.0" ]
Java
RichRegions
/** * RichRegions is one of the utilities of Exp3p. It identifies genomic regions * that are rich in defined nucleotides. It can be used to identify regions * that have, e.g. more than 4 As and more than 5 Ts in a 10-nt stretch. * * * @author tkonopka */
RichRegions is one of the utilities of Exp3p. It identifies genomic regions that are rich in defined nucleotides. It can be used to identify regions that have, e.g. more than 4 As and more than 5 Ts in a 10-nt stretch. @author tkonopka
[ "RichRegions", "is", "one", "of", "the", "utilities", "of", "Exp3p", ".", "It", "identifies", "genomic", "regions", "that", "are", "rich", "in", "defined", "nucleotides", ".", "It", "can", "be", "used", "to", "identify", "regions", "that", "have", "e", ".", "g", ".", "more", "than", "4", "As", "and", "more", "than", "5", "Ts", "in", "a", "10", "-", "nt", "stretch", ".", "@author", "tkonopka" ]
public class RichRegions implements Runnable { private boolean isok = false; private final int[] mincounts = new int[4]; private int windowlen = 10; private File genomefile = null; private String output = "stdout"; private static int indexA = 0, indexT = 1, indexC = 2, indexG = 3; public static void printRichRegionsHelp() { System.out.println("Exp3p richregions: find regions rich in some nucleotides (e.g. A-rich regions)"); System.out.println(); System.out.println("Usage: java -jar Exp3p.jar richregions [options]"); System.out.println(); System.out.println(" --genome <File> - fasta file for genome "); System.out.println(" --window <int> - length of window"); System.out.println(" --minA <int> - minimum count of A"); System.out.println(" --minT <int> - minimum count of T"); System.out.println(" --minC <int> - minimum count of C"); System.out.println(" --minG <int> - minimum count of G"); System.out.println(" --output <String> - file where output will be stored (default is stdout)"); System.out.println(); System.out.println("\nAuthor: Tomasz Konopka ([email protected])\n"); } private boolean parseRichRegionsParameters(String[] args) { OptionParser prs = new OptionParser(); prs.accepts("genome").withRequiredArg().ofType(File.class); prs.accepts("output").withRequiredArg().ofType(String.class); prs.accepts("window").withRequiredArg().ofType(Integer.class); prs.accepts("minA").withRequiredArg().ofType(Integer.class); prs.accepts("minT").withRequiredArg().ofType(Integer.class); prs.accepts("minC").withRequiredArg().ofType(Integer.class); prs.accepts("minG").withRequiredArg().ofType(Integer.class); // now use OptionSet to parse the command line OptionSet options; try { options = prs.parse(args); } catch (Exception ex) { System.out.println("Error parsing command line parameters\n" + ex.getMessage()); return false; } // determine the richness criteria if (options.has("minA")) { mincounts[indexA] = (int) (Integer) options.valueOf("minA"); } if (options.has("minT")) { mincounts[indexT] = (int) (Integer) options.valueOf("minT"); } if (options.has("minC")) { mincounts[indexC] = (int) (Integer) options.valueOf("minC"); } if (options.has("minG")) { mincounts[indexG] = (int) (Integer) options.valueOf("minG"); } // determine the sliding window length if (options.has("window")) { windowlen = (int) (Integer) options.valueOf("window"); } // get the genome to search if (options.has("genome")) { genomefile = (File) options.valueOf("genome"); if (!genomefile.exists() || !genomefile.canRead()) { System.out.println("Cannot read genome file: " + genomefile.getAbsolutePath()); return false; } } // output the if (options.has("output")) { output = (String) options.valueOf("output"); } return true; } RichRegions(String[] args) { if (args == null || args.length == 0) { printRichRegionsHelp(); return; } if (parseRichRegionsParameters(args)) { isok = true; } } @Override public void run() { if (!isok) { return; } FastaReader fr; OutputStream os; try { fr = new FastaReader(BufferedReaderMaker.makeBufferedReader(genomefile)); os = OutputStreamMaker.makeOutputStream(output); } catch (IOException ex) { System.out.println("Trouble setup: " + ex.getMessage()); return; } while (fr.hasNext()) { try { fr.readNext(true); BitSet bs = findRichRegions(fr, os); outputBed(bs, fr.getChromosomeName(), os); } catch (IOException ex) { System.out.println("Trouble reading genome: " + ex.getMessage()); return; } } try { fr.close(); os.close(); } catch (Exception ex) { System.out.println("Trouble closing genome: " + ex.getMessage()); } } private void updateCounts(int[] counts, byte base, int change) { switch (base) { case 'A': counts[indexA] += change; return; case 'T': counts[indexT] += change; return; case 'C': counts[indexC] += change; return; case 'G': counts[indexG] += change; } } /** * Compare base counts to thresholds. * * @param counts * * must be array of length 4 or more. * * @param thresholds * * must be array of length 4 or more. * * @return * * true if all the thresholds are satisfied. false otherwise. * */ private boolean decideOnRichRegion(int[] counts, int[] thresholds) { for (int i = 0; i < 4; i++) { if (counts[i] < thresholds[i]) { return false; } } return true; } private BitSet findRichRegions(FastaReader fr, OutputStream os) { int chrlen = fr.getChromosomeLength(); BitSet bs = new BitSet(chrlen); int[] counts = new int[4]; for (int i = 0; i < chrlen; i++) { // shift the window one to the right updateCounts(counts, fr.getBaseAtPositionBase0(i), 1); int imin = i - windowlen; if (imin >= 0) { updateCounts(counts, fr.getBaseAtPositionBase0(imin), -1); } // check if the interval satisfies richness criteria if (decideOnRichRegion(counts, mincounts)) { bs.set(Math.max(0, imin+1), i+1); } } return bs; } private void outputBed(BitSet bs, String chr, OutputStream os) throws IOException { int nextset = bs.nextSetBit(0); while (nextset >= 0) { int nextclear = bs.nextClearBit(nextset); if (nextclear < 0) { nextclear = bs.size(); } String out = chr + "\t" + nextset + "\t" + nextclear + "\n"; os.write(out.getBytes()); if (nextclear < 0) { nextset = -1; } else { nextset = bs.nextSetBit(nextclear); } } } }
[ "public", "class", "RichRegions", "implements", "Runnable", "{", "private", "boolean", "isok", "=", "false", ";", "private", "final", "int", "[", "]", "mincounts", "=", "new", "int", "[", "4", "]", ";", "private", "int", "windowlen", "=", "10", ";", "private", "File", "genomefile", "=", "null", ";", "private", "String", "output", "=", "\"", "stdout", "\"", ";", "private", "static", "int", "indexA", "=", "0", ",", "indexT", "=", "1", ",", "indexC", "=", "2", ",", "indexG", "=", "3", ";", "public", "static", "void", "printRichRegionsHelp", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Exp3p richregions: find regions rich in some nucleotides (e.g. A-rich regions)", "\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Usage: java -jar Exp3p.jar richregions [options]", "\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --genome <File> - fasta file for genome ", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --window <int> - length of window", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --minA <int> - minimum count of A", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --minT <int> - minimum count of T", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --minC <int> - minimum count of C", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --minG <int> - minimum count of G", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " --output <String> - file where output will be stored (default is stdout)", "\"", ")", ";", "System", ".", "out", ".", "println", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "\\n", "Author: Tomasz Konopka ([email protected])", "\\n", "\"", ")", ";", "}", "private", "boolean", "parseRichRegionsParameters", "(", "String", "[", "]", "args", ")", "{", "OptionParser", "prs", "=", "new", "OptionParser", "(", ")", ";", "prs", ".", "accepts", "(", "\"", "genome", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "File", ".", "class", ")", ";", "prs", ".", "accepts", "(", "\"", "output", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "String", ".", "class", ")", ";", "prs", ".", "accepts", "(", "\"", "window", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "Integer", ".", "class", ")", ";", "prs", ".", "accepts", "(", "\"", "minA", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "Integer", ".", "class", ")", ";", "prs", ".", "accepts", "(", "\"", "minT", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "Integer", ".", "class", ")", ";", "prs", ".", "accepts", "(", "\"", "minC", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "Integer", ".", "class", ")", ";", "prs", ".", "accepts", "(", "\"", "minG", "\"", ")", ".", "withRequiredArg", "(", ")", ".", "ofType", "(", "Integer", ".", "class", ")", ";", "OptionSet", "options", ";", "try", "{", "options", "=", "prs", ".", "parse", "(", "args", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Error parsing command line parameters", "\\n", "\"", "+", "ex", ".", "getMessage", "(", ")", ")", ";", "return", "false", ";", "}", "if", "(", "options", ".", "has", "(", "\"", "minA", "\"", ")", ")", "{", "mincounts", "[", "indexA", "]", "=", "(", "int", ")", "(", "Integer", ")", "options", ".", "valueOf", "(", "\"", "minA", "\"", ")", ";", "}", "if", "(", "options", ".", "has", "(", "\"", "minT", "\"", ")", ")", "{", "mincounts", "[", "indexT", "]", "=", "(", "int", ")", "(", "Integer", ")", "options", ".", "valueOf", "(", "\"", "minT", "\"", ")", ";", "}", "if", "(", "options", ".", "has", "(", "\"", "minC", "\"", ")", ")", "{", "mincounts", "[", "indexC", "]", "=", "(", "int", ")", "(", "Integer", ")", "options", ".", "valueOf", "(", "\"", "minC", "\"", ")", ";", "}", "if", "(", "options", ".", "has", "(", "\"", "minG", "\"", ")", ")", "{", "mincounts", "[", "indexG", "]", "=", "(", "int", ")", "(", "Integer", ")", "options", ".", "valueOf", "(", "\"", "minG", "\"", ")", ";", "}", "if", "(", "options", ".", "has", "(", "\"", "window", "\"", ")", ")", "{", "windowlen", "=", "(", "int", ")", "(", "Integer", ")", "options", ".", "valueOf", "(", "\"", "window", "\"", ")", ";", "}", "if", "(", "options", ".", "has", "(", "\"", "genome", "\"", ")", ")", "{", "genomefile", "=", "(", "File", ")", "options", ".", "valueOf", "(", "\"", "genome", "\"", ")", ";", "if", "(", "!", "genomefile", ".", "exists", "(", ")", "||", "!", "genomefile", ".", "canRead", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Cannot read genome file: ", "\"", "+", "genomefile", ".", "getAbsolutePath", "(", ")", ")", ";", "return", "false", ";", "}", "}", "if", "(", "options", ".", "has", "(", "\"", "output", "\"", ")", ")", "{", "output", "=", "(", "String", ")", "options", ".", "valueOf", "(", "\"", "output", "\"", ")", ";", "}", "return", "true", ";", "}", "RichRegions", "(", "String", "[", "]", "args", ")", "{", "if", "(", "args", "==", "null", "||", "args", ".", "length", "==", "0", ")", "{", "printRichRegionsHelp", "(", ")", ";", "return", ";", "}", "if", "(", "parseRichRegionsParameters", "(", "args", ")", ")", "{", "isok", "=", "true", ";", "}", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "if", "(", "!", "isok", ")", "{", "return", ";", "}", "FastaReader", "fr", ";", "OutputStream", "os", ";", "try", "{", "fr", "=", "new", "FastaReader", "(", "BufferedReaderMaker", ".", "makeBufferedReader", "(", "genomefile", ")", ")", ";", "os", "=", "OutputStreamMaker", ".", "makeOutputStream", "(", "output", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Trouble setup: ", "\"", "+", "ex", ".", "getMessage", "(", ")", ")", ";", "return", ";", "}", "while", "(", "fr", ".", "hasNext", "(", ")", ")", "{", "try", "{", "fr", ".", "readNext", "(", "true", ")", ";", "BitSet", "bs", "=", "findRichRegions", "(", "fr", ",", "os", ")", ";", "outputBed", "(", "bs", ",", "fr", ".", "getChromosomeName", "(", ")", ",", "os", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Trouble reading genome: ", "\"", "+", "ex", ".", "getMessage", "(", ")", ")", ";", "return", ";", "}", "}", "try", "{", "fr", ".", "close", "(", ")", ";", "os", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Trouble closing genome: ", "\"", "+", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "}", "private", "void", "updateCounts", "(", "int", "[", "]", "counts", ",", "byte", "base", ",", "int", "change", ")", "{", "switch", "(", "base", ")", "{", "case", "'A'", ":", "counts", "[", "indexA", "]", "+=", "change", ";", "return", ";", "case", "'T'", ":", "counts", "[", "indexT", "]", "+=", "change", ";", "return", ";", "case", "'C'", ":", "counts", "[", "indexC", "]", "+=", "change", ";", "return", ";", "case", "'G'", ":", "counts", "[", "indexG", "]", "+=", "change", ";", "}", "}", "/**\n * Compare base counts to thresholds.\n *\n * @param counts\n *\n * must be array of length 4 or more.\n *\n * @param thresholds\n *\n * must be array of length 4 or more.\n *\n * @return\n *\n * true if all the thresholds are satisfied. false otherwise.\n *\n */", "private", "boolean", "decideOnRichRegion", "(", "int", "[", "]", "counts", ",", "int", "[", "]", "thresholds", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "if", "(", "counts", "[", "i", "]", "<", "thresholds", "[", "i", "]", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}", "private", "BitSet", "findRichRegions", "(", "FastaReader", "fr", ",", "OutputStream", "os", ")", "{", "int", "chrlen", "=", "fr", ".", "getChromosomeLength", "(", ")", ";", "BitSet", "bs", "=", "new", "BitSet", "(", "chrlen", ")", ";", "int", "[", "]", "counts", "=", "new", "int", "[", "4", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "chrlen", ";", "i", "++", ")", "{", "updateCounts", "(", "counts", ",", "fr", ".", "getBaseAtPositionBase0", "(", "i", ")", ",", "1", ")", ";", "int", "imin", "=", "i", "-", "windowlen", ";", "if", "(", "imin", ">=", "0", ")", "{", "updateCounts", "(", "counts", ",", "fr", ".", "getBaseAtPositionBase0", "(", "imin", ")", ",", "-", "1", ")", ";", "}", "if", "(", "decideOnRichRegion", "(", "counts", ",", "mincounts", ")", ")", "{", "bs", ".", "set", "(", "Math", ".", "max", "(", "0", ",", "imin", "+", "1", ")", ",", "i", "+", "1", ")", ";", "}", "}", "return", "bs", ";", "}", "private", "void", "outputBed", "(", "BitSet", "bs", ",", "String", "chr", ",", "OutputStream", "os", ")", "throws", "IOException", "{", "int", "nextset", "=", "bs", ".", "nextSetBit", "(", "0", ")", ";", "while", "(", "nextset", ">=", "0", ")", "{", "int", "nextclear", "=", "bs", ".", "nextClearBit", "(", "nextset", ")", ";", "if", "(", "nextclear", "<", "0", ")", "{", "nextclear", "=", "bs", ".", "size", "(", ")", ";", "}", "String", "out", "=", "chr", "+", "\"", "\\t", "\"", "+", "nextset", "+", "\"", "\\t", "\"", "+", "nextclear", "+", "\"", "\\n", "\"", ";", "os", ".", "write", "(", "out", ".", "getBytes", "(", ")", ")", ";", "if", "(", "nextclear", "<", "0", ")", "{", "nextset", "=", "-", "1", ";", "}", "else", "{", "nextset", "=", "bs", ".", "nextSetBit", "(", "nextclear", ")", ";", "}", "}", "}", "}" ]
RichRegions is one of the utilities of Exp3p.
[ "RichRegions", "is", "one", "of", "the", "utilities", "of", "Exp3p", "." ]
[ "// now use OptionSet to parse the command line", "// determine the richness criteria", "// determine the sliding window length", "// get the genome to search", "// output the ", "// shift the window one to the right", "// check if the interval satisfies richness criteria" ]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
1,591
77
550f98958707590e57a841955c8f697d3319ae4f
dram/metasfresh
backend/de.metas.business/src/main/java/de/metas/product/event/ProductWithNoCustomsTariffUserNotificationsProducer.java
[ "RSA-MD" ]
Java
ProductWithNoCustomsTariffUserNotificationsProducer
/* * #%L * de.metas.business * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . #L%
[ "This", "program", "is", "distributed", "in", "the", "hope", "that", "it", "will", "be", "useful", "but", "WITHOUT", "ANY", "WARRANTY", ";", "without", "even", "the", "implied", "warranty", "of", "MERCHANTABILITY", "or", "FITNESS", "FOR", "A", "PARTICULAR", "PURPOSE", ".", "See", "the", "GNU", "General", "Public", "License", "for", "more", "details", ".", "You", "should", "have", "received", "a", "copy", "of", "the", "GNU", "General", "Public", "License", "along", "with", "this", "program", ".", "If", "not", "see", ".", "#L%" ]
public class ProductWithNoCustomsTariffUserNotificationsProducer { private static final AdMessageKey MSG_ProductWithNoCustomsTariff = AdMessageKey.of("M_Product_No_CustomsTariff"); public static ProductWithNoCustomsTariffUserNotificationsProducer newInstance() { return new ProductWithNoCustomsTariffUserNotificationsProducer(); } /** Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously */ public static final Topic EVENTBUS_TOPIC = Topic.builder() .name("de.metas.product.UserNotifications") .type(Type.REMOTE) .build(); private static final AdWindowId DEFAULT_WINDOW_Product = AdWindowId.ofRepoId(140); // FIXME: HARDCODED private ProductWithNoCustomsTariffUserNotificationsProducer() { } public ProductWithNoCustomsTariffUserNotificationsProducer notify(final Collection<ProductId> productIds) { if (productIds == null || productIds.isEmpty()) { return this; } postNotifications(productIds.stream() .map(this::createUserNotification) .collect(ImmutableList.toImmutableList())); return this; } private UserNotificationRequest createUserNotification(@NonNull final ProductId productId) { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final AdWindowId productWindowId = adWindowDAO.getAdWindowId(I_M_Product.Table_Name, SOTrx.SALES, DEFAULT_WINDOW_Product); final TableRecordReference productRef = toTableRecordRef(productId); return newUserNotificationRequest() .recipientUserId(Env.getLoggedUserId()) .contentADMessage(MSG_ProductWithNoCustomsTariff) .contentADMessageParam(productRef) .targetAction(TargetRecordAction.ofRecordAndWindow(productRef, productWindowId)) .build(); } private static TableRecordReference toTableRecordRef(final ProductId productId) { return TableRecordReference.of(I_M_Product.Table_Name, productId); } private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC); } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } }
[ "public", "class", "ProductWithNoCustomsTariffUserNotificationsProducer", "{", "private", "static", "final", "AdMessageKey", "MSG_ProductWithNoCustomsTariff", "=", "AdMessageKey", ".", "of", "(", "\"", "M_Product_No_CustomsTariff", "\"", ")", ";", "public", "static", "ProductWithNoCustomsTariffUserNotificationsProducer", "newInstance", "(", ")", "{", "return", "new", "ProductWithNoCustomsTariffUserNotificationsProducer", "(", ")", ";", "}", "/** Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously */", "public", "static", "final", "Topic", "EVENTBUS_TOPIC", "=", "Topic", ".", "builder", "(", ")", ".", "name", "(", "\"", "de.metas.product.UserNotifications", "\"", ")", ".", "type", "(", "Type", ".", "REMOTE", ")", ".", "build", "(", ")", ";", "private", "static", "final", "AdWindowId", "DEFAULT_WINDOW_Product", "=", "AdWindowId", ".", "ofRepoId", "(", "140", ")", ";", "private", "ProductWithNoCustomsTariffUserNotificationsProducer", "(", ")", "{", "}", "public", "ProductWithNoCustomsTariffUserNotificationsProducer", "notify", "(", "final", "Collection", "<", "ProductId", ">", "productIds", ")", "{", "if", "(", "productIds", "==", "null", "||", "productIds", ".", "isEmpty", "(", ")", ")", "{", "return", "this", ";", "}", "postNotifications", "(", "productIds", ".", "stream", "(", ")", ".", "map", "(", "this", "::", "createUserNotification", ")", ".", "collect", "(", "ImmutableList", ".", "toImmutableList", "(", ")", ")", ")", ";", "return", "this", ";", "}", "private", "UserNotificationRequest", "createUserNotification", "(", "@", "NonNull", "final", "ProductId", "productId", ")", "{", "final", "IADWindowDAO", "adWindowDAO", "=", "Services", ".", "get", "(", "IADWindowDAO", ".", "class", ")", ";", "final", "AdWindowId", "productWindowId", "=", "adWindowDAO", ".", "getAdWindowId", "(", "I_M_Product", ".", "Table_Name", ",", "SOTrx", ".", "SALES", ",", "DEFAULT_WINDOW_Product", ")", ";", "final", "TableRecordReference", "productRef", "=", "toTableRecordRef", "(", "productId", ")", ";", "return", "newUserNotificationRequest", "(", ")", ".", "recipientUserId", "(", "Env", ".", "getLoggedUserId", "(", ")", ")", ".", "contentADMessage", "(", "MSG_ProductWithNoCustomsTariff", ")", ".", "contentADMessageParam", "(", "productRef", ")", ".", "targetAction", "(", "TargetRecordAction", ".", "ofRecordAndWindow", "(", "productRef", ",", "productWindowId", ")", ")", ".", "build", "(", ")", ";", "}", "private", "static", "TableRecordReference", "toTableRecordRef", "(", "final", "ProductId", "productId", ")", "{", "return", "TableRecordReference", ".", "of", "(", "I_M_Product", ".", "Table_Name", ",", "productId", ")", ";", "}", "private", "UserNotificationRequest", ".", "UserNotificationRequestBuilder", "newUserNotificationRequest", "(", ")", "{", "return", "UserNotificationRequest", ".", "builder", "(", ")", ".", "topic", "(", "EVENTBUS_TOPIC", ")", ";", "}", "private", "void", "postNotifications", "(", "final", "List", "<", "UserNotificationRequest", ">", "notifications", ")", "{", "Services", ".", "get", "(", "INotificationBL", ".", "class", ")", ".", "sendAfterCommit", "(", "notifications", ")", ";", "}", "}" ]
#%L de.metas.business %% Copyright (C) 2019 metas GmbH %% This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version.
[ "#%L", "de", ".", "metas", ".", "business", "%%", "Copyright", "(", "C", ")", "2019", "metas", "GmbH", "%%", "This", "program", "is", "free", "software", ":", "you", "can", "redistribute", "it", "and", "/", "or", "modify", "it", "under", "the", "terms", "of", "the", "GNU", "General", "Public", "License", "as", "published", "by", "the", "Free", "Software", "Foundation", "either", "version", "2", "of", "the", "License", "or", "(", "at", "your", "option", ")", "any", "later", "version", "." ]
[ "// FIXME: HARDCODED" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
485
180
060b91113ea6bedf043b7675788f276f838cd8d1
pablotrinidad/computo-evolutivo
projects/01/project/individuals.py
[ "MIT" ]
Python
AB
Approximated Brachistochrone. Approximated brachistochrones are the individuals that going to be evolving during the main algorithm execution. Each AB is represented as a set of n-1 vertical coordinates representing the overall curve, where n is the number of evenly distributed "slots" between the starting point and the final point.
Approximated Brachistochrone. Approximated brachistochrones are the individuals that going to be evolving during the main algorithm execution. Each AB is represented as a set of n-1 vertical coordinates representing the overall curve, where n is the number of evenly distributed "slots" between the starting point and the final point.
[ "Approximated", "Brachistochrone", ".", "Approximated", "brachistochrones", "are", "the", "individuals", "that", "going", "to", "be", "evolving", "during", "the", "main", "algorithm", "execution", ".", "Each", "AB", "is", "represented", "as", "a", "set", "of", "n", "-", "1", "vertical", "coordinates", "representing", "the", "overall", "curve", "where", "n", "is", "the", "number", "of", "evenly", "distributed", "\"", "slots", "\"", "between", "the", "starting", "point", "and", "the", "final", "point", "." ]
class AB: """Approximated Brachistochrone. Approximated brachistochrones are the individuals that going to be evolving during the main algorithm execution. Each AB is represented as a set of n-1 vertical coordinates representing the overall curve, where n is the number of evenly distributed "slots" between the starting point and the final point. """ def __init__( self, n: int, y: float, x: float, std: float, search_space: SearchSpace, chromosome: Chromosome = None ) -> None: """AB initialization.""" self.n = n self.y = y self.x = x self.std = std self.search_space = search_space self.chromosome = chromosome if chromosome else self.initialize() def initialize(self) -> Chromosome: """Return a real-valued random vector constrained by the search space.""" chromosome = [] for _ in range(self.n - 1): value = self.y while value >= self.y: value = random.randint(*self.search_space) chromosome.append(value) return chromosome @property def fitness(self) -> float: """Compute AB's fitness based on Borschbach-Dreckmann.""" total_sum = 0.0 points = [self.y] + self.chromosome + [0] bin_width = self.x / self.n for i in range(self.n): si = np.sqrt( ((bin_width)**2) + ((points[i+1] - points[i])**2) ) d = np.sqrt(self.y - points[i]) + np.sqrt(self.y - points[i+1]) total_sum += si/d return total_sum
[ "class", "AB", ":", "def", "__init__", "(", "self", ",", "n", ":", "int", ",", "y", ":", "float", ",", "x", ":", "float", ",", "std", ":", "float", ",", "search_space", ":", "SearchSpace", ",", "chromosome", ":", "Chromosome", "=", "None", ")", "->", "None", ":", "\"\"\"AB initialization.\"\"\"", "self", ".", "n", "=", "n", "self", ".", "y", "=", "y", "self", ".", "x", "=", "x", "self", ".", "std", "=", "std", "self", ".", "search_space", "=", "search_space", "self", ".", "chromosome", "=", "chromosome", "if", "chromosome", "else", "self", ".", "initialize", "(", ")", "def", "initialize", "(", "self", ")", "->", "Chromosome", ":", "\"\"\"Return a real-valued random vector constrained by the search space.\"\"\"", "chromosome", "=", "[", "]", "for", "_", "in", "range", "(", "self", ".", "n", "-", "1", ")", ":", "value", "=", "self", ".", "y", "while", "value", ">=", "self", ".", "y", ":", "value", "=", "random", ".", "randint", "(", "*", "self", ".", "search_space", ")", "chromosome", ".", "append", "(", "value", ")", "return", "chromosome", "@", "property", "def", "fitness", "(", "self", ")", "->", "float", ":", "\"\"\"Compute AB's fitness based on Borschbach-Dreckmann.\"\"\"", "total_sum", "=", "0.0", "points", "=", "[", "self", ".", "y", "]", "+", "self", ".", "chromosome", "+", "[", "0", "]", "bin_width", "=", "self", ".", "x", "/", "self", ".", "n", "for", "i", "in", "range", "(", "self", ".", "n", ")", ":", "si", "=", "np", ".", "sqrt", "(", "(", "(", "bin_width", ")", "**", "2", ")", "+", "(", "(", "points", "[", "i", "+", "1", "]", "-", "points", "[", "i", "]", ")", "**", "2", ")", ")", "d", "=", "np", ".", "sqrt", "(", "self", ".", "y", "-", "points", "[", "i", "]", ")", "+", "np", ".", "sqrt", "(", "self", ".", "y", "-", "points", "[", "i", "+", "1", "]", ")", "total_sum", "+=", "si", "/", "d", "return", "total_sum" ]
Approximated Brachistochrone.
[ "Approximated", "Brachistochrone", "." ]
[ "\"\"\"Approximated Brachistochrone.\n\n Approximated brachistochrones are the individuals that going to be evolving\n during the main algorithm execution. Each AB is represented as a set of\n n-1 vertical coordinates representing the overall curve, where n is the\n number of evenly distributed \"slots\" between the starting point and the\n final point.\n \"\"\"", "\"\"\"AB initialization.\"\"\"", "\"\"\"Return a real-valued random vector constrained by the search space.\"\"\"", "\"\"\"Compute AB's fitness based on Borschbach-Dreckmann.\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
382
77
5c9c9a7a48e040f5856bfc89c63eac2225585c22
cbevins/fire-behavior-simulator
src/variant/_Numeric.js
[ "MIT" ]
JavaScript
_Numeric
/** * _Numeric is an ABSTRACT CLASS and should never be instantiated by the client. * * _Numeric extends _Variant by * - enforcing numeric values within a specified range * - validating input text as valid numbers * * New methods: * - inputHint() * - isValidDisplayValue(inputText) * - maximumValue() * - minimumValue() * - stepValue() * - validateDisplayValue(inputText) * - validateNativeValue(value) */
_Numeric is an ABSTRACT CLASS and should never be instantiated by the client. _Numeric extends _Variant by - enforcing numeric values within a specified range - validating input text as valid numbers
[ "_Numeric", "is", "an", "ABSTRACT", "CLASS", "and", "should", "never", "be", "instantiated", "by", "the", "client", ".", "_Numeric", "extends", "_Variant", "by", "-", "enforcing", "numeric", "values", "within", "a", "specified", "range", "-", "validating", "input", "text", "as", "valid", "numbers" ]
class _Numeric extends _Variant { constructor (key, defaultValue = 0, minValue = 1 - Number.MAX_VALUE, maxValue = Number.MAX_VALUE, stepValue = 1) { const signature = `new _Numeric(${key}, ${defaultValue}, ${minValue}, ${maxValue}, ${stepValue})` if (typeof defaultValue !== 'number') { throw new Error(signature + ' requires arg 2 \'defaultValue\' to be a \'number\'') } else if (typeof minValue !== 'number') { throw new Error(signature + ' requires arg 3 \'minValue\' to be a \'number\'') } else if (typeof maxValue !== 'number') { throw new Error(signature + ' requires arg 4 \'maxValue\' to be a \'number\'') } else if (typeof stepValue !== 'number') { throw new Error(signature + ' requires arg 5 \'stepValue\' to be a \'number\'') } else if (minValue > maxValue) { throw new Error(signature + 'requires arg 3 \'minValue\' to be less than arg 3 \'maxValue\'') } else if (defaultValue < minValue) { throw new Error(signature + 'requires arg 2 \'defaultValue\' to be greater than arg 3 \'minValue\'') } else if (defaultValue > maxValue) { throw new Error(signature + 'requires arg 2 \'defaultValue\' to be less than arg 4 \'maxValue\'') } super(key, defaultValue) this._value._minimum = minValue this._value._maximum = maxValue this._value._step = stepValue } // defaultDisplayString() { return this.defaultDisplayValue() } // defaultDisplayValue() { return this.displayString('Numeric '+this.defaultValue()) } displayString (value) { return value.toString() } displayValue (value) { return value.toString() } inputHint () { return `${this.minimumValue()} - ${this.maximumValue()}` } isValidDisplayValue (inputText) { return this.validateDisplayValue(inputText).valid } isValidNativeValue (value) { if (typeof value !== 'number') return false return this.validateNativeValue(value).valid } maximumValue () { return this._value._maximum } minimumValue () { return this._value._minimum } stepValue () { return this._value._step } validateDisplayValue (inputText) { // filter invalid characters from input text const filtered = filterNumeric(inputText) // cast from text to number, boolean, object, or some other string const inputValue = parseFloat(filtered) if (isNaN(inputValue)) { return new ValidationResult(false, filtered, 'Not a valid number') } // Now we have a number value to convert to native units return this.validateNativeValue(inputValue) } validateNativeValue (value) { if (value < this._value._minimum) { return new ValidationResult(false, value, `Less than minimum value of ${this._value._minimum}`) } else if (value > this._value._maximum) { return new ValidationResult(false, value, `Greater than maximum value of ${this._value._maximum}`) } return new ValidationResult(true, value) } }
[ "class", "_Numeric", "extends", "_Variant", "{", "constructor", "(", "key", ",", "defaultValue", "=", "0", ",", "minValue", "=", "1", "-", "Number", ".", "MAX_VALUE", ",", "maxValue", "=", "Number", ".", "MAX_VALUE", ",", "stepValue", "=", "1", ")", "{", "const", "signature", "=", "`", "${", "key", "}", "${", "defaultValue", "}", "${", "minValue", "}", "${", "maxValue", "}", "${", "stepValue", "}", "`", "if", "(", "typeof", "defaultValue", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "signature", "+", "' requires arg 2 \\'defaultValue\\' to be a \\'number\\''", ")", "}", "else", "if", "(", "typeof", "minValue", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "signature", "+", "' requires arg 3 \\'minValue\\' to be a \\'number\\''", ")", "}", "else", "if", "(", "typeof", "maxValue", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "signature", "+", "' requires arg 4 \\'maxValue\\' to be a \\'number\\''", ")", "}", "else", "if", "(", "typeof", "stepValue", "!==", "'number'", ")", "{", "throw", "new", "Error", "(", "signature", "+", "' requires arg 5 \\'stepValue\\' to be a \\'number\\''", ")", "}", "else", "if", "(", "minValue", ">", "maxValue", ")", "{", "throw", "new", "Error", "(", "signature", "+", "'requires arg 3 \\'minValue\\' to be less than arg 3 \\'maxValue\\''", ")", "}", "else", "if", "(", "defaultValue", "<", "minValue", ")", "{", "throw", "new", "Error", "(", "signature", "+", "'requires arg 2 \\'defaultValue\\' to be greater than arg 3 \\'minValue\\''", ")", "}", "else", "if", "(", "defaultValue", ">", "maxValue", ")", "{", "throw", "new", "Error", "(", "signature", "+", "'requires arg 2 \\'defaultValue\\' to be less than arg 4 \\'maxValue\\''", ")", "}", "super", "(", "key", ",", "defaultValue", ")", "this", ".", "_value", ".", "_minimum", "=", "minValue", "this", ".", "_value", ".", "_maximum", "=", "maxValue", "this", ".", "_value", ".", "_step", "=", "stepValue", "}", "displayString", "(", "value", ")", "{", "return", "value", ".", "toString", "(", ")", "}", "displayValue", "(", "value", ")", "{", "return", "value", ".", "toString", "(", ")", "}", "inputHint", "(", ")", "{", "return", "`", "${", "this", ".", "minimumValue", "(", ")", "}", "${", "this", ".", "maximumValue", "(", ")", "}", "`", "}", "isValidDisplayValue", "(", "inputText", ")", "{", "return", "this", ".", "validateDisplayValue", "(", "inputText", ")", ".", "valid", "}", "isValidNativeValue", "(", "value", ")", "{", "if", "(", "typeof", "value", "!==", "'number'", ")", "return", "false", "return", "this", ".", "validateNativeValue", "(", "value", ")", ".", "valid", "}", "maximumValue", "(", ")", "{", "return", "this", ".", "_value", ".", "_maximum", "}", "minimumValue", "(", ")", "{", "return", "this", ".", "_value", ".", "_minimum", "}", "stepValue", "(", ")", "{", "return", "this", ".", "_value", ".", "_step", "}", "validateDisplayValue", "(", "inputText", ")", "{", "const", "filtered", "=", "filterNumeric", "(", "inputText", ")", "const", "inputValue", "=", "parseFloat", "(", "filtered", ")", "if", "(", "isNaN", "(", "inputValue", ")", ")", "{", "return", "new", "ValidationResult", "(", "false", ",", "filtered", ",", "'Not a valid number'", ")", "}", "return", "this", ".", "validateNativeValue", "(", "inputValue", ")", "}", "validateNativeValue", "(", "value", ")", "{", "if", "(", "value", "<", "this", ".", "_value", ".", "_minimum", ")", "{", "return", "new", "ValidationResult", "(", "false", ",", "value", ",", "`", "${", "this", ".", "_value", ".", "_minimum", "}", "`", ")", "}", "else", "if", "(", "value", ">", "this", ".", "_value", ".", "_maximum", ")", "{", "return", "new", "ValidationResult", "(", "false", ",", "value", ",", "`", "${", "this", ".", "_value", ".", "_maximum", "}", "`", ")", "}", "return", "new", "ValidationResult", "(", "true", ",", "value", ")", "}", "}" ]
_Numeric is an ABSTRACT CLASS and should never be instantiated by the client.
[ "_Numeric", "is", "an", "ABSTRACT", "CLASS", "and", "should", "never", "be", "instantiated", "by", "the", "client", "." ]
[ "// defaultDisplayString() { return this.defaultDisplayValue() }", "// defaultDisplayValue() { return this.displayString('Numeric '+this.defaultValue()) }", "// filter invalid characters from input text", "// cast from text to number, boolean, object, or some other string", "// Now we have a number value to convert to native units" ]
[ { "param": "_Variant", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "_Variant", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
24
699
95
f08e8007fb11b6bf38b05749741df189f089ec63
307209239/apollo-net
Apollo/SmartThreadPool/EventWaitHandle.cs
[ "Apache-2.0" ]
C#
STPEventWaitHandle
/// <summary> /// EventWaitHandle class /// In WindowsCE this class doesn't exist and I needed the WaitAll and WaitAny implementation. /// So I wrote this class to implement these two methods with some of their overloads. /// It uses the WaitForMultipleObjects API to do the WaitAll and WaitAny. /// Note that this class doesn't even inherit from WaitHandle! /// </summary>
EventWaitHandle class In WindowsCE this class doesn't exist and I needed the WaitAll and WaitAny implementation. So I wrote this class to implement these two methods with some of their overloads. It uses the WaitForMultipleObjects API to do the WaitAll and WaitAny. Note that this class doesn't even inherit from WaitHandle!
[ "EventWaitHandle", "class", "In", "WindowsCE", "this", "class", "doesn", "'", "t", "exist", "and", "I", "needed", "the", "WaitAll", "and", "WaitAny", "implementation", ".", "So", "I", "wrote", "this", "class", "to", "implement", "these", "two", "methods", "with", "some", "of", "their", "overloads", ".", "It", "uses", "the", "WaitForMultipleObjects", "API", "to", "do", "the", "WaitAll", "and", "WaitAny", ".", "Note", "that", "this", "class", "doesn", "'", "t", "even", "inherit", "from", "WaitHandle!" ]
public class STPEventWaitHandle { #region Public Constants public const int WaitTimeout = Timeout.Infinite; #endregion #region Private External Constants private const Int32 WAIT_FAILED = -1; private const Int32 WAIT_TIMEOUT = 0x102; private const UInt32 INFINITE = 0xFFFFFFFF; #endregion #region WaitAll and WaitAny internal static bool WaitOne(WaitHandle waitHandle, int millisecondsTimeout, bool exitContext) { return waitHandle.WaitOne(millisecondsTimeout, exitContext); } private static IntPtr[] PrepareNativeHandles(WaitHandle[] waitHandles) { IntPtr[] nativeHandles = new IntPtr[waitHandles.Length]; for (int i = 0; i < waitHandles.Length; i++) { nativeHandles[i] = waitHandles[i].Handle; } return nativeHandles; } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { uint timeout = millisecondsTimeout < 0 ? INFINITE : (uint)millisecondsTimeout; IntPtr[] nativeHandles = PrepareNativeHandles(waitHandles); int result = WaitForMultipleObjects((uint)waitHandles.Length, nativeHandles, true, timeout); if (result == WAIT_TIMEOUT || result == WAIT_FAILED) { return false; } return true; } public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { uint timeout = millisecondsTimeout < 0 ? INFINITE : (uint)millisecondsTimeout; IntPtr[] nativeHandles = PrepareNativeHandles(waitHandles); int result = WaitForMultipleObjects((uint)waitHandles.Length, nativeHandles, false, timeout); if (result >= 0 && result < waitHandles.Length) { return result; } return -1; } public static int WaitAny(WaitHandle[] waitHandles) { return WaitAny(waitHandles, Timeout.Infinite, false); } public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { int millisecondsTimeout = (int)timeout.TotalMilliseconds; return WaitAny(waitHandles, millisecondsTimeout, false); } #endregion #region External methods [DllImport("coredll.dll", SetLastError = true)] public static extern int WaitForMultipleObjects(uint nCount, IntPtr[] lpHandles, bool fWaitAll, uint dwMilliseconds); #endregion }
[ "public", "class", "STPEventWaitHandle", "{", "region", " Public Constants", "public", "const", "int", "WaitTimeout", "=", "Timeout", ".", "Infinite", ";", "endregion", "region", " Private External Constants", "private", "const", "Int32", "WAIT_FAILED", "=", "-", "1", ";", "private", "const", "Int32", "WAIT_TIMEOUT", "=", "0x102", ";", "private", "const", "UInt32", "INFINITE", "=", "0xFFFFFFFF", ";", "endregion", "region", " WaitAll and WaitAny", "internal", "static", "bool", "WaitOne", "(", "WaitHandle", "waitHandle", ",", "int", "millisecondsTimeout", ",", "bool", "exitContext", ")", "{", "return", "waitHandle", ".", "WaitOne", "(", "millisecondsTimeout", ",", "exitContext", ")", ";", "}", "private", "static", "IntPtr", "[", "]", "PrepareNativeHandles", "(", "WaitHandle", "[", "]", "waitHandles", ")", "{", "IntPtr", "[", "]", "nativeHandles", "=", "new", "IntPtr", "[", "waitHandles", ".", "Length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "waitHandles", ".", "Length", ";", "i", "++", ")", "{", "nativeHandles", "[", "i", "]", "=", "waitHandles", "[", "i", "]", ".", "Handle", ";", "}", "return", "nativeHandles", ";", "}", "public", "static", "bool", "WaitAll", "(", "WaitHandle", "[", "]", "waitHandles", ",", "int", "millisecondsTimeout", ",", "bool", "exitContext", ")", "{", "uint", "timeout", "=", "millisecondsTimeout", "<", "0", "?", "INFINITE", ":", "(", "uint", ")", "millisecondsTimeout", ";", "IntPtr", "[", "]", "nativeHandles", "=", "PrepareNativeHandles", "(", "waitHandles", ")", ";", "int", "result", "=", "WaitForMultipleObjects", "(", "(", "uint", ")", "waitHandles", ".", "Length", ",", "nativeHandles", ",", "true", ",", "timeout", ")", ";", "if", "(", "result", "==", "WAIT_TIMEOUT", "||", "result", "==", "WAIT_FAILED", ")", "{", "return", "false", ";", "}", "return", "true", ";", "}", "public", "static", "int", "WaitAny", "(", "WaitHandle", "[", "]", "waitHandles", ",", "int", "millisecondsTimeout", ",", "bool", "exitContext", ")", "{", "uint", "timeout", "=", "millisecondsTimeout", "<", "0", "?", "INFINITE", ":", "(", "uint", ")", "millisecondsTimeout", ";", "IntPtr", "[", "]", "nativeHandles", "=", "PrepareNativeHandles", "(", "waitHandles", ")", ";", "int", "result", "=", "WaitForMultipleObjects", "(", "(", "uint", ")", "waitHandles", ".", "Length", ",", "nativeHandles", ",", "false", ",", "timeout", ")", ";", "if", "(", "result", ">=", "0", "&&", "result", "<", "waitHandles", ".", "Length", ")", "{", "return", "result", ";", "}", "return", "-", "1", ";", "}", "public", "static", "int", "WaitAny", "(", "WaitHandle", "[", "]", "waitHandles", ")", "{", "return", "WaitAny", "(", "waitHandles", ",", "Timeout", ".", "Infinite", ",", "false", ")", ";", "}", "public", "static", "int", "WaitAny", "(", "WaitHandle", "[", "]", "waitHandles", ",", "TimeSpan", "timeout", ",", "bool", "exitContext", ")", "{", "int", "millisecondsTimeout", "=", "(", "int", ")", "timeout", ".", "TotalMilliseconds", ";", "return", "WaitAny", "(", "waitHandles", ",", "millisecondsTimeout", ",", "false", ")", ";", "}", "endregion", "region", " External methods", "[", "DllImport", "(", "\"", "coredll.dll", "\"", ",", "SetLastError", "=", "true", ")", "]", "public", "static", "extern", "int", "WaitForMultipleObjects", "(", "uint", "nCount", ",", "IntPtr", "[", "]", "lpHandles", ",", "bool", "fWaitAll", ",", "uint", "dwMilliseconds", ")", ";", "endregion", "}" ]
EventWaitHandle class In WindowsCE this class doesn't exist and I needed the WaitAll and WaitAny implementation.
[ "EventWaitHandle", "class", "In", "WindowsCE", "this", "class", "doesn", "'", "t", "exist", "and", "I", "needed", "the", "WaitAll", "and", "WaitAny", "implementation", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
536
82
cd9969a9b24aae26dfc66f4224f54d66a1e09b5a
letannam1999/FinalReport
UserInterface_Group6/Properties/Resources.Designer.cs
[ "MIT" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WindowsFormsApp4.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static System.Drawing.Bitmap _115893 { get { object obj = ResourceManager.GetObject("115893", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap _130304 { get { object obj = ResourceManager.GetObject("130304", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap _44948 { get { object obj = ResourceManager.GetObject("44948", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap _99_512 { get { object obj = ResourceManager.GetObject("99-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap camera_512 { get { object obj = ResourceManager.GetObject("camera-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap camera_icon_design_icon_png_favpng_sJFW2mRtWxBTG6T65cg3tXy71 { get { object obj = ResourceManager.GetObject("camera-icon-design-icon-png-favpng-sJFW2mRtWxBTG6T65cg3tXy71", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap computer_icons_information_icon_design_info_icon { get { object obj = ResourceManager.GetObject("computer-icons-information-icon-design-info-icon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap images { get { object obj = ResourceManager.GetObject("images", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap information_512 { get { object obj = ResourceManager.GetObject("information-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap Logout_512 { get { object obj = ResourceManager.GetObject("Logout-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap Logout_5121 { get { object obj = ResourceManager.GetObject("Logout-5121", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap map { get { object obj = ResourceManager.GetObject("map", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap phone_call_communication_telephone_number_512 { get { object obj = ResourceManager.GetObject("phone_call_communication_telephone_number-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap Phone_Small_Smart_Phone_512 { get { object obj = ResourceManager.GetObject("Phone_Small_Smart_Phone-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap pngtree_vector_camera_icon_png_image_926156 { get { object obj = ResourceManager.GetObject("pngtree-vector-camera-icon-png-image_926156", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap reload_512 { get { object obj = ResourceManager.GetObject("reload-512", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap Simple_movie_camera_icon_EPS_10_by_Hoeda80_580x386 { get { object obj = ResourceManager.GetObject("Simple-movie-camera-icon-EPS-10-by-Hoeda80-580x386", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap tải_xuống { get { object obj = ResourceManager.GetObject("tải xuống", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap Thegirltyler_Brand_Camp_Camp_Fire_Stories { get { object obj = ResourceManager.GetObject("Thegirltyler-Brand-Camp-Camp-Fire-Stories", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "WindowsFormsApp4.Properties.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "_115893", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "115893", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "_130304", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "130304", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "_44948", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "44948", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "_99_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "99-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "camera_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "camera-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "camera_icon_design_icon_png_favpng_sJFW2mRtWxBTG6T65cg3tXy71", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "camera-icon-design-icon-png-favpng-sJFW2mRtWxBTG6T65cg3tXy71", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "computer_icons_information_icon_design_info_icon", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "computer-icons-information-icon-design-info-icon", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "images", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "images", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "information_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "information-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "Logout_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Logout-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "Logout_5121", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Logout-5121", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "map", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "map", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "phone_call_communication_telephone_number_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "phone_call_communication_telephone_number-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "Phone_Small_Smart_Phone_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Phone_Small_Smart_Phone-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "pngtree_vector_camera_icon_png_image_926156", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "pngtree-vector-camera-icon-png-image_926156", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "reload_512", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "reload-512", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "Simple_movie_camera_icon_EPS_10_by_Hoeda80_580x386", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Simple-movie-camera-icon-EPS-10-by-Hoeda80-580x386", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "tải_xuống {\r", "", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "tải xuống\", r", "e", "s", "urceCulture);\r", "", "", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "System", ".", "Drawing", ".", "Bitmap", "Thegirltyler_Brand_Camp_Camp_Fire_Stories", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Thegirltyler-Brand-Camp-Camp-Fire-Stories", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "System", ".", "Drawing", ".", "Bitmap", ")", "(", "obj", ")", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Drawing.Bitmap.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,242
84
0f93f8d157dfbdbddd5b23cf9de724782a628516
ylht/brew
Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/rubocop-rspec-2.4.0/lib/rubocop/cop/rspec/shared_context.rb
[ "BSD-2-Clause" ]
Ruby
SharedContext
# Checks for proper shared_context and shared_examples usage. # # If there are no examples defined, use shared_context. # If there is no setup defined, use shared_examples. # # @example # # bad # RSpec.shared_context 'only examples here' do # it 'does x' do # end # # it 'does y' do # end # end # # # good # RSpec.shared_examples 'only examples here' do # it 'does x' do # end # # it 'does y' do # end # end # # @example # # bad # RSpec.shared_examples 'only setup here' do # subject(:foo) { :bar } # # let(:baz) { :bazz } # # before do # something # end # end # # # good # RSpec.shared_context 'only setup here' do # subject(:foo) { :bar } # # let(:baz) { :bazz } # # before do # something # end # end #
Checks for proper shared_context and shared_examples usage. If there are no examples defined, use shared_context. If there is no setup defined, use shared_examples.
[ "Checks", "for", "proper", "shared_context", "and", "shared_examples", "usage", ".", "If", "there", "are", "no", "examples", "defined", "use", "shared_context", ".", "If", "there", "is", "no", "setup", "defined", "use", "shared_examples", "." ]
class SharedContext < Base extend AutoCorrector MSG_EXAMPLES = "Use `shared_examples` when you don't define context." MSG_CONTEXT = "Use `shared_context` when you don't define examples." # @!method examples?(node) def_node_search :examples?, send_pattern('{#Includes.examples #Examples.all}') # @!method context?(node) def_node_search :context?, <<-PATTERN ( send #rspec? { #Subjects.all #Helpers.all #Includes.context #Hooks.all } ... ) PATTERN # @!method shared_context(node) def_node_matcher :shared_context, block_pattern('#SharedGroups.context') # @!method shared_example(node) def_node_matcher :shared_example, block_pattern('#SharedGroups.examples') def on_block(node) context_with_only_examples(node) do add_offense(node.send_node, message: MSG_EXAMPLES) do |corrector| corrector.replace(node.send_node.loc.selector, 'shared_examples') end end examples_with_only_context(node) do add_offense(node.send_node, message: MSG_CONTEXT) do |corrector| corrector.replace(node.send_node.loc.selector, 'shared_context') end end end private def context_with_only_examples(node) shared_context(node) { yield if examples?(node) && !context?(node) } end def examples_with_only_context(node) shared_example(node) { yield if context?(node) && !examples?(node) } end end
[ "class", "SharedContext", "<", "Base", "extend", "AutoCorrector", "MSG_EXAMPLES", "=", "\"Use `shared_examples` when you don't define context.\"", "MSG_CONTEXT", "=", "\"Use `shared_context` when you don't define examples.\"", "def_node_search", ":examples?", ",", "send_pattern", "(", "'{#Includes.examples #Examples.all}'", ")", "def_node_search", ":context?", ",", "<<-PATTERN", "\n (\n send #rspec? {\n #Subjects.all\n #Helpers.all\n #Includes.context\n #Hooks.all\n } ...\n )\n ", "PATTERN", "def_node_matcher", ":shared_context", ",", "block_pattern", "(", "'#SharedGroups.context'", ")", "def_node_matcher", ":shared_example", ",", "block_pattern", "(", "'#SharedGroups.examples'", ")", "def", "on_block", "(", "node", ")", "context_with_only_examples", "(", "node", ")", "do", "add_offense", "(", "node", ".", "send_node", ",", "message", ":", "MSG_EXAMPLES", ")", "do", "|", "corrector", "|", "corrector", ".", "replace", "(", "node", ".", "send_node", ".", "loc", ".", "selector", ",", "'shared_examples'", ")", "end", "end", "examples_with_only_context", "(", "node", ")", "do", "add_offense", "(", "node", ".", "send_node", ",", "message", ":", "MSG_CONTEXT", ")", "do", "|", "corrector", "|", "corrector", ".", "replace", "(", "node", ".", "send_node", ".", "loc", ".", "selector", ",", "'shared_context'", ")", "end", "end", "end", "private", "def", "context_with_only_examples", "(", "node", ")", "shared_context", "(", "node", ")", "{", "yield", "if", "examples?", "(", "node", ")", "&&", "!", "context?", "(", "node", ")", "}", "end", "def", "examples_with_only_context", "(", "node", ")", "shared_example", "(", "node", ")", "{", "yield", "if", "context?", "(", "node", ")", "&&", "!", "examples?", "(", "node", ")", "}", "end", "end" ]
Checks for proper shared_context and shared_examples usage.
[ "Checks", "for", "proper", "shared_context", "and", "shared_examples", "usage", "." ]
[ "# @!method examples?(node)", "# @!method context?(node)", "# @!method shared_context(node)", "# @!method shared_example(node)" ]
[ { "param": "Base", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Base", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "example", "docstring": "bad RSpec.shared_context 'only examples here' do it 'does x' do end it 'does y' do end end # good RSpec.shared_examples 'only examples here' do it 'does x' do end it 'does y' do end end", "docstring_tokens": [ "bad", "RSpec", ".", "shared_context", "'", "only", "examples", "here", "'", "do", "it", "'", "does", "x", "'", "do", "end", "it", "'", "does", "y", "'", "do", "end", "end", "#", "good", "RSpec", ".", "shared_examples", "'", "only", "examples", "here", "'", "do", "it", "'", "does", "x", "'", "do", "end", "it", "'", "does", "y", "'", "do", "end", "end" ] }, { "identifier": "example", "docstring": "bad RSpec.shared_examples 'only setup here' do subject(:foo) { :bar } let(:baz) { :bazz } before do something end end # good RSpec.shared_context 'only setup here' do subject(:foo) { :bar } let(:baz) { :bazz } before do something end end", "docstring_tokens": [ "bad", "RSpec", ".", "shared_examples", "'", "only", "setup", "here", "'", "do", "subject", "(", ":", "foo", ")", "{", ":", "bar", "}", "let", "(", ":", "baz", ")", "{", ":", "bazz", "}", "before", "do", "something", "end", "end", "#", "good", "RSpec", ".", "shared_context", "'", "only", "setup", "here", "'", "do", "subject", "(", ":", "foo", ")", "{", ":", "bar", "}", "let", "(", ":", "baz", ")", "{", ":", "bazz", "}", "before", "do", "something", "end", "end" ] } ] }
false
16
356
263
40b80359214ec9abba744ff377a2532128befdec
sumitbirla/rhombus_store
app/models/purchase_order.rb
[ "MIT" ]
Ruby
PurchaseOrder
# == Schema Information # # Table name: inv_purchase_orders # # id :integer not null, primary key # due_date :date # issue_date :date # notes :text(65535) # payment_terms :string(255) # ship_method :string(255) # ship_to :string(255) # status :string(255) # uuid :string(255) # created_at :datetime # updated_at :datetime # affiliate_id :integer # supplier_id :integer # # Indexes # # index_store_purchase_orders_on_affiliate_id (affiliate_id) #
Schema Information Table name: inv_purchase_orders Indexes
[ "Schema", "Information", "Table", "name", ":", "inv_purchase_orders", "Indexes" ]
class PurchaseOrder < ActiveRecord::Base include Exportable self.table_name = "inv_purchase_orders" after_create :set_uuid belongs_to :affiliate belongs_to :supplier, class_name: 'Affiliate' has_many :items, class_name: 'PurchaseOrderItem', dependent: :destroy has_many :inventory_transactions, foreign_key: :external_id, primary_key: :uuid, dependent: :destroy validates_presence_of :affiliate, :supplier, :issue_date, :status accepts_nested_attributes_for :items, reject_if: lambda { |x| x['sku'].blank? }, allow_destroy: true def set_uuid self.uuid = Rails.configuration.system_prefix + "_po_" + "#{id}" update_column(:uuid, uuid) end def total_amount amt = 0.0 items.each { |i| amt += i.quantity * i.unit_price } amt end def amount_owed amt = 0.0 items.each { |i| amt += i.quantity_received * i.unit_price } amt end def update_received_counts items.each do |i| i.quantity_received = 0 inventory_transactions.each do |t| t.items.each { |ti| i.quantity_received += ti.quantity if ti.sku == i.sku } end i.update_status end update_status save end def update_status if items.all? { |x| x.status == 'closed' } self.status = 'closed' elsif items.any? { |x| x.status == 'received' } self.status = 'received' end end def update_affiliate_products items.each do |item| p = Product.find_by(sku: item.sku) next if (item.supplier_code.blank? || p.nil?) ap = AffiliateProduct.find_or_initialize_by(affiliate_id: supplier_id, product_id: p.id) ap.assign_attributes(item_number: item.supplier_code, price: item.unit_price, description: item.description) ap.save end end # PUNDIT def self.policy_class ApplicationPolicy end end
[ "class", "PurchaseOrder", "<", "ActiveRecord", "::", "Base", "include", "Exportable", "self", ".", "table_name", "=", "\"inv_purchase_orders\"", "after_create", ":set_uuid", "belongs_to", ":affiliate", "belongs_to", ":supplier", ",", "class_name", ":", "'Affiliate'", "has_many", ":items", ",", "class_name", ":", "'PurchaseOrderItem'", ",", "dependent", ":", ":destroy", "has_many", ":inventory_transactions", ",", "foreign_key", ":", ":external_id", ",", "primary_key", ":", ":uuid", ",", "dependent", ":", ":destroy", "validates_presence_of", ":affiliate", ",", ":supplier", ",", ":issue_date", ",", ":status", "accepts_nested_attributes_for", ":items", ",", "reject_if", ":", "lambda", "{", "|", "x", "|", "x", "[", "'sku'", "]", ".", "blank?", "}", ",", "allow_destroy", ":", "true", "def", "set_uuid", "self", ".", "uuid", "=", "Rails", ".", "configuration", ".", "system_prefix", "+", "\"_po_\"", "+", "\"#{id}\"", "update_column", "(", ":uuid", ",", "uuid", ")", "end", "def", "total_amount", "amt", "=", "0.0", "items", ".", "each", "{", "|", "i", "|", "amt", "+=", "i", ".", "quantity", "*", "i", ".", "unit_price", "}", "amt", "end", "def", "amount_owed", "amt", "=", "0.0", "items", ".", "each", "{", "|", "i", "|", "amt", "+=", "i", ".", "quantity_received", "*", "i", ".", "unit_price", "}", "amt", "end", "def", "update_received_counts", "items", ".", "each", "do", "|", "i", "|", "i", ".", "quantity_received", "=", "0", "inventory_transactions", ".", "each", "do", "|", "t", "|", "t", ".", "items", ".", "each", "{", "|", "ti", "|", "i", ".", "quantity_received", "+=", "ti", ".", "quantity", "if", "ti", ".", "sku", "==", "i", ".", "sku", "}", "end", "i", ".", "update_status", "end", "update_status", "save", "end", "def", "update_status", "if", "items", ".", "all?", "{", "|", "x", "|", "x", ".", "status", "==", "'closed'", "}", "self", ".", "status", "=", "'closed'", "elsif", "items", ".", "any?", "{", "|", "x", "|", "x", ".", "status", "==", "'received'", "}", "self", ".", "status", "=", "'received'", "end", "end", "def", "update_affiliate_products", "items", ".", "each", "do", "|", "item", "|", "p", "=", "Product", ".", "find_by", "(", "sku", ":", "item", ".", "sku", ")", "next", "if", "(", "item", ".", "supplier_code", ".", "blank?", "||", "p", ".", "nil?", ")", "ap", "=", "AffiliateProduct", ".", "find_or_initialize_by", "(", "affiliate_id", ":", "supplier_id", ",", "product_id", ":", "p", ".", "id", ")", "ap", ".", "assign_attributes", "(", "item_number", ":", "item", ".", "supplier_code", ",", "price", ":", "item", ".", "unit_price", ",", "description", ":", "item", ".", "description", ")", "ap", ".", "save", "end", "end", "def", "self", ".", "policy_class", "ApplicationPolicy", "end", "end" ]
Schema Information Table name: inv_purchase_orders
[ "Schema", "Information", "Table", "name", ":", "inv_purchase_orders" ]
[ "# PUNDIT" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
488
168
98ce66cb07f4ca11f18049c470c6fef2ec507669
em3ndez/tribuo
Data/src/main/java/org/tribuo/data/sql/SQLToCSV.java
[ "ECL-2.0", "Apache-2.0" ]
Java
SQLToCSV
/** * Read an SQL query in on the standard input, write a CSV file containing the * results to the standard output. * <p> * N.B. This class accepts raw SQL strings and executes them directly via JDBC. It DOES NOT perform * any SQL escaping or other injection prevention. It is the user's responsibility to ensure that SQL passed to this * class performs as desired. */
Read an SQL query in on the standard input, write a CSV file containing the results to the standard output.
[ "Read", "an", "SQL", "query", "in", "on", "the", "standard", "input", "write", "a", "CSV", "file", "containing", "the", "results", "to", "the", "standard", "output", "." ]
public class SQLToCSV { /** * Command line options. */ public static class SQLToCSVOptions implements Options { /** * Connection string to the SQL database */ @Option(charName = 'n', longName = "connection", usage = "Connection string to the SQL database") public String connString; /** * Password for the SQL database */ @Option(charName = 'p', longName = "password", usage = "Password for the SQL database") public String password; /** * Username for the SQL database */ @Option(charName = 'u', longName = "username", usage = "Username for the SQL database") public String username; /** * SQL File to run as a query, defaults to stdin */ @Option(charName = 'i', longName = "input-sql", usage = "SQL File to run as a query, defaults to stdin") public Path inputPath; /** * File to write query results as CSV, defaults to stdout */ @Option(charName = 'o', longName = "output-csv", usage = "File to write query results as CSV, defaults to stdout") public Path outputPath; /** * Name of the DBConfig to use */ @Option(longName = "db-config", usage = "Name of the DBConfig to use") public SQLDBConfig dbConfig; } private static final Logger logger = Logger.getLogger(SQLToCSV.class.getName()); /** * Reads an SQL query from the standard input and writes the results of the * query to the standard output. * * @param args Single arg is the JDBC connection string. */ public static void main(String[] args) { LabsLogFormatter.setAllLogFormatters(); SQLToCSVOptions opts = new SQLToCSVOptions(); ConfigurationManager cm; try { cm = new ConfigurationManager(args,opts); } catch (UsageException e) { logger.info(e.getUsage()); System.exit(1); } if (opts.dbConfig == null) { if (opts.connString == null) { logger.log(Level.SEVERE, "Must specify connection string with -n"); System.exit(1); } if (opts.username != null || opts.password != null) { if (opts.username == null || opts.password == null) { logger.log(Level.SEVERE, "Must specify both of user and password with -u, -p if one is specified!"); System.exit(1); } } } else if(opts.username != null || opts.password != null || opts.connString != null) { logger.warning("dbConfig provided but username/password/connstring also provided. Options from -u, -p, -n being ignored"); } String query; try (BufferedReader br = opts.inputPath != null ? Files.newBufferedReader(opts.inputPath) : new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8))) { StringBuilder qsb = new StringBuilder(); String l; while ((l = br.readLine()) != null) { qsb.append(l); qsb.append("\n"); } query = qsb.toString().trim(); } catch (IOException ex) { logger.log(Level.SEVERE, "Error reading query: " + ex); System.exit(1); return; } if (query.isEmpty()) { logger.log(Level.SEVERE, "Query is empty string"); System.exit(1); } Connection conn = null; try { if (opts.dbConfig != null) { conn = opts.dbConfig.getConnection(); } else if (opts.username != null) { conn = DriverManager.getConnection(opts.connString, opts.username, opts.password); } else { conn = DriverManager.getConnection(opts.connString); } } catch (SQLException ex) { logger.log(Level.SEVERE, "Can't connect to database: " + opts.connString, ex); System.exit(1); } try (Statement stmt = conn.createStatement()){ stmt.setFetchSize(1000); stmt.setFetchDirection(ResultSet.FETCH_FORWARD); ResultSet results; try { results = stmt.executeQuery(query); } catch (SQLException ex) { logger.log(Level.SEVERE, "Error running query", ex); try { conn.close(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Failed to close connection", ex1); } return; } try(ICSVWriter writer = new CSVParserWriter(opts.outputPath != null ? Files.newBufferedWriter(opts.outputPath) : new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), 1024 * 1024), new RFC4180Parser(), "\n")) { writer.writeAll(results, true); } catch (IOException ex) { logger.log(Level.SEVERE, "Error writing CSV", ex); System.exit(1); } catch (SQLException ex) { logger.log(Level.SEVERE, "Error retrieving results", ex); System.exit(1); } } catch (SQLException ex) { logger.log(Level.SEVERE, "Couldn't create statement", ex); try { conn.close(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Failed to close connection", ex1); } System.exit(1); return; } try { conn.close(); } catch (SQLException ex1) { logger.log(Level.SEVERE, "Failed to close connection", ex1); } } }
[ "public", "class", "SQLToCSV", "{", "/**\n * Command line options.\n */", "public", "static", "class", "SQLToCSVOptions", "implements", "Options", "{", "/**\n * Connection string to the SQL database\n */", "@", "Option", "(", "charName", "=", "'n'", ",", "longName", "=", "\"", "connection", "\"", ",", "usage", "=", "\"", "Connection string to the SQL database", "\"", ")", "public", "String", "connString", ";", "/**\n * Password for the SQL database\n */", "@", "Option", "(", "charName", "=", "'p'", ",", "longName", "=", "\"", "password", "\"", ",", "usage", "=", "\"", "Password for the SQL database", "\"", ")", "public", "String", "password", ";", "/**\n * Username for the SQL database\n */", "@", "Option", "(", "charName", "=", "'u'", ",", "longName", "=", "\"", "username", "\"", ",", "usage", "=", "\"", "Username for the SQL database", "\"", ")", "public", "String", "username", ";", "/**\n * SQL File to run as a query, defaults to stdin\n */", "@", "Option", "(", "charName", "=", "'i'", ",", "longName", "=", "\"", "input-sql", "\"", ",", "usage", "=", "\"", "SQL File to run as a query, defaults to stdin", "\"", ")", "public", "Path", "inputPath", ";", "/**\n * File to write query results as CSV, defaults to stdout\n */", "@", "Option", "(", "charName", "=", "'o'", ",", "longName", "=", "\"", "output-csv", "\"", ",", "usage", "=", "\"", "File to write query results as CSV, defaults to stdout", "\"", ")", "public", "Path", "outputPath", ";", "/**\n * Name of the DBConfig to use\n */", "@", "Option", "(", "longName", "=", "\"", "db-config", "\"", ",", "usage", "=", "\"", "Name of the DBConfig to use", "\"", ")", "public", "SQLDBConfig", "dbConfig", ";", "}", "private", "static", "final", "Logger", "logger", "=", "Logger", ".", "getLogger", "(", "SQLToCSV", ".", "class", ".", "getName", "(", ")", ")", ";", "/**\n * Reads an SQL query from the standard input and writes the results of the\n * query to the standard output.\n *\n * @param args Single arg is the JDBC connection string.\n */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "LabsLogFormatter", ".", "setAllLogFormatters", "(", ")", ";", "SQLToCSVOptions", "opts", "=", "new", "SQLToCSVOptions", "(", ")", ";", "ConfigurationManager", "cm", ";", "try", "{", "cm", "=", "new", "ConfigurationManager", "(", "args", ",", "opts", ")", ";", "}", "catch", "(", "UsageException", "e", ")", "{", "logger", ".", "info", "(", "e", ".", "getUsage", "(", ")", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "if", "(", "opts", ".", "dbConfig", "==", "null", ")", "{", "if", "(", "opts", ".", "connString", "==", "null", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Must specify connection string with -n", "\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "if", "(", "opts", ".", "username", "!=", "null", "||", "opts", ".", "password", "!=", "null", ")", "{", "if", "(", "opts", ".", "username", "==", "null", "||", "opts", ".", "password", "==", "null", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Must specify both of user and password with -u, -p if one is specified!", "\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "}", "else", "if", "(", "opts", ".", "username", "!=", "null", "||", "opts", ".", "password", "!=", "null", "||", "opts", ".", "connString", "!=", "null", ")", "{", "logger", ".", "warning", "(", "\"", "dbConfig provided but username/password/connstring also provided. Options from -u, -p, -n being ignored", "\"", ")", ";", "}", "String", "query", ";", "try", "(", "BufferedReader", "br", "=", "opts", ".", "inputPath", "!=", "null", "?", "Files", ".", "newBufferedReader", "(", "opts", ".", "inputPath", ")", ":", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "System", ".", "in", ",", "StandardCharsets", ".", "UTF_8", ")", ")", ")", "{", "StringBuilder", "qsb", "=", "new", "StringBuilder", "(", ")", ";", "String", "l", ";", "while", "(", "(", "l", "=", "br", ".", "readLine", "(", ")", ")", "!=", "null", ")", "{", "qsb", ".", "append", "(", "l", ")", ";", "qsb", ".", "append", "(", "\"", "\\n", "\"", ")", ";", "}", "query", "=", "qsb", ".", "toString", "(", ")", ".", "trim", "(", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Error reading query: ", "\"", "+", "ex", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "return", ";", "}", "if", "(", "query", ".", "isEmpty", "(", ")", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Query is empty string", "\"", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "Connection", "conn", "=", "null", ";", "try", "{", "if", "(", "opts", ".", "dbConfig", "!=", "null", ")", "{", "conn", "=", "opts", ".", "dbConfig", ".", "getConnection", "(", ")", ";", "}", "else", "if", "(", "opts", ".", "username", "!=", "null", ")", "{", "conn", "=", "DriverManager", ".", "getConnection", "(", "opts", ".", "connString", ",", "opts", ".", "username", ",", "opts", ".", "password", ")", ";", "}", "else", "{", "conn", "=", "DriverManager", ".", "getConnection", "(", "opts", ".", "connString", ")", ";", "}", "}", "catch", "(", "SQLException", "ex", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Can't connect to database: ", "\"", "+", "opts", ".", "connString", ",", "ex", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "try", "(", "Statement", "stmt", "=", "conn", ".", "createStatement", "(", ")", ")", "{", "stmt", ".", "setFetchSize", "(", "1000", ")", ";", "stmt", ".", "setFetchDirection", "(", "ResultSet", ".", "FETCH_FORWARD", ")", ";", "ResultSet", "results", ";", "try", "{", "results", "=", "stmt", ".", "executeQuery", "(", "query", ")", ";", "}", "catch", "(", "SQLException", "ex", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Error running query", "\"", ",", "ex", ")", ";", "try", "{", "conn", ".", "close", "(", ")", ";", "}", "catch", "(", "SQLException", "ex1", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Failed to close connection", "\"", ",", "ex1", ")", ";", "}", "return", ";", "}", "try", "(", "ICSVWriter", "writer", "=", "new", "CSVParserWriter", "(", "opts", ".", "outputPath", "!=", "null", "?", "Files", ".", "newBufferedWriter", "(", "opts", ".", "outputPath", ")", ":", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "System", ".", "out", ",", "StandardCharsets", ".", "UTF_8", ")", ",", "1024", "*", "1024", ")", ",", "new", "RFC4180Parser", "(", ")", ",", "\"", "\\n", "\"", ")", ")", "{", "writer", ".", "writeAll", "(", "results", ",", "true", ")", ";", "}", "catch", "(", "IOException", "ex", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Error writing CSV", "\"", ",", "ex", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "catch", "(", "SQLException", "ex", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Error retrieving results", "\"", ",", "ex", ")", ";", "System", ".", "exit", "(", "1", ")", ";", "}", "}", "catch", "(", "SQLException", "ex", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Couldn't create statement", "\"", ",", "ex", ")", ";", "try", "{", "conn", ".", "close", "(", ")", ";", "}", "catch", "(", "SQLException", "ex1", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Failed to close connection", "\"", ",", "ex1", ")", ";", "}", "System", ".", "exit", "(", "1", ")", ";", "return", ";", "}", "try", "{", "conn", ".", "close", "(", ")", ";", "}", "catch", "(", "SQLException", "ex1", ")", "{", "logger", ".", "log", "(", "Level", ".", "SEVERE", ",", "\"", "Failed to close connection", "\"", ",", "ex1", ")", ";", "}", "}", "}" ]
Read an SQL query in on the standard input, write a CSV file containing the results to the standard output.
[ "Read", "an", "SQL", "query", "in", "on", "the", "standard", "input", "write", "a", "CSV", "file", "containing", "the", "results", "to", "the", "standard", "output", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,189
82
5570a86f55a5c2209fb8683d2f4bf66ec2cf5a3d
jiangxiangji/abstractions
src/Lifetime/Managers/ContainerControlledLifetimeManager.cs
[ "Apache-2.0" ]
C#
ContainerControlledLifetimeManager
/// <summary> /// <para> /// Unity returns the same instance each time the Resolve(...) method is called or when the /// dependency mechanism injects the instance into other classes. /// </para> /// </summary> /// <remarks> /// <para> /// Per Container lifetime allows a registration of an existing or resolved object as /// a scoped singleton in the container it was created or registered. In other words /// this instance is unique within the container it war registered with. Child or parent /// containers could have their own instances registered for the same contract. /// </para> /// <para> /// When the <see cref="ContainerControlledLifetimeManager"/> is disposed, /// the instance is disposed with it. /// </para> /// </remarks>
Unity returns the same instance each time the Resolve(...) method is called or when the dependency mechanism injects the instance into other classes.
[ "Unity", "returns", "the", "same", "instance", "each", "time", "the", "Resolve", "(", "...", ")", "method", "is", "called", "or", "when", "the", "dependency", "mechanism", "injects", "the", "instance", "into", "other", "classes", "." ]
public class ContainerControlledLifetimeManager : SynchronizedLifetimeManager, IInstanceLifetimeManager, IFactoryLifetimeManager, ITypeLifetimeManager { #region Fields protected object Value = NoValue; #endregion #region Constructor public ContainerControlledLifetimeManager() { Set = base.SetValue; Get = base.GetValue; TryGet = base.TryGetValue; } #endregion #region Scope public object Scope { get; internal set; } #endregion #region SynchronizedLifetimeManager public override object GetValue(ILifetimeContainer container = null) { return Get(container); } public override void SetValue(object newValue, ILifetimeContainer container = null) { Set(newValue, container); Set = (o, c) => throw new InvalidOperationException("ContainerControlledLifetimeManager can only be set once"); Get = SynchronizedGetValue; TryGet = SynchronizedGetValue; } protected override object SynchronizedGetValue(ILifetimeContainer container = null) => Value; protected override void SynchronizedSetValue(object newValue, ILifetimeContainer container = null) => Value = newValue; public override void RemoveValue(ILifetimeContainer container = null) => Dispose(); #endregion #region IFactoryLifetimeManager protected override LifetimeManager OnCreateLifetimeManager() { return new ContainerControlledLifetimeManager { Scope = Scope }; } #endregion #region IDisposable protected override void Dispose(bool disposing) { try { if (NoValue == Value) return; if (Value is IDisposable disposable) { disposable.Dispose(); } Value = NoValue; } finally { base.Dispose(disposing); } } #endregion #region Overrides public override string ToString() => "Lifetime:PerContainer"; #endregion }
[ "public", "class", "ContainerControlledLifetimeManager", ":", "SynchronizedLifetimeManager", ",", "IInstanceLifetimeManager", ",", "IFactoryLifetimeManager", ",", "ITypeLifetimeManager", "{", "region", " Fields", "protected", "object", "Value", "=", "NoValue", ";", "endregion", "region", " Constructor", "public", "ContainerControlledLifetimeManager", "(", ")", "{", "Set", "=", "base", ".", "SetValue", ";", "Get", "=", "base", ".", "GetValue", ";", "TryGet", "=", "base", ".", "TryGetValue", ";", "}", "endregion", "region", " Scope", "public", "object", "Scope", "{", "get", ";", "internal", "set", ";", "}", "endregion", "region", " SynchronizedLifetimeManager", "public", "override", "object", "GetValue", "(", "ILifetimeContainer", "container", "=", "null", ")", "{", "return", "Get", "(", "container", ")", ";", "}", "public", "override", "void", "SetValue", "(", "object", "newValue", ",", "ILifetimeContainer", "container", "=", "null", ")", "{", "Set", "(", "newValue", ",", "container", ")", ";", "Set", "=", "(", "o", ",", "c", ")", "=>", "throw", "new", "InvalidOperationException", "(", "\"", "ContainerControlledLifetimeManager can only be set once", "\"", ")", ";", "Get", "=", "SynchronizedGetValue", ";", "TryGet", "=", "SynchronizedGetValue", ";", "}", "protected", "override", "object", "SynchronizedGetValue", "(", "ILifetimeContainer", "container", "=", "null", ")", "=>", "Value", ";", "protected", "override", "void", "SynchronizedSetValue", "(", "object", "newValue", ",", "ILifetimeContainer", "container", "=", "null", ")", "=>", "Value", "=", "newValue", ";", "public", "override", "void", "RemoveValue", "(", "ILifetimeContainer", "container", "=", "null", ")", "=>", "Dispose", "(", ")", ";", "endregion", "region", " IFactoryLifetimeManager", "protected", "override", "LifetimeManager", "OnCreateLifetimeManager", "(", ")", "{", "return", "new", "ContainerControlledLifetimeManager", "{", "Scope", "=", "Scope", "}", ";", "}", "endregion", "region", " IDisposable", "protected", "override", "void", "Dispose", "(", "bool", "disposing", ")", "{", "try", "{", "if", "(", "NoValue", "==", "Value", ")", "return", ";", "if", "(", "Value", "is", "IDisposable", "disposable", ")", "{", "disposable", ".", "Dispose", "(", ")", ";", "}", "Value", "=", "NoValue", ";", "}", "finally", "{", "base", ".", "Dispose", "(", "disposing", ")", ";", "}", "}", "endregion", "region", " Overrides", "public", "override", "string", "ToString", "(", ")", "=>", "\"", "Lifetime:PerContainer", "\"", ";", "endregion", "}" ]
Unity returns the same instance each time the Resolve(...) method is called or when the dependency mechanism injects the instance into other classes.
[ "Unity", "returns", "the", "same", "instance", "each", "time", "the", "Resolve", "(", "...", ")", "method", "is", "called", "or", "when", "the", "dependency", "mechanism", "injects", "the", "instance", "into", "other", "classes", "." ]
[ "/// <summary>", "/// An instance of the object this manager is associated with.", "/// </summary>", "/// <value>This field holds a strong reference to the associated object.</value>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <inheritdoc/>", "/// <summary>", "/// This method provides human readable representation of the lifetime", "/// </summary>", "/// <returns>Name of the lifetime</returns>" ]
[ { "param": "SynchronizedLifetimeManager", "type": null }, { "param": "IInstanceLifetimeManager", "type": null }, { "param": "IFactoryLifetimeManager", "type": null }, { "param": "ITypeLifetimeManager", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "SynchronizedLifetimeManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "IInstanceLifetimeManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "IFactoryLifetimeManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "ITypeLifetimeManager", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Per Container lifetime allows a registration of an existing or resolved object as\na scoped singleton in the container it was created or registered. In other words\nthis instance is unique within the container it war registered with. Child or parent\ncontainers could have their own instances registered for the same contract.\n\nWhen the is disposed,\nthe instance is disposed with it.", "docstring_tokens": [ "Per", "Container", "lifetime", "allows", "a", "registration", "of", "an", "existing", "or", "resolved", "object", "as", "a", "scoped", "singleton", "in", "the", "container", "it", "was", "created", "or", "registered", ".", "In", "other", "words", "this", "instance", "is", "unique", "within", "the", "container", "it", "war", "registered", "with", ".", "Child", "or", "parent", "containers", "could", "have", "their", "own", "instances", "registered", "for", "the", "same", "contract", ".", "When", "the", "is", "disposed", "the", "instance", "is", "disposed", "with", "it", "." ] } ] }
false
13
408
155
87df41cdfbf2894d61033b946d9c444a2261a988
mvasilkov/scrapheap
archive-other/verlet/src/com/gmail/craigmit/verletdemo/Edge.java
[ "MIT" ]
Java
Edge
/** * <p>Original C++ code written by Benedikt Bitterli Copyright (c) 2009 * <p>Original C++ code and tutorial available at {@link http://www.gamedev.net/reference/programming/features/verletPhys/default.asp}. * <p>Conversion from C++ to Java done by Craig Mitchell Copyright (c) 2010. * <p> * <pre> * The code is released under the ZLib/LibPNG license. * It basically means that you can treat the source in any way you like (including commercial applications), * but you may not claim that you wrote it. * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * </pre> * * @author Craig Mitchell * @since 21/01/2010 */
This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions. 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. @author Craig Mitchell @since 21/01/2010
[ "This", "software", "is", "provided", "'", "as", "-", "is", "'", "without", "any", "express", "or", "implied", "warranty", ".", "In", "no", "event", "will", "the", "authors", "be", "held", "liable", "for", "any", "damages", "arising", "from", "the", "use", "of", "this", "software", ".", "Permission", "is", "granted", "to", "anyone", "to", "use", "this", "software", "for", "any", "purpose", "including", "commercial", "applications", "and", "to", "alter", "it", "and", "redistribute", "it", "freely", "subject", "to", "the", "following", "restrictions", ".", "1", ".", "The", "origin", "of", "this", "software", "must", "not", "be", "misrepresented", ";", "you", "must", "not", "claim", "that", "you", "wrote", "the", "original", "software", ".", "If", "you", "use", "this", "software", "in", "a", "product", "an", "acknowledgment", "in", "the", "product", "documentation", "would", "be", "appreciated", "but", "is", "not", "required", ".", "2", ".", "Altered", "source", "versions", "must", "be", "plainly", "marked", "as", "such", "and", "must", "not", "be", "misrepresented", "as", "being", "the", "original", "software", ".", "3", ".", "This", "notice", "may", "not", "be", "removed", "or", "altered", "from", "any", "source", "distribution", ".", "@author", "Craig", "Mitchell", "@since", "21", "/", "01", "/", "2010" ]
public class Edge { Vertex v1; Vertex v2; float length; boolean boundary; //Value used for optimization - see Physics::DetectCollision for more information PhysicsBody parent; public Edge( Physics world, PhysicsBody body, Vertex pV1, Vertex pV2) { this(world, body, pV1, pV2, true); } public Edge( Physics world, PhysicsBody body, Vertex pV1, Vertex pV2, boolean pBoundary) { v1 = pV1; //Set boundary vertices v2 = pV2; length = (float)Math.hypot(pV2.position.x - pV1.position.x, pV2.position.y - pV1.position.y); //Calculate the original length boundary = pBoundary; parent = body; body.addEdge( this ); //Add the edge to the given body and to the physics simulator world.addEdge( this ); } }
[ "public", "class", "Edge", "{", "Vertex", "v1", ";", "Vertex", "v2", ";", "float", "length", ";", "boolean", "boundary", ";", "PhysicsBody", "parent", ";", "public", "Edge", "(", "Physics", "world", ",", "PhysicsBody", "body", ",", "Vertex", "pV1", ",", "Vertex", "pV2", ")", "{", "this", "(", "world", ",", "body", ",", "pV1", ",", "pV2", ",", "true", ")", ";", "}", "public", "Edge", "(", "Physics", "world", ",", "PhysicsBody", "body", ",", "Vertex", "pV1", ",", "Vertex", "pV2", ",", "boolean", "pBoundary", ")", "{", "v1", "=", "pV1", ";", "v2", "=", "pV2", ";", "length", "=", "(", "float", ")", "Math", ".", "hypot", "(", "pV2", ".", "position", ".", "x", "-", "pV1", ".", "position", ".", "x", ",", "pV2", ".", "position", ".", "y", "-", "pV1", ".", "position", ".", "y", ")", ";", "boundary", "=", "pBoundary", ";", "parent", "=", "body", ";", "body", ".", "addEdge", "(", "this", ")", ";", "world", ".", "addEdge", "(", "this", ")", ";", "}", "}" ]
<p>Original C++ code written by Benedikt Bitterli Copyright (c) 2009 <p>Original C++ code and tutorial available at {@link http://www.gamedev.net/reference/programming/features/verletPhys/default.asp}.
[ "<p", ">", "Original", "C", "++", "code", "written", "by", "Benedikt", "Bitterli", "Copyright", "(", "c", ")", "2009", "<p", ">", "Original", "C", "++", "code", "and", "tutorial", "available", "at", "{", "@link", "http", ":", "//", "www", ".", "gamedev", ".", "net", "/", "reference", "/", "programming", "/", "features", "/", "verletPhys", "/", "default", ".", "asp", "}", "." ]
[ "//Value used for optimization - see Physics::DetectCollision for more information\r", "//Set boundary vertices\r", "//Calculate the original length\r", "//Add the edge to the given body and to the physics simulator\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
206
356
f5538a82a1a5c139f666b0b3d24f06966d99ae15
mmomtchev/yatag
test/node-gdal-async/lib/multiplexer.js
[ "0BSD" ]
JavaScript
RasterMuxStream
/** * Multiplexer stream * * Reads multiple input streams and outputs a single * synchronized stream with multiple data elements * * All the input streams must have the same length * * @class RasterMuxStream * @extends stream.Readable * @param {Record<string,RasterReadStream>} inputs Input streams * @param {RasterReadableOptions} [options] * @param {bool} [options.blockOptimize=true] Read by file blocks when possible (when rasterSize.x == blockSize.x) */
Multiplexer stream Reads multiple input streams and outputs a single synchronized stream with multiple data elements All the input streams must have the same length
[ "Multiplexer", "stream", "Reads", "multiple", "input", "streams", "and", "outputs", "a", "single", "synchronized", "stream", "with", "multiple", "data", "elements", "All", "the", "input", "streams", "must", "have", "the", "same", "length" ]
class RasterMuxStream extends Readable { constructor(inputs, options) { super({ ...options, objectMode: true }) this.inputs = {} this.buffers = {} this.buffersTotalData = {} this.ids = Object.keys(inputs) this.dataHandlers = {} this.endHandlers = {} this.isRunning = {} this.blockOptimize = (options || {}).blockOptimize for (const id of this.ids) { const inp = inputs[id] if (!(inp instanceof Readable)) throw new TypeError('inputs must be a map of Readables') if (!inp.readableObjectMode) throw new TypeError('All inputs must be in object mode') this.inputs[id] = inp this.buffers[id] = [] this.buffersTotalData[id] = 0 this.dataHandlers[id] = this.handleIncoming.bind(this, id) this.isRunning[id] = false this.endHandlers[id] = this.inputEnded.bind(this, id) this.inputs[id].on('end', this.endHandlers[id]) } } handleIncoming(id, chunk) { debug(`received on ${id} chunk ${chunk.length}`) this.buffers[id].push(chunk) this.buffersTotalData[id] += chunk.length const maxReady = Math.min.apply(Math, this.ids.map((id) => this.buffersTotalData[id])) if (maxReady == 0) { return } debug(`sending ${maxReady}`) const send = {} for (const id of this.ids) { if (this.buffers[id][0] === null) { // one of the inputs ended before the others this.destroy(`premature end on ${id}`) return } else if (this.buffers[id][0].length == maxReady && !this.blockOptimize) { // zero-copy mode, this input blocks are same size as the output debug(`zero-copy from ${id}`) send[id] = this.buffers[id][0] this.buffers[id].shift() } else { // block consolidation mode debug(`block consolidation from ${id}: ${this.buffers[id].map((buf) => buf.length)}`) send[id] = new this.buffers[id][0].constructor(maxReady) let len = 0 while (len + this.buffers[id][0].length < maxReady) { send[id].set(this.buffers[0], len) len += this.buffers[id][0].length this.buffers[id].shift() if (this.buffers[id][0] === null) { // one of the inputs ended before the others this.destroy(`premature end on ${id}`) return } } send.set(this.buffers[id][0].subarray(0, maxReady - len), len) if (maxReady - len < this.buffers[id][0].length) { this.buffers[id][0] = this.buffers[id][0].subarray(maxReady - len) } else { this.buffers[id].shift() } } this.buffersTotalData[id] -= maxReady } // send the consolidated result and eventually start pausing const flowing = this.push(send) if (this.tryEnd()) return if (!flowing) this.throttle() } throttle() { debug(`trying to throttle ${this.ids.map((id) => this.buffersTotalData[id])}`) // Find the most advanced input and pause it when it is not already paused const most = this.ids.reduce((most, id) => this.buffersTotalData[id] > this.buffersTotalData[most] ? id : most, this.ids[0]) if (this.isRunning[most]) { debug(`throttling ${most}`) this.isRunning[most] = false this.inputs[most].off('data', this.dataHandlers[most]) } } tryEnd() { if (this.buffers[this.ids[0]][0] === null) { const max = Math.max.apply(Math, this.ids.map((id) => this.buffersTotalData[id])) if (max > 0) { this.destroy(`premature end on ${this.ids[0]}`) return true } // this is the normal end debug('ended') this.push(null) for (const id of this.ids) { if (this.isRunning[id]) { this.inputs[id].off('data', this.dataHandlers[id]) } this.inputs[id].off('end', this.endHandlers[id]) } return true } return false } inputEnded(id) { debug(`${id} ended, ${this.ids.map((id) => this.buffersTotalData[id])}`) this.buffers[id].push(null) this.tryEnd() } _read() { for (const id of this.ids) { if (!this.isRunning[id]) { debug(`resuming ${id}`) this.isRunning[id] = true this.inputs[id].on('data', this.dataHandlers[id]) } } } }
[ "class", "RasterMuxStream", "extends", "Readable", "{", "constructor", "(", "inputs", ",", "options", ")", "{", "super", "(", "{", "...", "options", ",", "objectMode", ":", "true", "}", ")", "this", ".", "inputs", "=", "{", "}", "this", ".", "buffers", "=", "{", "}", "this", ".", "buffersTotalData", "=", "{", "}", "this", ".", "ids", "=", "Object", ".", "keys", "(", "inputs", ")", "this", ".", "dataHandlers", "=", "{", "}", "this", ".", "endHandlers", "=", "{", "}", "this", ".", "isRunning", "=", "{", "}", "this", ".", "blockOptimize", "=", "(", "options", "||", "{", "}", ")", ".", "blockOptimize", "for", "(", "const", "id", "of", "this", ".", "ids", ")", "{", "const", "inp", "=", "inputs", "[", "id", "]", "if", "(", "!", "(", "inp", "instanceof", "Readable", ")", ")", "throw", "new", "TypeError", "(", "'inputs must be a map of Readables'", ")", "if", "(", "!", "inp", ".", "readableObjectMode", ")", "throw", "new", "TypeError", "(", "'All inputs must be in object mode'", ")", "this", ".", "inputs", "[", "id", "]", "=", "inp", "this", ".", "buffers", "[", "id", "]", "=", "[", "]", "this", ".", "buffersTotalData", "[", "id", "]", "=", "0", "this", ".", "dataHandlers", "[", "id", "]", "=", "this", ".", "handleIncoming", ".", "bind", "(", "this", ",", "id", ")", "this", ".", "isRunning", "[", "id", "]", "=", "false", "this", ".", "endHandlers", "[", "id", "]", "=", "this", ".", "inputEnded", ".", "bind", "(", "this", ",", "id", ")", "this", ".", "inputs", "[", "id", "]", ".", "on", "(", "'end'", ",", "this", ".", "endHandlers", "[", "id", "]", ")", "}", "}", "handleIncoming", "(", "id", ",", "chunk", ")", "{", "debug", "(", "`", "${", "id", "}", "${", "chunk", ".", "length", "}", "`", ")", "this", ".", "buffers", "[", "id", "]", ".", "push", "(", "chunk", ")", "this", ".", "buffersTotalData", "[", "id", "]", "+=", "chunk", ".", "length", "const", "maxReady", "=", "Math", ".", "min", ".", "apply", "(", "Math", ",", "this", ".", "ids", ".", "map", "(", "(", "id", ")", "=>", "this", ".", "buffersTotalData", "[", "id", "]", ")", ")", "if", "(", "maxReady", "==", "0", ")", "{", "return", "}", "debug", "(", "`", "${", "maxReady", "}", "`", ")", "const", "send", "=", "{", "}", "for", "(", "const", "id", "of", "this", ".", "ids", ")", "{", "if", "(", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", "===", "null", ")", "{", "this", ".", "destroy", "(", "`", "${", "id", "}", "`", ")", "return", "}", "else", "if", "(", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "length", "==", "maxReady", "&&", "!", "this", ".", "blockOptimize", ")", "{", "debug", "(", "`", "${", "id", "}", "`", ")", "send", "[", "id", "]", "=", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", "this", ".", "buffers", "[", "id", "]", ".", "shift", "(", ")", "}", "else", "{", "debug", "(", "`", "${", "id", "}", "${", "this", ".", "buffers", "[", "id", "]", ".", "map", "(", "(", "buf", ")", "=>", "buf", ".", "length", ")", "}", "`", ")", "send", "[", "id", "]", "=", "new", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "constructor", "(", "maxReady", ")", "let", "len", "=", "0", "while", "(", "len", "+", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "length", "<", "maxReady", ")", "{", "send", "[", "id", "]", ".", "set", "(", "this", ".", "buffers", "[", "0", "]", ",", "len", ")", "len", "+=", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "length", "this", ".", "buffers", "[", "id", "]", ".", "shift", "(", ")", "if", "(", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", "===", "null", ")", "{", "this", ".", "destroy", "(", "`", "${", "id", "}", "`", ")", "return", "}", "}", "send", ".", "set", "(", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "subarray", "(", "0", ",", "maxReady", "-", "len", ")", ",", "len", ")", "if", "(", "maxReady", "-", "len", "<", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "length", ")", "{", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", "=", "this", ".", "buffers", "[", "id", "]", "[", "0", "]", ".", "subarray", "(", "maxReady", "-", "len", ")", "}", "else", "{", "this", ".", "buffers", "[", "id", "]", ".", "shift", "(", ")", "}", "}", "this", ".", "buffersTotalData", "[", "id", "]", "-=", "maxReady", "}", "const", "flowing", "=", "this", ".", "push", "(", "send", ")", "if", "(", "this", ".", "tryEnd", "(", ")", ")", "return", "if", "(", "!", "flowing", ")", "this", ".", "throttle", "(", ")", "}", "throttle", "(", ")", "{", "debug", "(", "`", "${", "this", ".", "ids", ".", "map", "(", "(", "id", ")", "=>", "this", ".", "buffersTotalData", "[", "id", "]", ")", "}", "`", ")", "const", "most", "=", "this", ".", "ids", ".", "reduce", "(", "(", "most", ",", "id", ")", "=>", "this", ".", "buffersTotalData", "[", "id", "]", ">", "this", ".", "buffersTotalData", "[", "most", "]", "?", "id", ":", "most", ",", "this", ".", "ids", "[", "0", "]", ")", "if", "(", "this", ".", "isRunning", "[", "most", "]", ")", "{", "debug", "(", "`", "${", "most", "}", "`", ")", "this", ".", "isRunning", "[", "most", "]", "=", "false", "this", ".", "inputs", "[", "most", "]", ".", "off", "(", "'data'", ",", "this", ".", "dataHandlers", "[", "most", "]", ")", "}", "}", "tryEnd", "(", ")", "{", "if", "(", "this", ".", "buffers", "[", "this", ".", "ids", "[", "0", "]", "]", "[", "0", "]", "===", "null", ")", "{", "const", "max", "=", "Math", ".", "max", ".", "apply", "(", "Math", ",", "this", ".", "ids", ".", "map", "(", "(", "id", ")", "=>", "this", ".", "buffersTotalData", "[", "id", "]", ")", ")", "if", "(", "max", ">", "0", ")", "{", "this", ".", "destroy", "(", "`", "${", "this", ".", "ids", "[", "0", "]", "}", "`", ")", "return", "true", "}", "debug", "(", "'ended'", ")", "this", ".", "push", "(", "null", ")", "for", "(", "const", "id", "of", "this", ".", "ids", ")", "{", "if", "(", "this", ".", "isRunning", "[", "id", "]", ")", "{", "this", ".", "inputs", "[", "id", "]", ".", "off", "(", "'data'", ",", "this", ".", "dataHandlers", "[", "id", "]", ")", "}", "this", ".", "inputs", "[", "id", "]", ".", "off", "(", "'end'", ",", "this", ".", "endHandlers", "[", "id", "]", ")", "}", "return", "true", "}", "return", "false", "}", "inputEnded", "(", "id", ")", "{", "debug", "(", "`", "${", "id", "}", "${", "this", ".", "ids", ".", "map", "(", "(", "id", ")", "=>", "this", ".", "buffersTotalData", "[", "id", "]", ")", "}", "`", ")", "this", ".", "buffers", "[", "id", "]", ".", "push", "(", "null", ")", "this", ".", "tryEnd", "(", ")", "}", "_read", "(", ")", "{", "for", "(", "const", "id", "of", "this", ".", "ids", ")", "{", "if", "(", "!", "this", ".", "isRunning", "[", "id", "]", ")", "{", "debug", "(", "`", "${", "id", "}", "`", ")", "this", ".", "isRunning", "[", "id", "]", "=", "true", "this", ".", "inputs", "[", "id", "]", ".", "on", "(", "'data'", ",", "this", ".", "dataHandlers", "[", "id", "]", ")", "}", "}", "}", "}" ]
Multiplexer stream Reads multiple input streams and outputs a single synchronized stream with multiple data elements
[ "Multiplexer", "stream", "Reads", "multiple", "input", "streams", "and", "outputs", "a", "single", "synchronized", "stream", "with", "multiple", "data", "elements" ]
[ "// one of the inputs ended before the others", "// zero-copy mode, this input blocks are same size as the output", "// block consolidation mode", "// one of the inputs ended before the others", "// send the consolidated result and eventually start pausing", "// Find the most advanced input and pause it when it is not already paused", "// this is the normal end" ]
[ { "param": "Readable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Readable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
1,125
108
1ec029d610ec4aa396de4eeee47402470631133d
landongw/disease-pattern-miner
PatternMiner/libraries/spmf/src/main/java/algorithms/frequentpatterns/vme/AlgoVME.java
[ "MIT" ]
Java
AlgoVME
/** * This is an implementation of the VME algorithm (Deng and Xu, 2011) for * erasable itemset mining.<br/><br/> * <p> * The VME algorithm finds all the ereasable itemsets from a product database.<br/><br/> * <p> * Actually, this algorithms is a only slight modification of the AprioriTID algorithm.<br/><br/> * <p> * I have implemented mostly as described in the paper with some modifications to make * it more efficient.<br/> * First, the authors suggested to generate all candidates of a level before * removing the unereasable ones. This is inefficient. Instead, in my implementation, * I check the "gain" (loss of profit) directly after generating a candidate so I can eliminate * them right away. <br/> * Second, it is unecessary to check the subsets like the authors * suggest because they use a vertical representation. <br/> * Third, the authors suggest to store the profit of transactions * in PID List. This is not memory efficient. For implementation it is better to * store the profit of each transaction only once in a hashtable. * * @author Philippe Fournier-Viger * @see Itemset */
This is an implementation of the VME algorithm (Deng and Xu, 2011) for erasable itemset mining. The VME algorithm finds all the ereasable itemsets from a product database. Actually, this algorithms is a only slight modification of the AprioriTID algorithm. I have implemented mostly as described in the paper with some modifications to make it more efficient. First, the authors suggested to generate all candidates of a level before removing the unereasable ones. This is inefficient. Instead, in my implementation, I check the "gain" (loss of profit) directly after generating a candidate so I can eliminate them right away. Second, it is unecessary to check the subsets like the authors suggest because they use a vertical representation. Third, the authors suggest to store the profit of transactions in PID List. This is not memory efficient. For implementation it is better to store the profit of each transaction only once in a hashtable. @author Philippe Fournier-Viger @see Itemset
[ "This", "is", "an", "implementation", "of", "the", "VME", "algorithm", "(", "Deng", "and", "Xu", "2011", ")", "for", "erasable", "itemset", "mining", ".", "The", "VME", "algorithm", "finds", "all", "the", "ereasable", "itemsets", "from", "a", "product", "database", ".", "Actually", "this", "algorithms", "is", "a", "only", "slight", "modification", "of", "the", "AprioriTID", "algorithm", ".", "I", "have", "implemented", "mostly", "as", "described", "in", "the", "paper", "with", "some", "modifications", "to", "make", "it", "more", "efficient", ".", "First", "the", "authors", "suggested", "to", "generate", "all", "candidates", "of", "a", "level", "before", "removing", "the", "unereasable", "ones", ".", "This", "is", "inefficient", ".", "Instead", "in", "my", "implementation", "I", "check", "the", "\"", "gain", "\"", "(", "loss", "of", "profit", ")", "directly", "after", "generating", "a", "candidate", "so", "I", "can", "eliminate", "them", "right", "away", ".", "Second", "it", "is", "unecessary", "to", "check", "the", "subsets", "like", "the", "authors", "suggest", "because", "they", "use", "a", "vertical", "representation", ".", "Third", "the", "authors", "suggest", "to", "store", "the", "profit", "of", "transactions", "in", "PID", "List", ".", "This", "is", "not", "memory", "efficient", ".", "For", "implementation", "it", "is", "better", "to", "store", "the", "profit", "of", "each", "transaction", "only", "once", "in", "a", "hashtable", ".", "@author", "Philippe", "Fournier", "-", "Viger", "@see", "Itemset" ]
public class AlgoVME { /** * variables for counting support of items * // key: item value: tidset of the item as a set of integers */ Map<Integer, Set<Integer>> mapItemTIDs = new HashMap<Integer, Set<Integer>>(); /** * variables for storing the profit of each transaction * // key: transaction id value: transaction profit */ Map<Integer, Integer> mapTransactionProfit = new HashMap<Integer, Integer>(); /** * start time of latest execution */ long startTimestamp = 0; /** * end time of latest execution */ long endTimeStamp = 0; /** * the maximum profit loss */ double maxProfitLoss = 0; /** * the overall profit */ double overallProfit = 0; /** * object to write the output file */ BufferedWriter writer = null; /** * Special parameter to set the maximum size of itemsets to be discovered */ int maxItemsetSize = Integer.MAX_VALUE; /** * the number of erasable itemsets found by the latest execution */ private int erasableItemsetCount = 0; /** * Default constructor */ public AlgoVME() { } /** * Run the VME algorithm. * * @param input path to an input file * @param output path to be used for writing the output file * @param threshold the threshold chosen by the user. * @throws IOException exception if error reading/writing files */ public void runAlgorithm(String input, String output, double threshold) throws NumberFormatException, IOException { // record start time startTimestamp = System.currentTimeMillis(); // create writer writer = new BufferedWriter(new FileWriter(output)); // reset number of erasale itemsts o 0 erasableItemsetCount = 0; // Scan the database one time to get the overall profit // and at the same time we record the profit of each transaction (product). overallProfit = 0; BufferedReader reader = new BufferedReader(new FileReader(input)); String line; int i = 0; // for each transaction (line) until the end of file while (((line = reader.readLine()) != null)) { // if the line is a comment, is empty or is a // kind of metadata if (line.isEmpty() == true || line.charAt(0) == '#' || line.charAt(0) == '%' || line.charAt(0) == '@') { continue; } // split the line String[] lineSplited = line.split(" "); // get the profit (in first position of the line) int profit = Integer.parseInt(lineSplited[0]); // add the profit to overall profit overallProfit += profit; // put the profit of this transaction in the map of transaction profit mapTransactionProfit.put(i++, profit); } // close input file reader.close(); // Calculate max profit loss maxProfitLoss = overallProfit * threshold; // Scan the database second time to find erasable itemset of size 1 // and their tid list. reader = new BufferedReader(new FileReader(input)); i = 0; // for each transaction (line) until the end of file while (((line = reader.readLine()) != null)) { // if the line is a comment, is empty or is a // kind of metadata if (line.isEmpty() == true || line.charAt(0) == '#' || line.charAt(0) == '%' || line.charAt(0) == '@') { continue; } // split the line String[] lineSplited = line.split(" "); // for each item in that line for (int j = 1; j < lineSplited.length; j++) { // convert item to integer int item = Integer.parseInt(lineSplited[j]); // get the tidset of that item // and update it with the current tid for this transaction Set<Integer> tids = mapItemTIDs.get(item); if (tids == null) { tids = new HashSet<Integer>(); mapItemTIDs.put(item, tids); } tids.add(i); } i++; // increase the tid for next transaction } // close the input file reader.close(); // Find erasable itemsets of size 1 and delete items that are // not erasable from memory List<Itemset> level = new ArrayList<Itemset>(); // for each item Iterator<Entry<Integer, Set<Integer>>> iterator = mapItemTIDs.entrySet().iterator(); while (iterator.hasNext()) { // get the tidset of that item Map.Entry<Integer, Set<Integer>> entry = iterator.next(); // init loss to 0 int loss = 0; // for each tid in the tidset for (Integer tid : entry.getValue()) { // add the loss resulting from erasing that item loss += mapTransactionProfit.get(tid); } // if the looss is less than the max profit loss if (loss <= maxProfitLoss && maxItemsetSize >= 1) { // it is an erasable itemset Itemset itemset = new Itemset(entry.getKey()); itemset.setTIDs(mapItemTIDs.get(entry.getKey())); level.add(itemset); // save it to the output file saveItemsetToFile(itemset, loss); } else { // otherwise, not erasable so we remove from memory. iterator.remove(); } } // sort items because apriori based algorithm need // a total order for candidate generation Collections.sort(level, new Comparator<Itemset>() { public int compare(Itemset o1, Itemset o2) { return o1.get(0) - o2.get(0); } }); // Recursively generate candidate erasable itemsets of size k>1 by using // erasable itemsets of size k-1 and stop // when no candidates can be generated int k = 2; while (!level.isEmpty() && k <= maxItemsetSize) { // Generate candidates of size K level = generateCandidateSizeK(level); k++; } // close the file writer.close(); // record end time endTimeStamp = System.currentTimeMillis(); } /** * Generate candidate itemsets of size K by using HWTUIs of size k-1 * * @param levelK_1 itemsets of size k-1 * @return candidates of size K */ protected List<Itemset> generateCandidateSizeK(List<Itemset> levelK_1) throws IOException { // create list to store candidates of size k List<Itemset> candidates = new ArrayList<Itemset>(); // For each itemset I1 and I2 of level k-1 loop1: for (int i = 0; i < levelK_1.size(); i++) { Itemset itemset1 = levelK_1.get(i); loop2: for (int j = i + 1; j < levelK_1.size(); j++) { Itemset itemset2 = levelK_1.get(j); // we compare items of itemset1 and itemset2. // If they have all the same k-1 items and the last item of itemset1 is smaller than // the last item of itemset2, we will combine them to generate a candidate for (int k = 0; k < itemset1.size(); k++) { // if they are the last items if (k == itemset1.size() - 1) { // the one from itemset1 should be smaller (lexical order) // and different from the one of itemset2 if (itemset1.getItems()[k] >= itemset2.getItems()[k]) { continue loop1; } } // if they are not the last items, and else if (itemset1.getItems()[k] < itemset2.get(k)) { continue loop2; // we continue searching } else if (itemset1.getItems()[k] > itemset2.get(k)) { continue loop1; // we stop searching: because of lexical order } } // NOW COMBINE ITEMSET 1 AND ITEMSET 2 Integer missing = itemset2.get(itemset2.size() - 1); // create the union of tids Set<Integer> unionTIDS = new HashSet<Integer>(itemset1.getTransactionsIds()); unionTIDS.addAll(itemset2.getTransactionsIds()); // calculate loss int loss = 0; // for each tid, add the profit ot the transaction to the loss for (Integer tid : unionTIDS) { loss += mapTransactionProfit.get(tid); } // if the loss is higher or equal to the max profit loss // that we can tolerate if (loss <= maxProfitLoss) { // Create a new candidate by combining itemset1 and itemset2 int newItemset[] = new int[itemset1.size() + 1]; System.arraycopy(itemset1.itemset, 0, newItemset, 0, itemset1.size()); newItemset[itemset1.size()] = itemset2.getItems()[itemset2.size() - 1]; Itemset candidate = new Itemset(newItemset); candidate.setTIDs(unionTIDS); // add the itemset to the set of candidates candidates.add(candidate); // save the itemset to the output file saveItemsetToFile(candidate, loss); } } } // return candidates return candidates; } /** * Save an itemset to the output file. * * @param itemset the itemset * @param loss the loss * @throws IOException exception if error while writing to output file */ private void saveItemsetToFile(Itemset itemset, int loss) throws IOException { // write the itemset writer.write(itemset.toString() + " #LOSS: " + loss); writer.newLine(); // increase the itemset count erasableItemsetCount++; } /** * Print statistics about the latest execution to System.out. */ public void printStats() { System.out .println("============= VME - STATS ============="); long temps = endTimeStamp - startTimestamp; System.out.println("Overall profit: " + overallProfit); System.out.println("Maximum profit loss (over. profit x treshold): " + maxProfitLoss); System.out.println(" Erasable itemset count : " + erasableItemsetCount); System.out.println(" Total time ~ " + temps + " ms"); System.out .println("==================================================="); } /** * Set the maximum pattern length * * @param length the maximum length */ public void setMaximumPatternLength(int length) { this.maxItemsetSize = length; } }
[ "public", "class", "AlgoVME", "{", "/**\n * variables for counting support of items\n * // key: item value: tidset of the item as a set of integers\n */", "Map", "<", "Integer", ",", "Set", "<", "Integer", ">", ">", "mapItemTIDs", "=", "new", "HashMap", "<", "Integer", ",", "Set", "<", "Integer", ">", ">", "(", ")", ";", "/**\n * variables for storing the profit of each transaction\n * // key: transaction id value: transaction profit\n */", "Map", "<", "Integer", ",", "Integer", ">", "mapTransactionProfit", "=", "new", "HashMap", "<", "Integer", ",", "Integer", ">", "(", ")", ";", "/**\n * start time of latest execution\n */", "long", "startTimestamp", "=", "0", ";", "/**\n * end time of latest execution\n */", "long", "endTimeStamp", "=", "0", ";", "/**\n * the maximum profit loss\n */", "double", "maxProfitLoss", "=", "0", ";", "/**\n * the overall profit\n */", "double", "overallProfit", "=", "0", ";", "/**\n * object to write the output file\n */", "BufferedWriter", "writer", "=", "null", ";", "/**\n * Special parameter to set the maximum size of itemsets to be discovered\n */", "int", "maxItemsetSize", "=", "Integer", ".", "MAX_VALUE", ";", "/**\n * the number of erasable itemsets found by the latest execution\n */", "private", "int", "erasableItemsetCount", "=", "0", ";", "/**\n * Default constructor\n */", "public", "AlgoVME", "(", ")", "{", "}", "/**\n * Run the VME algorithm.\n *\n * @param input path to an input file\n * @param output path to be used for writing the output file\n * @param threshold the threshold chosen by the user.\n * @throws IOException exception if error reading/writing files\n */", "public", "void", "runAlgorithm", "(", "String", "input", ",", "String", "output", ",", "double", "threshold", ")", "throws", "NumberFormatException", ",", "IOException", "{", "startTimestamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "writer", "=", "new", "BufferedWriter", "(", "new", "FileWriter", "(", "output", ")", ")", ";", "erasableItemsetCount", "=", "0", ";", "overallProfit", "=", "0", ";", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "input", ")", ")", ";", "String", "line", ";", "int", "i", "=", "0", ";", "while", "(", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", ")", "{", "if", "(", "line", ".", "isEmpty", "(", ")", "==", "true", "||", "line", ".", "charAt", "(", "0", ")", "==", "'#'", "||", "line", ".", "charAt", "(", "0", ")", "==", "'%'", "||", "line", ".", "charAt", "(", "0", ")", "==", "'@'", ")", "{", "continue", ";", "}", "String", "[", "]", "lineSplited", "=", "line", ".", "split", "(", "\"", " ", "\"", ")", ";", "int", "profit", "=", "Integer", ".", "parseInt", "(", "lineSplited", "[", "0", "]", ")", ";", "overallProfit", "+=", "profit", ";", "mapTransactionProfit", ".", "put", "(", "i", "++", ",", "profit", ")", ";", "}", "reader", ".", "close", "(", ")", ";", "maxProfitLoss", "=", "overallProfit", "*", "threshold", ";", "reader", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "input", ")", ")", ";", "i", "=", "0", ";", "while", "(", "(", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ")", ")", "{", "if", "(", "line", ".", "isEmpty", "(", ")", "==", "true", "||", "line", ".", "charAt", "(", "0", ")", "==", "'#'", "||", "line", ".", "charAt", "(", "0", ")", "==", "'%'", "||", "line", ".", "charAt", "(", "0", ")", "==", "'@'", ")", "{", "continue", ";", "}", "String", "[", "]", "lineSplited", "=", "line", ".", "split", "(", "\"", " ", "\"", ")", ";", "for", "(", "int", "j", "=", "1", ";", "j", "<", "lineSplited", ".", "length", ";", "j", "++", ")", "{", "int", "item", "=", "Integer", ".", "parseInt", "(", "lineSplited", "[", "j", "]", ")", ";", "Set", "<", "Integer", ">", "tids", "=", "mapItemTIDs", ".", "get", "(", "item", ")", ";", "if", "(", "tids", "==", "null", ")", "{", "tids", "=", "new", "HashSet", "<", "Integer", ">", "(", ")", ";", "mapItemTIDs", ".", "put", "(", "item", ",", "tids", ")", ";", "}", "tids", ".", "add", "(", "i", ")", ";", "}", "i", "++", ";", "}", "reader", ".", "close", "(", ")", ";", "List", "<", "Itemset", ">", "level", "=", "new", "ArrayList", "<", "Itemset", ">", "(", ")", ";", "Iterator", "<", "Entry", "<", "Integer", ",", "Set", "<", "Integer", ">", ">", ">", "iterator", "=", "mapItemTIDs", ".", "entrySet", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "Map", ".", "Entry", "<", "Integer", ",", "Set", "<", "Integer", ">", ">", "entry", "=", "iterator", ".", "next", "(", ")", ";", "int", "loss", "=", "0", ";", "for", "(", "Integer", "tid", ":", "entry", ".", "getValue", "(", ")", ")", "{", "loss", "+=", "mapTransactionProfit", ".", "get", "(", "tid", ")", ";", "}", "if", "(", "loss", "<=", "maxProfitLoss", "&&", "maxItemsetSize", ">=", "1", ")", "{", "Itemset", "itemset", "=", "new", "Itemset", "(", "entry", ".", "getKey", "(", ")", ")", ";", "itemset", ".", "setTIDs", "(", "mapItemTIDs", ".", "get", "(", "entry", ".", "getKey", "(", ")", ")", ")", ";", "level", ".", "add", "(", "itemset", ")", ";", "saveItemsetToFile", "(", "itemset", ",", "loss", ")", ";", "}", "else", "{", "iterator", ".", "remove", "(", ")", ";", "}", "}", "Collections", ".", "sort", "(", "level", ",", "new", "Comparator", "<", "Itemset", ">", "(", ")", "{", "public", "int", "compare", "(", "Itemset", "o1", ",", "Itemset", "o2", ")", "{", "return", "o1", ".", "get", "(", "0", ")", "-", "o2", ".", "get", "(", "0", ")", ";", "}", "}", ")", ";", "int", "k", "=", "2", ";", "while", "(", "!", "level", ".", "isEmpty", "(", ")", "&&", "k", "<=", "maxItemsetSize", ")", "{", "level", "=", "generateCandidateSizeK", "(", "level", ")", ";", "k", "++", ";", "}", "writer", ".", "close", "(", ")", ";", "endTimeStamp", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "}", "/**\n * Generate candidate itemsets of size K by using HWTUIs of size k-1\n *\n * @param levelK_1 itemsets of size k-1\n * @return candidates of size K\n */", "protected", "List", "<", "Itemset", ">", "generateCandidateSizeK", "(", "List", "<", "Itemset", ">", "levelK_1", ")", "throws", "IOException", "{", "List", "<", "Itemset", ">", "candidates", "=", "new", "ArrayList", "<", "Itemset", ">", "(", ")", ";", "loop1", ":", "for", "(", "int", "i", "=", "0", ";", "i", "<", "levelK_1", ".", "size", "(", ")", ";", "i", "++", ")", "{", "Itemset", "itemset1", "=", "levelK_1", ".", "get", "(", "i", ")", ";", "loop2", ":", "for", "(", "int", "j", "=", "i", "+", "1", ";", "j", "<", "levelK_1", ".", "size", "(", ")", ";", "j", "++", ")", "{", "Itemset", "itemset2", "=", "levelK_1", ".", "get", "(", "j", ")", ";", "for", "(", "int", "k", "=", "0", ";", "k", "<", "itemset1", ".", "size", "(", ")", ";", "k", "++", ")", "{", "if", "(", "k", "==", "itemset1", ".", "size", "(", ")", "-", "1", ")", "{", "if", "(", "itemset1", ".", "getItems", "(", ")", "[", "k", "]", ">=", "itemset2", ".", "getItems", "(", ")", "[", "k", "]", ")", "{", "continue", "loop1", ";", "}", "}", "else", "if", "(", "itemset1", ".", "getItems", "(", ")", "[", "k", "]", "<", "itemset2", ".", "get", "(", "k", ")", ")", "{", "continue", "loop2", ";", "}", "else", "if", "(", "itemset1", ".", "getItems", "(", ")", "[", "k", "]", ">", "itemset2", ".", "get", "(", "k", ")", ")", "{", "continue", "loop1", ";", "}", "}", "Integer", "missing", "=", "itemset2", ".", "get", "(", "itemset2", ".", "size", "(", ")", "-", "1", ")", ";", "Set", "<", "Integer", ">", "unionTIDS", "=", "new", "HashSet", "<", "Integer", ">", "(", "itemset1", ".", "getTransactionsIds", "(", ")", ")", ";", "unionTIDS", ".", "addAll", "(", "itemset2", ".", "getTransactionsIds", "(", ")", ")", ";", "int", "loss", "=", "0", ";", "for", "(", "Integer", "tid", ":", "unionTIDS", ")", "{", "loss", "+=", "mapTransactionProfit", ".", "get", "(", "tid", ")", ";", "}", "if", "(", "loss", "<=", "maxProfitLoss", ")", "{", "int", "newItemset", "[", "]", "=", "new", "int", "[", "itemset1", ".", "size", "(", ")", "+", "1", "]", ";", "System", ".", "arraycopy", "(", "itemset1", ".", "itemset", ",", "0", ",", "newItemset", ",", "0", ",", "itemset1", ".", "size", "(", ")", ")", ";", "newItemset", "[", "itemset1", ".", "size", "(", ")", "]", "=", "itemset2", ".", "getItems", "(", ")", "[", "itemset2", ".", "size", "(", ")", "-", "1", "]", ";", "Itemset", "candidate", "=", "new", "Itemset", "(", "newItemset", ")", ";", "candidate", ".", "setTIDs", "(", "unionTIDS", ")", ";", "candidates", ".", "add", "(", "candidate", ")", ";", "saveItemsetToFile", "(", "candidate", ",", "loss", ")", ";", "}", "}", "}", "return", "candidates", ";", "}", "/**\n * Save an itemset to the output file.\n *\n * @param itemset the itemset\n * @param loss the loss\n * @throws IOException exception if error while writing to output file\n */", "private", "void", "saveItemsetToFile", "(", "Itemset", "itemset", ",", "int", "loss", ")", "throws", "IOException", "{", "writer", ".", "write", "(", "itemset", ".", "toString", "(", ")", "+", "\"", " #LOSS: ", "\"", "+", "loss", ")", ";", "writer", ".", "newLine", "(", ")", ";", "erasableItemsetCount", "++", ";", "}", "/**\n * Print statistics about the latest execution to System.out.\n */", "public", "void", "printStats", "(", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "============= VME - STATS =============", "\"", ")", ";", "long", "temps", "=", "endTimeStamp", "-", "startTimestamp", ";", "System", ".", "out", ".", "println", "(", "\"", "Overall profit: ", "\"", "+", "overallProfit", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Maximum profit loss (over. profit x treshold): ", "\"", "+", "maxProfitLoss", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " Erasable itemset count : ", "\"", "+", "erasableItemsetCount", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " Total time ~ ", "\"", "+", "temps", "+", "\"", " ms", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "===================================================", "\"", ")", ";", "}", "/**\n * Set the maximum pattern length\n *\n * @param length the maximum length\n */", "public", "void", "setMaximumPatternLength", "(", "int", "length", ")", "{", "this", ".", "maxItemsetSize", "=", "length", ";", "}", "}" ]
This is an implementation of the VME algorithm (Deng and Xu, 2011) for erasable itemset mining.<br/><br/> <p> The VME algorithm finds all the ereasable itemsets from a product database.<br/><br/> <p> Actually, this algorithms is a only slight modification of the AprioriTID algorithm.<br/><br/> <p> I have implemented mostly as described in the paper with some modifications to make it more efficient.<br/> First, the authors suggested to generate all candidates of a level before removing the unereasable ones.
[ "This", "is", "an", "implementation", "of", "the", "VME", "algorithm", "(", "Deng", "and", "Xu", "2011", ")", "for", "erasable", "itemset", "mining", ".", "<br", "/", ">", "<br", "/", ">", "<p", ">", "The", "VME", "algorithm", "finds", "all", "the", "ereasable", "itemsets", "from", "a", "product", "database", ".", "<br", "/", ">", "<br", "/", ">", "<p", ">", "Actually", "this", "algorithms", "is", "a", "only", "slight", "modification", "of", "the", "AprioriTID", "algorithm", ".", "<br", "/", ">", "<br", "/", ">", "<p", ">", "I", "have", "implemented", "mostly", "as", "described", "in", "the", "paper", "with", "some", "modifications", "to", "make", "it", "more", "efficient", ".", "<br", "/", ">", "First", "the", "authors", "suggested", "to", "generate", "all", "candidates", "of", "a", "level", "before", "removing", "the", "unereasable", "ones", "." ]
[ "// record start time", "// create writer", "// reset number of erasale itemsts o 0", "// Scan the database one time to get the overall profit", "// and at the same time we record the profit of each transaction (product).", "// for each transaction (line) until the end of file", "// if the line is a comment, is empty or is a", "// kind of metadata", "// split the line", "// get the profit (in first position of the line)", "// add the profit to overall profit", "// put the profit of this transaction in the map of transaction profit", "// close input file", "// Calculate max profit loss", "// Scan the database second time to find erasable itemset of size 1", "// and their tid list.", "// for each transaction (line) until the end of file", "// if the line is a comment, is empty or is a", "// kind of metadata", "// split the line", "// for each item in that line", "// convert item to integer", "// get the tidset of that item", "// and update it with the current tid for this transaction", "// increase the tid for next transaction", "// close the input file", "// Find erasable itemsets of size 1 and delete items that are", "// not erasable from memory", "// for each item", "// get the tidset of that item", "// init loss to 0", "// for each tid in the tidset", "// add the loss resulting from erasing that item", "// if the looss is less than the max profit loss", "// it is an erasable itemset", "// save it to the output file", "// otherwise, not erasable so we remove from memory.", "// sort items because apriori based algorithm need", "// a total order for candidate generation", "// Recursively generate candidate erasable itemsets of size k>1 by using", "// erasable itemsets of size k-1 and stop", "// when no candidates can be generated", "// Generate candidates of size K", "// close the file", "// record end time", "// create list to store candidates of size k", "// For each itemset I1 and I2 of level k-1", "// we compare items of itemset1 and itemset2.", "// If they have all the same k-1 items and the last item of itemset1 is smaller than", "// the last item of itemset2, we will combine them to generate a candidate", "// if they are the last items", "// the one from itemset1 should be smaller (lexical order)", "// and different from the one of itemset2", "// if they are not the last items, and", "// we continue searching", "// we stop searching: because of lexical order", "// NOW COMBINE ITEMSET 1 AND ITEMSET 2", "// create the union of tids", "// calculate loss", "// for each tid, add the profit ot the transaction to the loss", "// if the loss is higher or equal to the max profit loss", "// that we can tolerate", "// Create a new candidate by combining itemset1 and itemset2", "// add the itemset to the set of candidates", "// save the itemset to the output file", "// return candidates", "// write the itemset", "// increase the itemset count" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
2,454
270
6763e789d70b2b5ad9409cfe102e325a8484963e
jbakic/Shielded
Shielded/ShieldedDictNc.cs
[ "MIT" ]
C#
ShieldedDictNc
/// <summary> /// A transactional dictionary - adding, removing, replacing items are transactional, /// but anything done to the items is not unless they are Shielded themselves. The 'Nc' stands /// for 'no count' - you cannot find out how many items it has, unless you enumerate. /// WARNING: Enumerating transactions will not conflict with parallel transactions which /// add new items to the dictionary. This is OK for read-only transactions, but writers /// might successfully commit some result even though they did not see all items. /// For fully safe enumerating, please use <see cref="ShieldedDict&lt;TKey, TItem&gt;"/>. /// </summary>
A transactional dictionary - adding, removing, replacing items are transactional, but anything done to the items is not unless they are Shielded themselves. The 'Nc' stands for 'no count' - you cannot find out how many items it has, unless you enumerate. WARNING: Enumerating transactions will not conflict with parallel transactions which add new items to the dictionary. This is OK for read-only transactions, but writers might successfully commit some result even though they did not see all items. For fully safe enumerating, please use .
[ "A", "transactional", "dictionary", "-", "adding", "removing", "replacing", "items", "are", "transactional", "but", "anything", "done", "to", "the", "items", "is", "not", "unless", "they", "are", "Shielded", "themselves", ".", "The", "'", "Nc", "'", "stands", "for", "'", "no", "count", "'", "-", "you", "cannot", "find", "out", "how", "many", "items", "it", "has", "unless", "you", "enumerate", ".", "WARNING", ":", "Enumerating", "transactions", "will", "not", "conflict", "with", "parallel", "transactions", "which", "add", "new", "items", "to", "the", "dictionary", ".", "This", "is", "OK", "for", "read", "-", "only", "transactions", "but", "writers", "might", "successfully", "commit", "some", "result", "even", "though", "they", "did", "not", "see", "all", "items", ".", "For", "fully", "safe", "enumerating", "please", "use", "." ]
public class ShieldedDictNc<TKey, TItem> : IShielded, IEnumerable<KeyValuePair<TKey, TItem>> { private class ItemKeeper { public long Version; public TItem Value; public bool Empty; public ItemKeeper Older; } private class LocalDict { public Dictionary<TKey, ItemKeeper> Items; public bool HasChanges; public bool Locked; public LocalDict(IEqualityComparer<TKey> comparer) { Items = new Dictionary<TKey, ItemKeeper>(comparer); } } private readonly IEqualityComparer<TKey> _comparer; private readonly ConcurrentDictionary<TKey, ItemKeeper> _dict; private readonly ConcurrentDictionary<TKey, WriteStamp> _writeStamps; private readonly TransactionalStorage<LocalDict> _localDict = new TransactionalStorage<LocalDict>(); private readonly object _owner; public ShieldedDictNc(IEnumerable<KeyValuePair<TKey, TItem>> items = null, object owner = null, IEqualityComparer<TKey> comparer = null) { _comparer = comparer ?? EqualityComparer<TKey>.Default; _dict = items == null ? new ConcurrentDictionary<TKey, ItemKeeper>(_comparer) : new ConcurrentDictionary<TKey, ItemKeeper>( items.Select(kvp => new KeyValuePair<TKey, ItemKeeper>(kvp.Key, new ItemKeeper() { Value = kvp.Value })), _comparer); _writeStamps = new ConcurrentDictionary<TKey, WriteStamp>(_comparer); _owner = owner ?? this; } public ShieldedDictNc(IEqualityComparer<TKey> comparer) : this(null, null, comparer) { } internal ShieldedDictNc(IEnumerable<KeyValuePair<TKey, TItem>> items, object owner, IEqualityComparer<TKey> comparer, out int count) : this(items, owner, comparer) { count = _dict.Count; } private void CheckLockAndEnlist(TKey key, bool write) { var locals = _localDict.HasValue ? _localDict.Value : null; if (locals != null && locals.Locked) { CheckLockedAccess(key, write); return; } if (!Shield.Enlist(this, locals != null, write) && locals.Items.ContainsKey(key)) return; WriteStamp w; if (_writeStamps.TryGetValue(key, out w) && w.Locked && w.Version <= Shield.ReadStamp) w.Wait(); } void CheckLockedAccess(TKey key, bool write) { var locals = _localDict.Value; ItemKeeper item; if (!locals.Items.TryGetValue(key, out item)) throw new InvalidOperationException("No new key access in this context."); if (item == null && write) throw new InvalidOperationException("No new writes in this context."); } private ItemKeeper CurrentTransactionOldValue(TKey key) { ItemKeeper point; _dict.TryGetValue(key, out point); while (point != null && point.Version > Shield.ReadStamp) point = point.Older; return point; } private LocalDict PrepareLocals() { LocalDict locals; if (_localDict.HasValue) locals = _localDict.Value; else _localDict.Value = locals = new LocalDict(_comparer); return locals; } private ItemKeeper PrepareWrite(TKey key) { CheckLockAndEnlist(key, true); var locals = PrepareLocals(); ItemKeeper existing; if (locals.Items.TryGetValue(key, out existing)) return existing; return null; } private ItemKeeper Read(TKey key) { CheckLockAndEnlist(key, false); ItemKeeper v, curr; var locals = PrepareLocals(); bool hasLocal; if (!(hasLocal = locals.Items.TryGetValue(key, out v)) || v == null || Shield.ReadingOldState) { if (!hasLocal) locals.Items.Add(key, null); v = CurrentTransactionOldValue(key); } else if (!Shield.CommitCheckDone && _dict.TryGetValue(key, out curr) && curr.Version > Shield.ReadStamp) throw new TransException("Writable read collision."); return v; } public TItem this [TKey key] { get { ItemKeeper v; if (!Shield.IsInTransaction) { if (!_dict.TryGetValue(key, out v) || v.Empty) throw new KeyNotFoundException(); return v.Value; } v = Read(key); if (v == null || v.Empty) throw new KeyNotFoundException(); return v.Value; } set { ItemKeeper local = PrepareWrite(key); ItemKeeper curr; if (!Shield.CommitCheckDone && _dict.TryGetValue(key, out curr) && curr.Version > Shield.ReadStamp) throw new TransException("Write collision."); if (local == null) { var locals = _localDict.Value; locals.Items[key] = new ItemKeeper() { Value = value }; locals.HasChanges = true; } else { local.Empty = false; local.Value = value; } } } public IEnumerable<TKey> Changes { get { if (Shield.IsInTransaction && _localDict.HasValue && _localDict.Value.HasChanges) { return _localDict.Value.Items .Where(kvp => kvp.Value != null) .Select(kvp => kvp.Key); } return Enumerable.Empty<TKey>(); } } public IEnumerable<TKey> Reads { get { if (Shield.IsInTransaction && _localDict.HasValue) return _localDict.Value.Items.Keys; return Enumerable.Empty<TKey>(); } } bool IShielded.HasChanges { get { return _localDict.HasValue && _localDict.Value.HasChanges; } } object IShielded.Owner { get { return _owner; } } bool IShielded.CanCommit(WriteStamp writeStamp) { var locals = _localDict.Value; locals.Locked = true; if (locals.Items.Any(kvp => { ItemKeeper v; return _writeStamps.ContainsKey(kvp.Key) || (_dict.TryGetValue(kvp.Key, out v) && v.Version > Shield.ReadStamp); })) return false; else { if (locals.HasChanges) foreach (var kvp in locals.Items) if (kvp.Value != null) _writeStamps[kvp.Key] = writeStamp; return true; } } private ConcurrentQueue<Tuple<long, List<TKey>>> _copies = new ConcurrentQueue<Tuple<long, List<TKey>>>(); void IShielded.Commit() { var locals = _localDict.Value; if (locals.HasChanges) { long? version = null; var copyList = new List<TKey>(); foreach (var kvp in _localDict.Value.Items) { if (kvp.Value == null) continue; if (version == null) version = _writeStamps[kvp.Key].Version; ItemKeeper v = null; if (_dict.TryGetValue(kvp.Key, out v)) copyList.Add(kvp.Key); var newCurrent = kvp.Value; if (!newCurrent.Empty || v != null) { newCurrent.Version = (long)version; newCurrent.Older = v; lock (_dict) _dict[kvp.Key] = newCurrent; } WriteStamp ws; _writeStamps.TryRemove(kvp.Key, out ws); } if (copyList.Count > 0) _copies.Enqueue(Tuple.Create((long)version, copyList)); } _localDict.Release(); } void IShielded.Rollback() { if (!_localDict.HasValue) return; var locals = _localDict.Value; if (locals.HasChanges) { WriteStamp ws; var ctx = Shield.Context; foreach (var kvp in locals.Items) { if (kvp.Value != null && _writeStamps.TryGetValue(kvp.Key, out ws) && ws.Locker == ctx) { _writeStamps.TryRemove(kvp.Key, out ws); } } } _localDict.Release(); } void IShielded.TrimCopies(long smallestOpenTransactionId) { Tuple<long, List<TKey>> item; while (_copies.TryPeek(out item) && item.Item1 <= smallestOpenTransactionId) { _copies.TryDequeue(out item); foreach (var key in item.Item2) { ItemKeeper point; if (!_dict.TryGetValue(key, out point)) continue; ItemKeeper pointNewer = null; while (point != null && point.Version > smallestOpenTransactionId) { pointNewer = point; point = point.Older; } if (point != null) { point.Older = null; if (point.Empty) { if (pointNewer != null) pointNewer.Older = null; else { lock (_dict) { ItemKeeper k; if (_dict.TryGetValue(key, out k) && k == point) _dict.TryRemove(key, out k); } } } } } } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable<KeyValuePair<TKey, TItem>>)this).GetEnumerator(); } public IEnumerator<KeyValuePair<TKey, TItem>> GetEnumerator() { Shield.AssertInTransaction(); var keys = _localDict.HasValue ? _dict.Keys.Union(_localDict.Value.Items.Keys, _comparer) : _dict.Keys; foreach (var key in keys) { var v = Read(key); if (v == null || v.Empty) continue; yield return new KeyValuePair<TKey, TItem>(key, v.Value); } } public void Clear() { Shield.AssertInTransaction(); foreach (var key in Keys) Remove(key); } public void CopyTo(KeyValuePair<TKey, TItem>[] array, int arrayIndex) { Shield.InTransaction(() => { foreach (KeyValuePair<TKey, TItem> kvp in this) array[arrayIndex++] = kvp; }); } public void Add(TKey key, TItem value) { Shield.AssertInTransaction(); if (ContainsKey(key)) throw new ArgumentException("The given key is already present in the dictionary."); this[key] = value; } public bool ContainsKey(TKey key) { ItemKeeper v; if (!Shield.IsInTransaction) return _dict.TryGetValue(key, out v) && v != null && !v.Empty; v = Read(key); return v != null && !v.Empty; } public bool Remove(TKey key) { Shield.AssertInTransaction(); var keeper = PrepareWrite(key); if (keeper != null) { var res = !keeper.Empty; keeper.Empty = true; keeper.Value = default; return res; } var old = CurrentTransactionOldValue(key); if (old == null || old.Empty) return false; var locals = _localDict.Value; locals.Items[key] = new ItemKeeper { Empty = true }; locals.HasChanges = true; return true; } public bool TryGetValue(TKey key, out TItem value) { ItemKeeper v; if (!Shield.IsInTransaction) { if (_dict.TryGetValue(key, out v) && !v.Empty) { value = v.Value; return true; } value = default(TItem); return false; } v = Read(key); if (v != null && !v.Empty) { value = v.Value; return true; } value = default(TItem); return false; } public ICollection<TKey> Keys { get { return Shield.InTransaction( () => ((IEnumerable<KeyValuePair<TKey, TItem>>)this) .Select(kvp => kvp.Key) .ToList()); } } public ICollection<TItem> Values { get { return Shield.InTransaction( () => ((IEnumerable<KeyValuePair<TKey, TItem>>)this) .Select(kvp => kvp.Value) .ToList()); } } }
[ "public", "class", "ShieldedDictNc", "<", "TKey", ",", "TItem", ">", ":", "IShielded", ",", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", "{", "private", "class", "ItemKeeper", "{", "public", "long", "Version", ";", "public", "TItem", "Value", ";", "public", "bool", "Empty", ";", "public", "ItemKeeper", "Older", ";", "}", "private", "class", "LocalDict", "{", "public", "Dictionary", "<", "TKey", ",", "ItemKeeper", ">", "Items", ";", "public", "bool", "HasChanges", ";", "public", "bool", "Locked", ";", "public", "LocalDict", "(", "IEqualityComparer", "<", "TKey", ">", "comparer", ")", "{", "Items", "=", "new", "Dictionary", "<", "TKey", ",", "ItemKeeper", ">", "(", "comparer", ")", ";", "}", "}", "private", "readonly", "IEqualityComparer", "<", "TKey", ">", "_comparer", ";", "private", "readonly", "ConcurrentDictionary", "<", "TKey", ",", "ItemKeeper", ">", "_dict", ";", "private", "readonly", "ConcurrentDictionary", "<", "TKey", ",", "WriteStamp", ">", "_writeStamps", ";", "private", "readonly", "TransactionalStorage", "<", "LocalDict", ">", "_localDict", "=", "new", "TransactionalStorage", "<", "LocalDict", ">", "(", ")", ";", "private", "readonly", "object", "_owner", ";", "public", "ShieldedDictNc", "(", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", "items", "=", "null", ",", "object", "owner", "=", "null", ",", "IEqualityComparer", "<", "TKey", ">", "comparer", "=", "null", ")", "{", "_comparer", "=", "comparer", "??", "EqualityComparer", "<", "TKey", ">", ".", "Default", ";", "_dict", "=", "items", "==", "null", "?", "new", "ConcurrentDictionary", "<", "TKey", ",", "ItemKeeper", ">", "(", "_comparer", ")", ":", "new", "ConcurrentDictionary", "<", "TKey", ",", "ItemKeeper", ">", "(", "items", ".", "Select", "(", "kvp", "=>", "new", "KeyValuePair", "<", "TKey", ",", "ItemKeeper", ">", "(", "kvp", ".", "Key", ",", "new", "ItemKeeper", "(", ")", "{", "Value", "=", "kvp", ".", "Value", "}", ")", ")", ",", "_comparer", ")", ";", "_writeStamps", "=", "new", "ConcurrentDictionary", "<", "TKey", ",", "WriteStamp", ">", "(", "_comparer", ")", ";", "_owner", "=", "owner", "??", "this", ";", "}", "public", "ShieldedDictNc", "(", "IEqualityComparer", "<", "TKey", ">", "comparer", ")", ":", "this", "(", "null", ",", "null", ",", "comparer", ")", "{", "}", "internal", "ShieldedDictNc", "(", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", "items", ",", "object", "owner", ",", "IEqualityComparer", "<", "TKey", ">", "comparer", ",", "out", "int", "count", ")", ":", "this", "(", "items", ",", "owner", ",", "comparer", ")", "{", "count", "=", "_dict", ".", "Count", ";", "}", "private", "void", "CheckLockAndEnlist", "(", "TKey", "key", ",", "bool", "write", ")", "{", "var", "locals", "=", "_localDict", ".", "HasValue", "?", "_localDict", ".", "Value", ":", "null", ";", "if", "(", "locals", "!=", "null", "&&", "locals", ".", "Locked", ")", "{", "CheckLockedAccess", "(", "key", ",", "write", ")", ";", "return", ";", "}", "if", "(", "!", "Shield", ".", "Enlist", "(", "this", ",", "locals", "!=", "null", ",", "write", ")", "&&", "locals", ".", "Items", ".", "ContainsKey", "(", "key", ")", ")", "return", ";", "WriteStamp", "w", ";", "if", "(", "_writeStamps", ".", "TryGetValue", "(", "key", ",", "out", "w", ")", "&&", "w", ".", "Locked", "&&", "w", ".", "Version", "<=", "Shield", ".", "ReadStamp", ")", "w", ".", "Wait", "(", ")", ";", "}", "void", "CheckLockedAccess", "(", "TKey", "key", ",", "bool", "write", ")", "{", "var", "locals", "=", "_localDict", ".", "Value", ";", "ItemKeeper", "item", ";", "if", "(", "!", "locals", ".", "Items", ".", "TryGetValue", "(", "key", ",", "out", "item", ")", ")", "throw", "new", "InvalidOperationException", "(", "\"", "No new key access in this context.", "\"", ")", ";", "if", "(", "item", "==", "null", "&&", "write", ")", "throw", "new", "InvalidOperationException", "(", "\"", "No new writes in this context.", "\"", ")", ";", "}", "private", "ItemKeeper", "CurrentTransactionOldValue", "(", "TKey", "key", ")", "{", "ItemKeeper", "point", ";", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "point", ")", ";", "while", "(", "point", "!=", "null", "&&", "point", ".", "Version", ">", "Shield", ".", "ReadStamp", ")", "point", "=", "point", ".", "Older", ";", "return", "point", ";", "}", "private", "LocalDict", "PrepareLocals", "(", ")", "{", "LocalDict", "locals", ";", "if", "(", "_localDict", ".", "HasValue", ")", "locals", "=", "_localDict", ".", "Value", ";", "else", "_localDict", ".", "Value", "=", "locals", "=", "new", "LocalDict", "(", "_comparer", ")", ";", "return", "locals", ";", "}", "private", "ItemKeeper", "PrepareWrite", "(", "TKey", "key", ")", "{", "CheckLockAndEnlist", "(", "key", ",", "true", ")", ";", "var", "locals", "=", "PrepareLocals", "(", ")", ";", "ItemKeeper", "existing", ";", "if", "(", "locals", ".", "Items", ".", "TryGetValue", "(", "key", ",", "out", "existing", ")", ")", "return", "existing", ";", "return", "null", ";", "}", "private", "ItemKeeper", "Read", "(", "TKey", "key", ")", "{", "CheckLockAndEnlist", "(", "key", ",", "false", ")", ";", "ItemKeeper", "v", ",", "curr", ";", "var", "locals", "=", "PrepareLocals", "(", ")", ";", "bool", "hasLocal", ";", "if", "(", "!", "(", "hasLocal", "=", "locals", ".", "Items", ".", "TryGetValue", "(", "key", ",", "out", "v", ")", ")", "||", "v", "==", "null", "||", "Shield", ".", "ReadingOldState", ")", "{", "if", "(", "!", "hasLocal", ")", "locals", ".", "Items", ".", "Add", "(", "key", ",", "null", ")", ";", "v", "=", "CurrentTransactionOldValue", "(", "key", ")", ";", "}", "else", "if", "(", "!", "Shield", ".", "CommitCheckDone", "&&", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "curr", ")", "&&", "curr", ".", "Version", ">", "Shield", ".", "ReadStamp", ")", "throw", "new", "TransException", "(", "\"", "Writable read collision.", "\"", ")", ";", "return", "v", ";", "}", "public", "TItem", "this", "[", "TKey", "key", "]", "{", "get", "{", "ItemKeeper", "v", ";", "if", "(", "!", "Shield", ".", "IsInTransaction", ")", "{", "if", "(", "!", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "v", ")", "||", "v", ".", "Empty", ")", "throw", "new", "KeyNotFoundException", "(", ")", ";", "return", "v", ".", "Value", ";", "}", "v", "=", "Read", "(", "key", ")", ";", "if", "(", "v", "==", "null", "||", "v", ".", "Empty", ")", "throw", "new", "KeyNotFoundException", "(", ")", ";", "return", "v", ".", "Value", ";", "}", "set", "{", "ItemKeeper", "local", "=", "PrepareWrite", "(", "key", ")", ";", "ItemKeeper", "curr", ";", "if", "(", "!", "Shield", ".", "CommitCheckDone", "&&", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "curr", ")", "&&", "curr", ".", "Version", ">", "Shield", ".", "ReadStamp", ")", "throw", "new", "TransException", "(", "\"", "Write collision.", "\"", ")", ";", "if", "(", "local", "==", "null", ")", "{", "var", "locals", "=", "_localDict", ".", "Value", ";", "locals", ".", "Items", "[", "key", "]", "=", "new", "ItemKeeper", "(", ")", "{", "Value", "=", "value", "}", ";", "locals", ".", "HasChanges", "=", "true", ";", "}", "else", "{", "local", ".", "Empty", "=", "false", ";", "local", ".", "Value", "=", "value", ";", "}", "}", "}", "public", "IEnumerable", "<", "TKey", ">", "Changes", "{", "get", "{", "if", "(", "Shield", ".", "IsInTransaction", "&&", "_localDict", ".", "HasValue", "&&", "_localDict", ".", "Value", ".", "HasChanges", ")", "{", "return", "_localDict", ".", "Value", ".", "Items", ".", "Where", "(", "kvp", "=>", "kvp", ".", "Value", "!=", "null", ")", ".", "Select", "(", "kvp", "=>", "kvp", ".", "Key", ")", ";", "}", "return", "Enumerable", ".", "Empty", "<", "TKey", ">", "(", ")", ";", "}", "}", "public", "IEnumerable", "<", "TKey", ">", "Reads", "{", "get", "{", "if", "(", "Shield", ".", "IsInTransaction", "&&", "_localDict", ".", "HasValue", ")", "return", "_localDict", ".", "Value", ".", "Items", ".", "Keys", ";", "return", "Enumerable", ".", "Empty", "<", "TKey", ">", "(", ")", ";", "}", "}", "bool", "IShielded", ".", "HasChanges", "{", "get", "{", "return", "_localDict", ".", "HasValue", "&&", "_localDict", ".", "Value", ".", "HasChanges", ";", "}", "}", "object", "IShielded", ".", "Owner", "{", "get", "{", "return", "_owner", ";", "}", "}", "bool", "IShielded", ".", "CanCommit", "(", "WriteStamp", "writeStamp", ")", "{", "var", "locals", "=", "_localDict", ".", "Value", ";", "locals", ".", "Locked", "=", "true", ";", "if", "(", "locals", ".", "Items", ".", "Any", "(", "kvp", "=>", "{", "ItemKeeper", "v", ";", "return", "_writeStamps", ".", "ContainsKey", "(", "kvp", ".", "Key", ")", "||", "(", "_dict", ".", "TryGetValue", "(", "kvp", ".", "Key", ",", "out", "v", ")", "&&", "v", ".", "Version", ">", "Shield", ".", "ReadStamp", ")", ";", "}", ")", ")", "return", "false", ";", "else", "{", "if", "(", "locals", ".", "HasChanges", ")", "foreach", "(", "var", "kvp", "in", "locals", ".", "Items", ")", "if", "(", "kvp", ".", "Value", "!=", "null", ")", "_writeStamps", "[", "kvp", ".", "Key", "]", "=", "writeStamp", ";", "return", "true", ";", "}", "}", "private", "ConcurrentQueue", "<", "Tuple", "<", "long", ",", "List", "<", "TKey", ">", ">", ">", "_copies", "=", "new", "ConcurrentQueue", "<", "Tuple", "<", "long", ",", "List", "<", "TKey", ">", ">", ">", "(", ")", ";", "void", "IShielded", ".", "Commit", "(", ")", "{", "var", "locals", "=", "_localDict", ".", "Value", ";", "if", "(", "locals", ".", "HasChanges", ")", "{", "long", "?", "version", "=", "null", ";", "var", "copyList", "=", "new", "List", "<", "TKey", ">", "(", ")", ";", "foreach", "(", "var", "kvp", "in", "_localDict", ".", "Value", ".", "Items", ")", "{", "if", "(", "kvp", ".", "Value", "==", "null", ")", "continue", ";", "if", "(", "version", "==", "null", ")", "version", "=", "_writeStamps", "[", "kvp", ".", "Key", "]", ".", "Version", ";", "ItemKeeper", "v", "=", "null", ";", "if", "(", "_dict", ".", "TryGetValue", "(", "kvp", ".", "Key", ",", "out", "v", ")", ")", "copyList", ".", "Add", "(", "kvp", ".", "Key", ")", ";", "var", "newCurrent", "=", "kvp", ".", "Value", ";", "if", "(", "!", "newCurrent", ".", "Empty", "||", "v", "!=", "null", ")", "{", "newCurrent", ".", "Version", "=", "(", "long", ")", "version", ";", "newCurrent", ".", "Older", "=", "v", ";", "lock", "(", "_dict", ")", "_dict", "[", "kvp", ".", "Key", "]", "=", "newCurrent", ";", "}", "WriteStamp", "ws", ";", "_writeStamps", ".", "TryRemove", "(", "kvp", ".", "Key", ",", "out", "ws", ")", ";", "}", "if", "(", "copyList", ".", "Count", ">", "0", ")", "_copies", ".", "Enqueue", "(", "Tuple", ".", "Create", "(", "(", "long", ")", "version", ",", "copyList", ")", ")", ";", "}", "_localDict", ".", "Release", "(", ")", ";", "}", "void", "IShielded", ".", "Rollback", "(", ")", "{", "if", "(", "!", "_localDict", ".", "HasValue", ")", "return", ";", "var", "locals", "=", "_localDict", ".", "Value", ";", "if", "(", "locals", ".", "HasChanges", ")", "{", "WriteStamp", "ws", ";", "var", "ctx", "=", "Shield", ".", "Context", ";", "foreach", "(", "var", "kvp", "in", "locals", ".", "Items", ")", "{", "if", "(", "kvp", ".", "Value", "!=", "null", "&&", "_writeStamps", ".", "TryGetValue", "(", "kvp", ".", "Key", ",", "out", "ws", ")", "&&", "ws", ".", "Locker", "==", "ctx", ")", "{", "_writeStamps", ".", "TryRemove", "(", "kvp", ".", "Key", ",", "out", "ws", ")", ";", "}", "}", "}", "_localDict", ".", "Release", "(", ")", ";", "}", "void", "IShielded", ".", "TrimCopies", "(", "long", "smallestOpenTransactionId", ")", "{", "Tuple", "<", "long", ",", "List", "<", "TKey", ">", ">", "item", ";", "while", "(", "_copies", ".", "TryPeek", "(", "out", "item", ")", "&&", "item", ".", "Item1", "<=", "smallestOpenTransactionId", ")", "{", "_copies", ".", "TryDequeue", "(", "out", "item", ")", ";", "foreach", "(", "var", "key", "in", "item", ".", "Item2", ")", "{", "ItemKeeper", "point", ";", "if", "(", "!", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "point", ")", ")", "continue", ";", "ItemKeeper", "pointNewer", "=", "null", ";", "while", "(", "point", "!=", "null", "&&", "point", ".", "Version", ">", "smallestOpenTransactionId", ")", "{", "pointNewer", "=", "point", ";", "point", "=", "point", ".", "Older", ";", "}", "if", "(", "point", "!=", "null", ")", "{", "point", ".", "Older", "=", "null", ";", "if", "(", "point", ".", "Empty", ")", "{", "if", "(", "pointNewer", "!=", "null", ")", "pointNewer", ".", "Older", "=", "null", ";", "else", "{", "lock", "(", "_dict", ")", "{", "ItemKeeper", "k", ";", "if", "(", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "k", ")", "&&", "k", "==", "point", ")", "_dict", ".", "TryRemove", "(", "key", ",", "out", "k", ")", ";", "}", "}", "}", "}", "}", "}", "}", "System", ".", "Collections", ".", "IEnumerator", "System", ".", "Collections", ".", "IEnumerable", ".", "GetEnumerator", "(", ")", "{", "return", "(", "(", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", ")", "this", ")", ".", "GetEnumerator", "(", ")", ";", "}", "public", "IEnumerator", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", "GetEnumerator", "(", ")", "{", "Shield", ".", "AssertInTransaction", "(", ")", ";", "var", "keys", "=", "_localDict", ".", "HasValue", "?", "_dict", ".", "Keys", ".", "Union", "(", "_localDict", ".", "Value", ".", "Items", ".", "Keys", ",", "_comparer", ")", ":", "_dict", ".", "Keys", ";", "foreach", "(", "var", "key", "in", "keys", ")", "{", "var", "v", "=", "Read", "(", "key", ")", ";", "if", "(", "v", "==", "null", "||", "v", ".", "Empty", ")", "continue", ";", "yield", "return", "new", "KeyValuePair", "<", "TKey", ",", "TItem", ">", "(", "key", ",", "v", ".", "Value", ")", ";", "}", "}", "public", "void", "Clear", "(", ")", "{", "Shield", ".", "AssertInTransaction", "(", ")", ";", "foreach", "(", "var", "key", "in", "Keys", ")", "Remove", "(", "key", ")", ";", "}", "public", "void", "CopyTo", "(", "KeyValuePair", "<", "TKey", ",", "TItem", ">", "[", "]", "array", ",", "int", "arrayIndex", ")", "{", "Shield", ".", "InTransaction", "(", "(", ")", "=>", "{", "foreach", "(", "KeyValuePair", "<", "TKey", ",", "TItem", ">", "kvp", "in", "this", ")", "array", "[", "arrayIndex", "++", "]", "=", "kvp", ";", "}", ")", ";", "}", "public", "void", "Add", "(", "TKey", "key", ",", "TItem", "value", ")", "{", "Shield", ".", "AssertInTransaction", "(", ")", ";", "if", "(", "ContainsKey", "(", "key", ")", ")", "throw", "new", "ArgumentException", "(", "\"", "The given key is already present in the dictionary.", "\"", ")", ";", "this", "[", "key", "]", "=", "value", ";", "}", "public", "bool", "ContainsKey", "(", "TKey", "key", ")", "{", "ItemKeeper", "v", ";", "if", "(", "!", "Shield", ".", "IsInTransaction", ")", "return", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "v", ")", "&&", "v", "!=", "null", "&&", "!", "v", ".", "Empty", ";", "v", "=", "Read", "(", "key", ")", ";", "return", "v", "!=", "null", "&&", "!", "v", ".", "Empty", ";", "}", "public", "bool", "Remove", "(", "TKey", "key", ")", "{", "Shield", ".", "AssertInTransaction", "(", ")", ";", "var", "keeper", "=", "PrepareWrite", "(", "key", ")", ";", "if", "(", "keeper", "!=", "null", ")", "{", "var", "res", "=", "!", "keeper", ".", "Empty", ";", "keeper", ".", "Empty", "=", "true", ";", "keeper", ".", "Value", "=", "default", ";", "return", "res", ";", "}", "var", "old", "=", "CurrentTransactionOldValue", "(", "key", ")", ";", "if", "(", "old", "==", "null", "||", "old", ".", "Empty", ")", "return", "false", ";", "var", "locals", "=", "_localDict", ".", "Value", ";", "locals", ".", "Items", "[", "key", "]", "=", "new", "ItemKeeper", "{", "Empty", "=", "true", "}", ";", "locals", ".", "HasChanges", "=", "true", ";", "return", "true", ";", "}", "public", "bool", "TryGetValue", "(", "TKey", "key", ",", "out", "TItem", "value", ")", "{", "ItemKeeper", "v", ";", "if", "(", "!", "Shield", ".", "IsInTransaction", ")", "{", "if", "(", "_dict", ".", "TryGetValue", "(", "key", ",", "out", "v", ")", "&&", "!", "v", ".", "Empty", ")", "{", "value", "=", "v", ".", "Value", ";", "return", "true", ";", "}", "value", "=", "default", "(", "TItem", ")", ";", "return", "false", ";", "}", "v", "=", "Read", "(", "key", ")", ";", "if", "(", "v", "!=", "null", "&&", "!", "v", ".", "Empty", ")", "{", "value", "=", "v", ".", "Value", ";", "return", "true", ";", "}", "value", "=", "default", "(", "TItem", ")", ";", "return", "false", ";", "}", "public", "ICollection", "<", "TKey", ">", "Keys", "{", "get", "{", "return", "Shield", ".", "InTransaction", "(", "(", ")", "=>", "(", "(", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", ")", "this", ")", ".", "Select", "(", "kvp", "=>", "kvp", ".", "Key", ")", ".", "ToList", "(", ")", ")", ";", "}", "}", "public", "ICollection", "<", "TItem", ">", "Values", "{", "get", "{", "return", "Shield", ".", "InTransaction", "(", "(", ")", "=>", "(", "(", "IEnumerable", "<", "KeyValuePair", "<", "TKey", ",", "TItem", ">", ">", ")", "this", ")", ".", "Select", "(", "kvp", "=>", "kvp", ".", "Value", ")", ".", "ToList", "(", ")", ")", ";", "}", "}", "}" ]
A transactional dictionary - adding, removing, replacing items are transactional, but anything done to the items is not unless they are Shielded themselves.
[ "A", "transactional", "dictionary", "-", "adding", "removing", "replacing", "items", "are", "transactional", "but", "anything", "done", "to", "the", "items", "is", "not", "unless", "they", "are", "Shielded", "themselves", "." ]
[ "/// <summary>", "/// Initializes a new instance.", "/// </summary>", "/// <param name=\"items\">Initial items.</param>", "/// <param name=\"owner\">If this is given, then in WhenCommitting subscriptions", "/// this shielded will report its owner instead of itself.</param>", "/// <param name=\"comparer\">Equality comparer for keys.</param>", "/// <summary>", "/// Initializes a new instance.", "/// </summary>", "/// <param name=\"comparer\">Equality comparer for keys.</param>", "// because the check above is much stricter than anything", "/// <summary>", "/// Since the dictionary is just one field to the Shield class, we internally check, if", "/// the access is happening while locked, whether the access is safe.", "/// </summary>", "/// <summary>", "/// Returns an existing local entry, if any.", "/// </summary>", "/// <summary>", "/// Gets or sets the value under the specified key.", "/// </summary>", "/// <summary>", "/// An enumerable of keys for which the current transaction made changes in the dictionary.", "/// Safely accessible from <see cref=\"Shield.WhenCommitting\"/> subscriptions. NB that", "/// this also includes keys which were removed from the dictionary.", "/// </summary>", "/// <summary>", "/// An enumerable of keys which the current transaction read or wrote into.", "/// Safely accessible from <see cref=\"Shield.WhenCommitting\"/> subscriptions. NB that", "/// this also includes keys which were removed from the dictionary.", "/// </summary>", "// locals were prepared when we enlisted.", "// touch only the ones we plan to change", "// look at this negated - if the new value is empty, and the old value is null, then we", "// need not add anything to the underlying dict.", "// NB the \"smallest transaction\" and others can freely read while", "// we're doing this.", "// point is the last accessible - his Older is not needed.", "//((ICollection<KeyValuePair<TKey, ItemKeeper>>)_dict)", "// .Remove(new KeyValuePair<TKey, ItemKeeper>(key, point));", "/// <summary>", "/// Get an enumerator for the dictionary contents. Iterating over this dictionary", "/// does not conflict with other transactions that are adding new items, so it", "/// is not fully safe. For read-only transactions, however, no problem.", "/// </summary>", "/// <summary>", "/// Removes all items, but one by one.", "/// </summary>", "/// <summary>", "/// Copy the dictionary contents to an array. Involves enumerating, might not get all", "/// items which should have been visible at the time of your commit. This does not", "/// affect read-only transactions, or those writers that do not logically depend on", "/// seeing all items.", "/// </summary>", "/// <summary>", "/// Add the specified key and value to the dictionary.", "/// </summary>", "/// <exception cref=\"ArgumentException\">Thrown if the key is already present in the dictionary.</exception>", "/// <summary>", "/// Check if the dictionary contains the given key.", "/// </summary>", "/// <summary>", "/// Remove the specified key from the collection.", "/// </summary>", "/// <summary>", "/// Safe read based on the key - returns true if the key is present, and", "/// then also returns the value stored under that key through the out parameter.", "/// </summary>", "/// <summary>", "/// Get a collection of all the keys in the dictionary. Can be used out of transactions.", "/// The result is a copy, it will not be updated if the dictionary is later changed.", "/// Like all enumerating operations on this type, it is not completely safe, unless", "/// your transaction is read-only.", "/// </summary>", "/// <summary>", "/// Get a collection of all the values in the dictionary. Can be used out of transactions.", "/// The result is a copy, it will not be updated if the dictionary is later changed.", "/// Like all enumerating operations on this type, it is not completely safe, unless", "/// your transaction is read-only.", "/// </summary>" ]
[ { "param": "IShielded", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IShielded", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
22
2,659
143
38a41e10d66fcdf9c50c7c1b195cf82ef69a783e
mapbox/mr-ui
src/components/modal/modal.js
[ "BSD-2-Clause" ]
JavaScript
Modal
/** * An accessible modal dialog. * * To get a standard button arrangement at the bottom of the modal, use the * `primaryAction`, `secondaryAction`, and `tertiaryAction` props. * * This modal *traps focus within it*. You should be aware of that, because it * can sometimes introduce a hurdle when integrating the modal with other * things, especially third-party libraries. But it's an essential UX feature. */
An accessible modal dialog. This modal *traps focus within it*. You should be aware of that, because it can sometimes introduce a hurdle when integrating the modal with other things, especially third-party libraries. But it's an essential UX feature.
[ "An", "accessible", "modal", "dialog", ".", "This", "modal", "*", "traps", "focus", "within", "it", "*", ".", "You", "should", "be", "aware", "of", "that", "because", "it", "can", "sometimes", "introduce", "a", "hurdle", "when", "integrating", "the", "modal", "with", "other", "things", "especially", "third", "-", "party", "libraries", ".", "But", "it", "'", "s", "an", "essential", "UX", "feature", "." ]
class Modal extends React.Component { constructor(props) { super(props); this.setDialogEl = this.setDialogEl.bind(this); } componentDidMount() { // After the modal has mounted, it will receive focus (unless initialFocus) // is set. If it is taller than the viewport, the browser will scroll down // so the top of the modal is at the top of the viewport, instead of // staying at the top where you can see the nice padding. To show the // padding, we get the underlay element and scroll to the top of that // right after the component mounts. if (!this.dialogEl || typeof window === 'undefined') return; // A slight delay is necessary so this happens after focus is placed. this.scrollTimeout = getWindow().setTimeout(() => { const offsetParent = this.dialogEl.offsetParent; if (offsetParent.tagName === 'BODY' || offsetParent.tagName === 'HTML') { return; } offsetParent.scrollTop = 0; }, 0); } componentWillUnmount() { if (typeof window === 'undefined') return; getWindow().clearTimeout(this.scrollTimeout); } setDialogEl(el) { this.dialogEl = el; } renderActions() { const { primaryAction, secondaryAction, tertiaryAction } = this.props; if (!primaryAction) { return null; } return ( <div className="mt24"> <ModalActions primaryAction={primaryAction} secondaryAction={secondaryAction} tertiaryAction={tertiaryAction} /> </div> ); } render() { const { props } = this; let closeButton = null; if (props.onExit) { closeButton = ( <div className="absolute top right"> <Tooltip block={true} content="Close"> <button aria-label="Close" type="button" className="btn btn--transparent unround-t unround-br color-gray py12 px12" onClick={props.onExit} data-test="modal-close" > <Icon name="close" /> </button> </Tooltip> </div> ); } let widthClass = ''; if (props.size === 'small') { widthClass = 'w360'; } else if (props.size === 'large') { widthClass = 'w600'; } const containerClasses = classnames( `relative wmax-full ${widthClass} bg-white round`, { 'px36 py36': props.padding === 'large' } ); const dialogBody = ( <div ref={this.setDialogEl} className={containerClasses}> {props.children} {this.renderActions()} {closeButton} </div> ); const modalProps = { titleText: props.accessibleTitle, getApplicationNode: props.getApplicationNode, underlayProps: { 'data-popover-ignore-clicks': true }, underlayClass: 'bg-darken50 px12 py12 px60-mm py60-mm ', underlayStyle: { zIndex: 1 }, alert: props.alert }; if (props.onExit) { modalProps.onExit = props.onExit; } if (props.initialFocus) { modalProps.initialFocus = props.initialFocus; } else { modalProps.focusDialog = true; } if (props.focusTrapPaused) { modalProps.focusTrapPaused = true; } if (!props.allowEventBubbling) { // stopPropagation prevents child modals from closing parent modals when nesting return ( <EventTrap> <AriaModal {...modalProps}>{dialogBody}</AriaModal> </EventTrap> ); } return <AriaModal {...modalProps}>{dialogBody}</AriaModal>; } }
[ "class", "Modal", "extends", "React", ".", "Component", "{", "constructor", "(", "props", ")", "{", "super", "(", "props", ")", ";", "this", ".", "setDialogEl", "=", "this", ".", "setDialogEl", ".", "bind", "(", "this", ")", ";", "}", "componentDidMount", "(", ")", "{", "if", "(", "!", "this", ".", "dialogEl", "||", "typeof", "window", "===", "'undefined'", ")", "return", ";", "this", ".", "scrollTimeout", "=", "getWindow", "(", ")", ".", "setTimeout", "(", "(", ")", "=>", "{", "const", "offsetParent", "=", "this", ".", "dialogEl", ".", "offsetParent", ";", "if", "(", "offsetParent", ".", "tagName", "===", "'BODY'", "||", "offsetParent", ".", "tagName", "===", "'HTML'", ")", "{", "return", ";", "}", "offsetParent", ".", "scrollTop", "=", "0", ";", "}", ",", "0", ")", ";", "}", "componentWillUnmount", "(", ")", "{", "if", "(", "typeof", "window", "===", "'undefined'", ")", "return", ";", "getWindow", "(", ")", ".", "clearTimeout", "(", "this", ".", "scrollTimeout", ")", ";", "}", "setDialogEl", "(", "el", ")", "{", "this", ".", "dialogEl", "=", "el", ";", "}", "renderActions", "(", ")", "{", "const", "{", "primaryAction", ",", "secondaryAction", ",", "tertiaryAction", "}", "=", "this", ".", "props", ";", "if", "(", "!", "primaryAction", ")", "{", "return", "null", ";", "}", "return", "(", "<", "div", "className", "=", "\"mt24\"", ">", "\n ", "<", "ModalActions", "primaryAction", "=", "{", "primaryAction", "}", "secondaryAction", "=", "{", "secondaryAction", "}", "tertiaryAction", "=", "{", "tertiaryAction", "}", "/", ">", "\n ", "<", "/", "div", ">", ")", ";", "}", "render", "(", ")", "{", "const", "{", "props", "}", "=", "this", ";", "let", "closeButton", "=", "null", ";", "if", "(", "props", ".", "onExit", ")", "{", "closeButton", "=", "(", "<", "div", "className", "=", "\"absolute top right\"", ">", "\n ", "<", "Tooltip", "block", "=", "{", "true", "}", "content", "=", "\"Close\"", ">", "\n ", "<", "button", "aria-label", "=", "\"Close\"", "type", "=", "\"button\"", "className", "=", "\"btn btn--transparent unround-t unround-br color-gray py12 px12\"", "onClick", "=", "{", "props", ".", "onExit", "}", "data-test", "=", "\"modal-close\"", ">", "\n ", "<", "Icon", "name", "=", "\"close\"", "/", ">", "\n ", "<", "/", "button", ">", "\n ", "<", "/", "Tooltip", ">", "\n ", "<", "/", "div", ">", ")", ";", "}", "let", "widthClass", "=", "''", ";", "if", "(", "props", ".", "size", "===", "'small'", ")", "{", "widthClass", "=", "'w360'", ";", "}", "else", "if", "(", "props", ".", "size", "===", "'large'", ")", "{", "widthClass", "=", "'w600'", ";", "}", "const", "containerClasses", "=", "classnames", "(", "`", "${", "widthClass", "}", "`", ",", "{", "'px36 py36'", ":", "props", ".", "padding", "===", "'large'", "}", ")", ";", "const", "dialogBody", "=", "(", "<", "div", "ref", "=", "{", "this", ".", "setDialogEl", "}", "className", "=", "{", "containerClasses", "}", ">", "\n ", "{", "props", ".", "children", "}", "\n ", "{", "this", ".", "renderActions", "(", ")", "}", "\n ", "{", "closeButton", "}", "\n ", "<", "/", "div", ">", ")", ";", "const", "modalProps", "=", "{", "titleText", ":", "props", ".", "accessibleTitle", ",", "getApplicationNode", ":", "props", ".", "getApplicationNode", ",", "underlayProps", ":", "{", "'data-popover-ignore-clicks'", ":", "true", "}", ",", "underlayClass", ":", "'bg-darken50 px12 py12 px60-mm py60-mm '", ",", "underlayStyle", ":", "{", "zIndex", ":", "1", "}", ",", "alert", ":", "props", ".", "alert", "}", ";", "if", "(", "props", ".", "onExit", ")", "{", "modalProps", ".", "onExit", "=", "props", ".", "onExit", ";", "}", "if", "(", "props", ".", "initialFocus", ")", "{", "modalProps", ".", "initialFocus", "=", "props", ".", "initialFocus", ";", "}", "else", "{", "modalProps", ".", "focusDialog", "=", "true", ";", "}", "if", "(", "props", ".", "focusTrapPaused", ")", "{", "modalProps", ".", "focusTrapPaused", "=", "true", ";", "}", "if", "(", "!", "props", ".", "allowEventBubbling", ")", "{", "return", "(", "<", "EventTrap", ">", "\n ", "<", "AriaModal", "{", "...", "modalProps", "}", ">", "{", "dialogBody", "}", "<", "/", "AriaModal", ">", "\n ", "<", "/", "EventTrap", ">", ")", ";", "}", "return", "<", "AriaModal", "{", "...", "modalProps", "}", ">", "{", "dialogBody", "}", "<", "/", "AriaModal", ">", ";", "}", "}" ]
An accessible modal dialog.
[ "An", "accessible", "modal", "dialog", "." ]
[ "// After the modal has mounted, it will receive focus (unless initialFocus)", "// is set. If it is taller than the viewport, the browser will scroll down", "// so the top of the modal is at the top of the viewport, instead of", "// staying at the top where you can see the nice padding. To show the", "// padding, we get the underlay element and scroll to the top of that", "// right after the component mounts.", "// A slight delay is necessary so this happens after focus is placed.", "// stopPropagation prevents child modals from closing parent modals when nesting" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
852
94
fc854e694df98cf8bd92c2afd8973434bf995e30
isabella232/feedbunch
FeedBunch-app/app/models/deleted_entry.rb
[ "MIT" ]
Ruby
DeletedEntry
## # Deleted Entry model. Each instance of this class represents a feed entry that has been deleted from the # database during an automated cleanup. # # Each deleted_entry belongs to exactly one feed. # # When an entry is deleted during an automated cleanup, a new record is inserted in the deleted_entries table. # The "feed_id", "guid" and "unique_hash" attributes of the new deleted_entry record are the same as those of the deleted # entry. This means that deleted entries still occupy some space in the database, but much less because the # entry content is not kept. # # Each deleted_entry is uniquely identified by its guid and unique_hash within the scope of a given feed. # Duplicate guids are not allowed for a given feed. Duplicate unique_hashes are not allowed for a given feed, # with the exception that multiple deleted_entries with nil unique_hash are allowed for a given feed (for backward # compatibility reasons). # # A deleted_entry with the same feed_id and either guid or unique_hash as an already existing entry is not valid and won't be # saved in the database (it would indicate an entry which is at once deleted and not deleted). # # Attributes of the model: # - feed_id: ID of the feed to which the deleted entry belonged. # - guid: guid of the deleted entry. # - unique_hash: MD5 hash of the content+summary+title of the deleted entry # # The unique_hash attribute is not mandatory (can be nil) for backwards compatibility reasons: we cannot know calculate # the unique hash for already deleted entries, so the attribute is left nil for older deleted entries.
Deleted Entry model. Each instance of this class represents a feed entry that has been deleted from the database during an automated cleanup. Each deleted_entry belongs to exactly one feed. When an entry is deleted during an automated cleanup, a new record is inserted in the deleted_entries table. Each deleted_entry is uniquely identified by its guid and unique_hash within the scope of a given feed. Duplicate guids are not allowed for a given feed. Duplicate unique_hashes are not allowed for a given feed, with the exception that multiple deleted_entries with nil unique_hash are allowed for a given feed (for backward compatibility reasons). A deleted_entry with the same feed_id and either guid or unique_hash as an already existing entry is not valid and won't be saved in the database (it would indicate an entry which is at once deleted and not deleted). Attributes of the model: feed_id: ID of the feed to which the deleted entry belonged. guid: guid of the deleted entry. unique_hash: MD5 hash of the content+summary+title of the deleted entry The unique_hash attribute is not mandatory (can be nil) for backwards compatibility reasons: we cannot know calculate the unique hash for already deleted entries, so the attribute is left nil for older deleted entries.
[ "Deleted", "Entry", "model", ".", "Each", "instance", "of", "this", "class", "represents", "a", "feed", "entry", "that", "has", "been", "deleted", "from", "the", "database", "during", "an", "automated", "cleanup", ".", "Each", "deleted_entry", "belongs", "to", "exactly", "one", "feed", ".", "When", "an", "entry", "is", "deleted", "during", "an", "automated", "cleanup", "a", "new", "record", "is", "inserted", "in", "the", "deleted_entries", "table", ".", "Each", "deleted_entry", "is", "uniquely", "identified", "by", "its", "guid", "and", "unique_hash", "within", "the", "scope", "of", "a", "given", "feed", ".", "Duplicate", "guids", "are", "not", "allowed", "for", "a", "given", "feed", ".", "Duplicate", "unique_hashes", "are", "not", "allowed", "for", "a", "given", "feed", "with", "the", "exception", "that", "multiple", "deleted_entries", "with", "nil", "unique_hash", "are", "allowed", "for", "a", "given", "feed", "(", "for", "backward", "compatibility", "reasons", ")", ".", "A", "deleted_entry", "with", "the", "same", "feed_id", "and", "either", "guid", "or", "unique_hash", "as", "an", "already", "existing", "entry", "is", "not", "valid", "and", "won", "'", "t", "be", "saved", "in", "the", "database", "(", "it", "would", "indicate", "an", "entry", "which", "is", "at", "once", "deleted", "and", "not", "deleted", ")", ".", "Attributes", "of", "the", "model", ":", "feed_id", ":", "ID", "of", "the", "feed", "to", "which", "the", "deleted", "entry", "belonged", ".", "guid", ":", "guid", "of", "the", "deleted", "entry", ".", "unique_hash", ":", "MD5", "hash", "of", "the", "content", "+", "summary", "+", "title", "of", "the", "deleted", "entry", "The", "unique_hash", "attribute", "is", "not", "mandatory", "(", "can", "be", "nil", ")", "for", "backwards", "compatibility", "reasons", ":", "we", "cannot", "know", "calculate", "the", "unique", "hash", "for", "already", "deleted", "entries", "so", "the", "attribute", "is", "left", "nil", "for", "older", "deleted", "entries", "." ]
class DeletedEntry < ApplicationRecord belongs_to :feed validates :feed_id, presence: true validates :guid, presence: true, uniqueness: {case_sensitive: true, scope: :feed_id} validates :unique_hash, uniqueness: {case_sensitive: true, scope: :feed_id, allow_nil: true} validate :entry_deleted private ## # Validate that the entry has been deleted (there isn't an entry record with the # same feed_id and either guid or unique_hash) def entry_deleted if Entry.where('feed_id = ? AND (guid = ? OR unique_hash = ?)', self.feed_id, self.guid, self.unique_hash).exists? Rails.logger.warn "Failed attempt to mark as deleted existing entry - guid: #{self.try :guid}, unique_hash: #{self.try :unique_hash}, published: #{self.try :published}, feed_id: #{self.feed_id}, feed title: #{self.feed.title}" errors.add :base, 'entry not deleted' end end end
[ "class", "DeletedEntry", "<", "ApplicationRecord", "belongs_to", ":feed", "validates", ":feed_id", ",", "presence", ":", "true", "validates", ":guid", ",", "presence", ":", "true", ",", "uniqueness", ":", "{", "case_sensitive", ":", "true", ",", "scope", ":", ":feed_id", "}", "validates", ":unique_hash", ",", "uniqueness", ":", "{", "case_sensitive", ":", "true", ",", "scope", ":", ":feed_id", ",", "allow_nil", ":", "true", "}", "validate", ":entry_deleted", "private", "def", "entry_deleted", "if", "Entry", ".", "where", "(", "'feed_id = ? AND (guid = ? OR unique_hash = ?)'", ",", "self", ".", "feed_id", ",", "self", ".", "guid", ",", "self", ".", "unique_hash", ")", ".", "exists?", "Rails", ".", "logger", ".", "warn", "\"Failed attempt to mark as deleted existing entry - guid: #{self.try :guid}, unique_hash: #{self.try :unique_hash}, published: #{self.try :published}, feed_id: #{self.feed_id}, feed title: #{self.feed.title}\"", "errors", ".", "add", ":base", ",", "'entry not deleted'", "end", "end", "end" ]
Deleted Entry model.
[ "Deleted", "Entry", "model", "." ]
[ "##", "# Validate that the entry has been deleted (there isn't an entry record with the", "# same feed_id and either guid or unique_hash)" ]
[ { "param": "ApplicationRecord", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ApplicationRecord", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
224
339
63e7b320fd1fa72b1d574832215d9de58fd8f491
cobaltblueocean/Fudge-Java
src/org/fudgemsg/FudgeMsgReader.java
[ "Apache-2.0" ]
Java
FudgeMsgReader
/** * A reader for returning whole Fudge messages ({@link FudgeFieldContainer} instances) from an underlying {@link FudgeStreamReader} instance. * This implementation constructs the whole Fudge message in memory before returning to the caller. This is provided for convenience - greater * runtime efficiency may be possible by working directly with the {@link FudgeStreamReader} to process stream elements as they are decoded. * * @author Andrew Griffin */
A reader for returning whole Fudge messages ( FudgeFieldContainer instances) from an underlying FudgeStreamReader instance. This implementation constructs the whole Fudge message in memory before returning to the caller. This is provided for convenience - greater runtime efficiency may be possible by working directly with the FudgeStreamReader to process stream elements as they are decoded. @author Andrew Griffin
[ "A", "reader", "for", "returning", "whole", "Fudge", "messages", "(", "FudgeFieldContainer", "instances", ")", "from", "an", "underlying", "FudgeStreamReader", "instance", ".", "This", "implementation", "constructs", "the", "whole", "Fudge", "message", "in", "memory", "before", "returning", "to", "the", "caller", ".", "This", "is", "provided", "for", "convenience", "-", "greater", "runtime", "efficiency", "may", "be", "possible", "by", "working", "directly", "with", "the", "FudgeStreamReader", "to", "process", "stream", "elements", "as", "they", "are", "decoded", ".", "@author", "Andrew", "Griffin" ]
public class FudgeMsgReader { /** * The underlying source of Fudge elements. */ private final FudgeStreamReader _streamReader; /** * An envelope buffer for reading in the current message. {@link #hasNext} will read the envelope header, and create this object * with a {@link MutableFudgeFieldContainer} attached to it. The full call to {@link nextMessage} or {@link #nextMessageEnvelope} will * process the message fields. */ private FudgeMsgEnvelope _currentEnvelope = null; /** * Creates a new {@link FudgeMsgReader} around an existing {@link FudgeStreamReader}. * * @param streamReader the source of Fudge stream elements to read */ public FudgeMsgReader (final FudgeStreamReader streamReader) { if (streamReader == null) { throw new NullPointerException ("streamReader cannot be null"); } _streamReader = streamReader; } /** * Closes this {@link FudgeMsgReader} and the underlying {@link FudgeStreamReader}. */ public void close () { if (_streamReader == null) return; _streamReader.close (); } /** * Returns the {@link FudgeContext} associated with the underlying source. * * @return the {@code FudgeContext} */ public FudgeContext getFudgeContext () { final FudgeStreamReader reader = getStreamReader (); if (reader == null) return null; return reader.getFudgeContext (); } /** * Returns the underlying {@link FudgeStreamReader} for this message reader. * * @return the {@code FudgeStreamReader} */ protected FudgeStreamReader getStreamReader () { return _streamReader; } /** * Returns true if there are more messages to read from the underlying source. * * @return {@code true} if {@link #nextMessage()} or {@link #nextMessageEnvelope()} will return data */ public boolean hasNext () { if (_currentEnvelope != null) return true; _currentEnvelope = readMessageEnvelope (); return (_currentEnvelope != null); } /** * Reads the next message, discarding the envelope. * * @return the message read without the envelope */ public FudgeFieldContainer nextMessage () { final FudgeMsgEnvelope msgEnv = nextMessageEnvelope (); if (msgEnv == null) return null; return msgEnv.getMessage (); } /** * Reads the next message, returning the envelope. * * @return the {@link FudgeMsgEnvelope} */ public FudgeMsgEnvelope nextMessageEnvelope () { FudgeMsgEnvelope msgEnv; if (_currentEnvelope == null) { msgEnv = readMessageEnvelope (); if (msgEnv == null) return null; } else { msgEnv = _currentEnvelope; _currentEnvelope = null; } processFields ((MutableFudgeFieldContainer)msgEnv.getMessage ()); return msgEnv; } /** * Reads the next message envelope from the underlying stream. No fields are read. * * @return the {@link FudgeMsgEnvelope} read */ protected FudgeMsgEnvelope readMessageEnvelope () { if (getStreamReader ().hasNext () == false) { return null; } FudgeStreamElement element = getStreamReader ().next(); if(element == null) { return null; } if(element != FudgeStreamElement.MESSAGE_ENVELOPE) { throw new IllegalArgumentException("First element in encoding stream wasn't a message element."); } MutableFudgeFieldContainer msg = getFudgeContext().newMessage(); FudgeMsgEnvelope envelope = new FudgeMsgEnvelope (msg, getStreamReader ().getSchemaVersion(), getStreamReader ().getProcessingDirectives ()); return envelope; } /** * Processes all of the fields from the current message (or sub-message) in the stream, adding them to the supplied container. * * @param msg container to add fields read to */ protected void processFields(MutableFudgeFieldContainer msg) { final FudgeStreamReader reader = getStreamReader (); while(reader.hasNext()) { FudgeStreamElement element = reader.next(); switch(element) { case SIMPLE_FIELD: msg.add(reader.getFieldName(), reader.getFieldOrdinal(), reader.getFieldType(), reader.getFieldValue()); break; case SUBMESSAGE_FIELD_START: MutableFudgeFieldContainer subMsg = getFudgeContext().newMessage (); msg.add(reader.getFieldName(), reader.getFieldOrdinal(), FudgeMsgFieldType.INSTANCE, subMsg); processFields(subMsg); break; case SUBMESSAGE_FIELD_END: return; } } } }
[ "public", "class", "FudgeMsgReader", "{", "/**\n * The underlying source of Fudge elements.\n */", "private", "final", "FudgeStreamReader", "_streamReader", ";", "/**\n * An envelope buffer for reading in the current message. {@link #hasNext} will read the envelope header, and create this object\n * with a {@link MutableFudgeFieldContainer} attached to it. The full call to {@link nextMessage} or {@link #nextMessageEnvelope} will\n * process the message fields.\n */", "private", "FudgeMsgEnvelope", "_currentEnvelope", "=", "null", ";", "/**\n * Creates a new {@link FudgeMsgReader} around an existing {@link FudgeStreamReader}.\n * \n * @param streamReader the source of Fudge stream elements to read\n */", "public", "FudgeMsgReader", "(", "final", "FudgeStreamReader", "streamReader", ")", "{", "if", "(", "streamReader", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"", "streamReader cannot be null", "\"", ")", ";", "}", "_streamReader", "=", "streamReader", ";", "}", "/**\n * Closes this {@link FudgeMsgReader} and the underlying {@link FudgeStreamReader}.\n */", "public", "void", "close", "(", ")", "{", "if", "(", "_streamReader", "==", "null", ")", "return", ";", "_streamReader", ".", "close", "(", ")", ";", "}", "/**\n * Returns the {@link FudgeContext} associated with the underlying source.\n * \n * @return the {@code FudgeContext}\n */", "public", "FudgeContext", "getFudgeContext", "(", ")", "{", "final", "FudgeStreamReader", "reader", "=", "getStreamReader", "(", ")", ";", "if", "(", "reader", "==", "null", ")", "return", "null", ";", "return", "reader", ".", "getFudgeContext", "(", ")", ";", "}", "/**\n * Returns the underlying {@link FudgeStreamReader} for this message reader.\n * \n * @return the {@code FudgeStreamReader}\n */", "protected", "FudgeStreamReader", "getStreamReader", "(", ")", "{", "return", "_streamReader", ";", "}", "/**\n * Returns true if there are more messages to read from the underlying source.\n * \n * @return {@code true} if {@link #nextMessage()} or {@link #nextMessageEnvelope()} will return data\n */", "public", "boolean", "hasNext", "(", ")", "{", "if", "(", "_currentEnvelope", "!=", "null", ")", "return", "true", ";", "_currentEnvelope", "=", "readMessageEnvelope", "(", ")", ";", "return", "(", "_currentEnvelope", "!=", "null", ")", ";", "}", "/**\n * Reads the next message, discarding the envelope.\n * \n * @return the message read without the envelope\n */", "public", "FudgeFieldContainer", "nextMessage", "(", ")", "{", "final", "FudgeMsgEnvelope", "msgEnv", "=", "nextMessageEnvelope", "(", ")", ";", "if", "(", "msgEnv", "==", "null", ")", "return", "null", ";", "return", "msgEnv", ".", "getMessage", "(", ")", ";", "}", "/**\n * Reads the next message, returning the envelope.\n * \n * @return the {@link FudgeMsgEnvelope}\n */", "public", "FudgeMsgEnvelope", "nextMessageEnvelope", "(", ")", "{", "FudgeMsgEnvelope", "msgEnv", ";", "if", "(", "_currentEnvelope", "==", "null", ")", "{", "msgEnv", "=", "readMessageEnvelope", "(", ")", ";", "if", "(", "msgEnv", "==", "null", ")", "return", "null", ";", "}", "else", "{", "msgEnv", "=", "_currentEnvelope", ";", "_currentEnvelope", "=", "null", ";", "}", "processFields", "(", "(", "MutableFudgeFieldContainer", ")", "msgEnv", ".", "getMessage", "(", ")", ")", ";", "return", "msgEnv", ";", "}", "/**\n * Reads the next message envelope from the underlying stream. No fields are read.\n * \n * @return the {@link FudgeMsgEnvelope} read\n */", "protected", "FudgeMsgEnvelope", "readMessageEnvelope", "(", ")", "{", "if", "(", "getStreamReader", "(", ")", ".", "hasNext", "(", ")", "==", "false", ")", "{", "return", "null", ";", "}", "FudgeStreamElement", "element", "=", "getStreamReader", "(", ")", ".", "next", "(", ")", ";", "if", "(", "element", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "element", "!=", "FudgeStreamElement", ".", "MESSAGE_ENVELOPE", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "First element in encoding stream wasn't a message element.", "\"", ")", ";", "}", "MutableFudgeFieldContainer", "msg", "=", "getFudgeContext", "(", ")", ".", "newMessage", "(", ")", ";", "FudgeMsgEnvelope", "envelope", "=", "new", "FudgeMsgEnvelope", "(", "msg", ",", "getStreamReader", "(", ")", ".", "getSchemaVersion", "(", ")", ",", "getStreamReader", "(", ")", ".", "getProcessingDirectives", "(", ")", ")", ";", "return", "envelope", ";", "}", "/**\n * Processes all of the fields from the current message (or sub-message) in the stream, adding them to the supplied container.\n * \n * @param msg container to add fields read to\n */", "protected", "void", "processFields", "(", "MutableFudgeFieldContainer", "msg", ")", "{", "final", "FudgeStreamReader", "reader", "=", "getStreamReader", "(", ")", ";", "while", "(", "reader", ".", "hasNext", "(", ")", ")", "{", "FudgeStreamElement", "element", "=", "reader", ".", "next", "(", ")", ";", "switch", "(", "element", ")", "{", "case", "SIMPLE_FIELD", ":", "msg", ".", "add", "(", "reader", ".", "getFieldName", "(", ")", ",", "reader", ".", "getFieldOrdinal", "(", ")", ",", "reader", ".", "getFieldType", "(", ")", ",", "reader", ".", "getFieldValue", "(", ")", ")", ";", "break", ";", "case", "SUBMESSAGE_FIELD_START", ":", "MutableFudgeFieldContainer", "subMsg", "=", "getFudgeContext", "(", ")", ".", "newMessage", "(", ")", ";", "msg", ".", "add", "(", "reader", ".", "getFieldName", "(", ")", ",", "reader", ".", "getFieldOrdinal", "(", ")", ",", "FudgeMsgFieldType", ".", "INSTANCE", ",", "subMsg", ")", ";", "processFields", "(", "subMsg", ")", ";", "break", ";", "case", "SUBMESSAGE_FIELD_END", ":", "return", ";", "}", "}", "}", "}" ]
A reader for returning whole Fudge messages ({@link FudgeFieldContainer} instances) from an underlying {@link FudgeStreamReader} instance.
[ "A", "reader", "for", "returning", "whole", "Fudge", "messages", "(", "{", "@link", "FudgeFieldContainer", "}", "instances", ")", "from", "an", "underlying", "{", "@link", "FudgeStreamReader", "}", "instance", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,038
91
1b04e369f30300575b98e55de595165a7253627d
barchart/user-configuration-public
packages/sdk-js/example/example.js
[ "MIT" ]
JavaScript
ComparatorBuilder
/** * A builder for compound comparator functions (e.g. sort by last name, * then by first name, then by social security number) that uses a fluent * interface. * * @public * @param {Function} comparator - The initial comparator. * @param {Boolean=} invert - Indicates if the comparator should sort in descending order. */
A builder for compound comparator functions that uses a fluent interface. @public @param {Function} comparator - The initial comparator. @param {Boolean=} invert - Indicates if the comparator should sort in descending order.
[ "A", "builder", "for", "compound", "comparator", "functions", "that", "uses", "a", "fluent", "interface", ".", "@public", "@param", "{", "Function", "}", "comparator", "-", "The", "initial", "comparator", ".", "@param", "{", "Boolean", "=", "}", "invert", "-", "Indicates", "if", "the", "comparator", "should", "sort", "in", "descending", "order", "." ]
class ComparatorBuilder { constructor(comparator, invert, previous) { assert.argumentIsRequired(comparator, 'comparator', Function); assert.argumentIsOptional(invert, 'invert', Boolean); this._comparator = comparator; this._invert = invert || false; this._previous = previous || null; } /** * Adds a new comparator to the list of comparators to use. * * @public * @param {Function} comparator - The next comparator function. * @param {Boolean=} invert - Indicates if the comparator should sort in descending order. * @returns {ComparatorBuilder} */ thenBy(comparator, invert) { assert.argumentIsRequired(comparator, 'comparator', Function); assert.argumentIsOptional(invert, 'invert', Boolean); return new ComparatorBuilder(comparator, invert, this); } /** * Flips the order of the comparator (e.g. ascending to descending). * * @public * @returns {ComparatorBuilder} */ invert() { let previous; if (this._previous) { previous = this._previous.invert(); } else { previous = null; } return new ComparatorBuilder(this._comparator, !this._invert, previous); } /** * Returns the comparator function. * * @public * @returns {Function} */ toComparator() { let previousComparator; if (this._previous) { previousComparator = this._previous.toComparator(); } else { previousComparator = comparators.empty; } return (a, b) => { let result = previousComparator(a, b); if (result === 0) { let sortA; let sortB; if (this._invert) { sortA = b; sortB = a; } else { sortA = a; sortB = b; } result = this._comparator(sortA, sortB); } return result; }; } toString() { return '[ComparatorBuilder]'; } /** * Creates a {@link ComparatorBuilder}, given an initial comparator function. * * @public * @param {Function} comparator - The initial comparator. * @param {Boolean=} invert - Indicates if the comparator should sort in descending order. * @returns {ComparatorBuilder} */ static startWith(comparator, invert) { return new ComparatorBuilder(comparator, invert); } }
[ "class", "ComparatorBuilder", "{", "constructor", "(", "comparator", ",", "invert", ",", "previous", ")", "{", "assert", ".", "argumentIsRequired", "(", "comparator", ",", "'comparator'", ",", "Function", ")", ";", "assert", ".", "argumentIsOptional", "(", "invert", ",", "'invert'", ",", "Boolean", ")", ";", "this", ".", "_comparator", "=", "comparator", ";", "this", ".", "_invert", "=", "invert", "||", "false", ";", "this", ".", "_previous", "=", "previous", "||", "null", ";", "}", "thenBy", "(", "comparator", ",", "invert", ")", "{", "assert", ".", "argumentIsRequired", "(", "comparator", ",", "'comparator'", ",", "Function", ")", ";", "assert", ".", "argumentIsOptional", "(", "invert", ",", "'invert'", ",", "Boolean", ")", ";", "return", "new", "ComparatorBuilder", "(", "comparator", ",", "invert", ",", "this", ")", ";", "}", "invert", "(", ")", "{", "let", "previous", ";", "if", "(", "this", ".", "_previous", ")", "{", "previous", "=", "this", ".", "_previous", ".", "invert", "(", ")", ";", "}", "else", "{", "previous", "=", "null", ";", "}", "return", "new", "ComparatorBuilder", "(", "this", ".", "_comparator", ",", "!", "this", ".", "_invert", ",", "previous", ")", ";", "}", "toComparator", "(", ")", "{", "let", "previousComparator", ";", "if", "(", "this", ".", "_previous", ")", "{", "previousComparator", "=", "this", ".", "_previous", ".", "toComparator", "(", ")", ";", "}", "else", "{", "previousComparator", "=", "comparators", ".", "empty", ";", "}", "return", "(", "a", ",", "b", ")", "=>", "{", "let", "result", "=", "previousComparator", "(", "a", ",", "b", ")", ";", "if", "(", "result", "===", "0", ")", "{", "let", "sortA", ";", "let", "sortB", ";", "if", "(", "this", ".", "_invert", ")", "{", "sortA", "=", "b", ";", "sortB", "=", "a", ";", "}", "else", "{", "sortA", "=", "a", ";", "sortB", "=", "b", ";", "}", "result", "=", "this", ".", "_comparator", "(", "sortA", ",", "sortB", ")", ";", "}", "return", "result", ";", "}", ";", "}", "toString", "(", ")", "{", "return", "'[ComparatorBuilder]'", ";", "}", "static", "startWith", "(", "comparator", ",", "invert", ")", "{", "return", "new", "ComparatorBuilder", "(", "comparator", ",", "invert", ")", ";", "}", "}" ]
A builder for compound comparator functions (e.g.
[ "A", "builder", "for", "compound", "comparator", "functions", "(", "e", ".", "g", "." ]
[ "/**\n * Adds a new comparator to the list of comparators to use.\n *\n * @public\n * @param {Function} comparator - The next comparator function.\n * @param {Boolean=} invert - Indicates if the comparator should sort in descending order.\n * @returns {ComparatorBuilder}\n */", "/**\n * Flips the order of the comparator (e.g. ascending to descending).\n *\n * @public\n * @returns {ComparatorBuilder}\n */", "/**\n * Returns the comparator function.\n *\n * @public\n * @returns {Function}\n */", "/**\n * Creates a {@link ComparatorBuilder}, given an initial comparator function.\n *\n * @public\n * @param {Function} comparator - The initial comparator.\n * @param {Boolean=} invert - Indicates if the comparator should sort in descending order.\n * @returns {ComparatorBuilder}\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
543
81
14cef0a4225f15eee7b559568dfdaaa66e044226
ekzyis/CrypTool-2
CrypPlugins/ArrayOperations/Properties/Resources.Designer.cs
[ "Apache-2.0" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ArrayOperations.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string Array1Caption { get { return ResourceManager.GetString("Array1Caption", resourceCulture); } } internal static string Array1Tooltip { get { return ResourceManager.GetString("Array1Tooltip", resourceCulture); } } internal static string Array2Caption { get { return ResourceManager.GetString("Array2Caption", resourceCulture); } } internal static string Array2Tooltip { get { return ResourceManager.GetString("Array2Tooltip", resourceCulture); } } internal static string Array3Caption { get { return ResourceManager.GetString("Array3Caption", resourceCulture); } } internal static string Array3Tooltip { get { return ResourceManager.GetString("Array3Tooltip", resourceCulture); } } internal static string Arrayarg1 { get { return ResourceManager.GetString("Arrayarg1", resourceCulture); } } internal static string Arrayarg2 { get { return ResourceManager.GetString("Arrayarg2", resourceCulture); } } internal static string Arrayarg3 { get { return ResourceManager.GetString("Arrayarg3", resourceCulture); } } internal static string ArrayNotSetError { get { return ResourceManager.GetString("ArrayNotSetError", resourceCulture); } } internal static string ArrayOperations_Execute_Could_not_execute_operation___0______1_ { get { return ResourceManager.GetString("ArrayOperations_Execute_Could_not_execute_operation___0______1_", resourceCulture); } } internal static string IndexError { get { return ResourceManager.GetString("IndexError", resourceCulture); } } internal static string InputNotSetError { get { return ResourceManager.GetString("InputNotSetError", resourceCulture); } } internal static string InputNotValidError { get { return ResourceManager.GetString("InputNotValidError", resourceCulture); } } internal static string NumericArg1 { get { return ResourceManager.GetString("NumericArg1", resourceCulture); } } internal static string NumericArg2 { get { return ResourceManager.GetString("NumericArg2", resourceCulture); } } internal static string Object1Caption { get { return ResourceManager.GetString("Object1Caption", resourceCulture); } } internal static string Object1Tooltip { get { return ResourceManager.GetString("Object1Tooltip", resourceCulture); } } internal static string Object2Caption { get { return ResourceManager.GetString("Object2Caption", resourceCulture); } } internal static string Object2Tooltip { get { return ResourceManager.GetString("Object2Tooltip", resourceCulture); } } internal static string OperationCaption { get { return ResourceManager.GetString("OperationCaption", resourceCulture); } } internal static string OperationList1 { get { return ResourceManager.GetString("OperationList1", resourceCulture); } } internal static string OperationList10 { get { return ResourceManager.GetString("OperationList10", resourceCulture); } } internal static string OperationList11 { get { return ResourceManager.GetString("OperationList11", resourceCulture); } } internal static string OperationList12 { get { return ResourceManager.GetString("OperationList12", resourceCulture); } } internal static string OperationList13 { get { return ResourceManager.GetString("OperationList13", resourceCulture); } } internal static string OperationList14 { get { return ResourceManager.GetString("OperationList14", resourceCulture); } } internal static string OperationList2 { get { return ResourceManager.GetString("OperationList2", resourceCulture); } } internal static string OperationList3 { get { return ResourceManager.GetString("OperationList3", resourceCulture); } } internal static string OperationList4 { get { return ResourceManager.GetString("OperationList4", resourceCulture); } } internal static string OperationList5 { get { return ResourceManager.GetString("OperationList5", resourceCulture); } } internal static string OperationList6 { get { return ResourceManager.GetString("OperationList6", resourceCulture); } } internal static string OperationList7 { get { return ResourceManager.GetString("OperationList7", resourceCulture); } } internal static string OperationList8 { get { return ResourceManager.GetString("OperationList8", resourceCulture); } } internal static string OperationList9 { get { return ResourceManager.GetString("OperationList9", resourceCulture); } } internal static string OperationTooltip { get { return ResourceManager.GetString("OperationTooltip", resourceCulture); } } internal static string OutputArrayCaption { get { return ResourceManager.GetString("OutputArrayCaption", resourceCulture); } } internal static string OutputArrayTooltip { get { return ResourceManager.GetString("OutputArrayTooltip", resourceCulture); } } internal static string OutputValueCaption { get { return ResourceManager.GetString("OutputValueCaption", resourceCulture); } } internal static string OutputValueTooltip { get { return ResourceManager.GetString("OutputValueTooltip", resourceCulture); } } internal static string PluginCaption { get { return ResourceManager.GetString("PluginCaption", resourceCulture); } } internal static string PluginTooltip { get { return ResourceManager.GetString("PluginTooltip", resourceCulture); } } internal static string Value1Caption { get { return ResourceManager.GetString("Value1Caption", resourceCulture); } } internal static string Value1Tooltip { get { return ResourceManager.GetString("Value1Tooltip", resourceCulture); } } internal static string Value2Caption { get { return ResourceManager.GetString("Value2Caption", resourceCulture); } } internal static string Value2Tooltip { get { return ResourceManager.GetString("Value2Tooltip", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "ArrayOperations.Properties.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "Array1Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Array1Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Array1Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Array1Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Array2Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Array2Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Array2Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Array2Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Array3Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Array3Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Array3Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Array3Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Arrayarg1", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Arrayarg1", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Arrayarg2", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Arrayarg2", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Arrayarg3", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Arrayarg3", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ArrayNotSetError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ArrayNotSetError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ArrayOperations_Execute_Could_not_execute_operation___0______1_", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ArrayOperations_Execute_Could_not_execute_operation___0______1_", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "IndexError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "IndexError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InputNotSetError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InputNotSetError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "InputNotValidError", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InputNotValidError", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NumericArg1", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NumericArg1", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NumericArg2", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NumericArg2", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Object1Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Object1Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Object1Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Object1Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Object2Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Object2Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Object2Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Object2Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationCaption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationCaption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList1", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList1", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList10", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList10", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList11", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList11", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList12", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList12", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList13", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList13", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList14", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList14", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList2", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList2", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList3", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList3", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList4", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList4", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList5", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList5", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList6", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList6", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList7", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList7", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList8", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList8", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationList9", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationList9", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OutputArrayCaption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OutputArrayCaption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OutputArrayTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OutputArrayTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OutputValueCaption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OutputValueCaption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OutputValueTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OutputValueTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PluginCaption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PluginCaption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "PluginTooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PluginTooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Value1Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Value1Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Value1Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Value1Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Value2Caption", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Value2Caption", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Value2Tooltip", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Value2Tooltip", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Array-One.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to First input array.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Array-Two.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Second input array.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Array-Three.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Third input array.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to array #1.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to array #2.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to array #3.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No array provided for {0}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Could not execute operation &apos;{0}&apos; : {1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to the value {0} is not inside of the allowed range ({1}..{2}).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The input &quot;{0}&quot; is not set.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The input &quot;{0}&quot; is not valid: {1}.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to numeric value #1.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to numeric value #2.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Object-One.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Arbitrary value number one.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Object-Two.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Arbitrary value number two.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Operation.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Set-Union.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sort (Descending).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Reverse.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Subarray.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to IndexOf.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Contains.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Set-Complement (Difference).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Set-Intersection.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Concatenate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Equals.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Unique.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Length.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Replace.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Sort (Ascending).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Change the operation of this ArrayOperation.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to OutputArray.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The output array created by this operation.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to OutputValue.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The output value of this operation.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Array Operations.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Operations for modifying arrays.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Integer-One.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to First numeric value.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Integer-Two.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Second numeric value.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,529
84
32eb345f9c90bf205ab2e654634415c939cbe51d
SlyngDK/slf4j-jboss-logging
src/main/java/org/jboss/slf4j/JBossLoggerAdapter.java
[ "Apache-2.0" ]
Java
JBossLoggerAdapter
/** * A wrapper over {@link org.jboss.logging.Logger org.jboss.logging.Logger} * in conformance with the {@link Logger} interface. * <p/> * Adapted from the corresponding slf4j-log4j adapter. * * @author <a href="mailto:[email protected]">Dimitris Andreadis</a> * @author <a href="mailto:[email protected]">James R. Perkins</a> * @version <tt>$Revision: 2784 $</tt> */
A wrapper over org.jboss.logging.Logger org.jboss.logging.Logger in conformance with the Logger interface. Adapted from the corresponding slf4j-log4j adapter. @author Dimitris Andreadis @author James R. Perkins @version $Revision: 2784 $
[ "A", "wrapper", "over", "org", ".", "jboss", ".", "logging", ".", "Logger", "org", ".", "jboss", ".", "logging", ".", "Logger", "in", "conformance", "with", "the", "Logger", "interface", ".", "Adapted", "from", "the", "corresponding", "slf4j", "-", "log4j", "adapter", ".", "@author", "Dimitris", "Andreadis", "@author", "James", "R", ".", "Perkins", "@version", "$Revision", ":", "2784", "$" ]
public final class JBossLoggerAdapter extends MarkerIgnoringBase implements LocationAwareLogger { private static final long serialVersionUID = -1855332334983449117L; final org.jboss.logging.Logger logger; private static final String LOGGER_FQCN = JBossLoggerAdapter.class.getName(); // package access so that only JBossLoggerFactory be able to create one. JBossLoggerAdapter(org.jboss.logging.Logger logger) { this.logger = logger; this.name = logger.getName(); } @Override public void log(Marker marker, String fqcn, int level, String message, Object[] argArray, Throwable t) { FormattingTuple result = MessageFormatter.arrayFormat(message, argArray); switch (level) { case LocationAwareLogger.TRACE_INT: logger.trace(fqcn, result.getMessage(), argArray, t); break; case LocationAwareLogger.DEBUG_INT: logger.debug(fqcn, result.getMessage(), argArray, t); break; case LocationAwareLogger.INFO_INT: logger.info(fqcn, result.getMessage(), argArray, t); break; case LocationAwareLogger.WARN_INT: logger.warn(fqcn, result.getMessage(), argArray, t); break; case LocationAwareLogger.ERROR_INT: logger.error(fqcn, result.getMessage(), argArray, t); break; default: throw new IllegalStateException("Level number " + level + " is not recognized."); } } @Override public boolean isTraceEnabled() { return logger.isTraceEnabled(); } @Override public void trace(final String msg) { log(Level.TRACE, LOGGER_FQCN, msg); } @Override public void trace(final String format, final Object arg) { if (logger.isTraceEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg); log(Level.TRACE, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg); } } @Override public void trace(final String format, final Object arg1, final Object arg2) { if (logger.isTraceEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg1, arg2); log(Level.TRACE, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg1, arg2); } } @Override public void trace(final String format, final Object... arguments) { if (logger.isTraceEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments); log(Level.TRACE, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arguments); } } @Override public void trace(final String msg, final Throwable t) { if (logger.isTraceEnabled()) { log(Level.TRACE, LOGGER_FQCN, msg, t); } } @Override public boolean isDebugEnabled() { return logger.isDebugEnabled(); } @Override public void debug(final String msg) { if (logger.isDebugEnabled()) { log(Level.DEBUG, LOGGER_FQCN, msg); } } @Override public void debug(final String format, final Object arg) { if (logger.isDebugEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg); log(Level.DEBUG, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg); } } @Override public void debug(final String format, final Object arg1, final Object arg2) { if (logger.isDebugEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg1, arg2); log(Level.DEBUG, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg1, arg2); } } @Override public void debug(final String format, final Object... arguments) { if (logger.isDebugEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments); log(Level.DEBUG, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arguments); } } @Override public void debug(final String msg, final Throwable t) { if (logger.isDebugEnabled()) { log(Level.DEBUG, LOGGER_FQCN, msg, t); } } @Override public boolean isInfoEnabled() { return logger.isInfoEnabled(); } @Override public void info(final String msg) { if (logger.isInfoEnabled()) { log(Level.INFO, LOGGER_FQCN, msg); } } @Override public void info(final String format, final Object arg) { if (logger.isInfoEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg); log(Level.INFO, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg); } } @Override public void info(final String format, final Object arg1, final Object arg2) { if (logger.isInfoEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg1, arg2); log(Level.INFO, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg1, arg2); } } @Override public void info(final String format, final Object... arguments) { if (logger.isInfoEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments); log(Level.INFO, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arguments); } } @Override public void info(final String msg, final Throwable t) { if (logger.isInfoEnabled()) { log(Level.INFO, LOGGER_FQCN, msg, t); } } @Override public boolean isWarnEnabled() { return logger.isEnabled(Level.WARN); } @Override public void warn(final String msg) { if (isWarnEnabled()) { log(Level.WARN, LOGGER_FQCN, msg); } } @Override public void warn(final String format, final Object arg) { if (isWarnEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg); log(Level.WARN, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg); } } @Override public void warn(final String format, final Object... arguments) { if (isWarnEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments); log(Level.WARN, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arguments); } } @Override public void warn(final String format, final Object arg1, final Object arg2) { if (isWarnEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg1, arg2); log(Level.WARN, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg1, arg2); } } @Override public void warn(final String msg, final Throwable t) { if (isWarnEnabled()) { log(Level.WARN, LOGGER_FQCN, msg, t); } } @Override public boolean isErrorEnabled() { return logger.isEnabled(Level.ERROR); } @Override public void error(final String msg) { if (isErrorEnabled()) { log(Level.ERROR, LOGGER_FQCN, msg); } } @Override public void error(final String format, final Object arg) { if (isErrorEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg); log(Level.ERROR, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg); } } @Override public void error(final String format, final Object arg1, final Object arg2) { if (isErrorEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.format(format, arg1, arg2); log(Level.ERROR, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arg1, arg2); } } @Override public void error(final String format, final Object... arguments) { if (isErrorEnabled()) { final FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments); log(Level.ERROR, LOGGER_FQCN, formattingTuple.getMessage(), formattingTuple.getThrowable(), arguments); } } @Override public void error(final String msg, final Throwable t) { if (isErrorEnabled()) { log(Level.ERROR, LOGGER_FQCN, msg, t); } } private void log(final org.jboss.logging.Logger.Level level, final String fqcn, final Object message) { log(level, fqcn, message, null); } private void log(final org.jboss.logging.Logger.Level level, final String fqcn, final Object message, final Throwable t) { logger.log(fqcn, level, message, null, t); } private void log(final org.jboss.logging.Logger.Level level, final String fqcn, final Object message, final Throwable t, Object... args) { logger.log(fqcn, level, message, args, t); } }
[ "public", "final", "class", "JBossLoggerAdapter", "extends", "MarkerIgnoringBase", "implements", "LocationAwareLogger", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "1855332334983449117L", ";", "final", "org", ".", "jboss", ".", "logging", ".", "Logger", "logger", ";", "private", "static", "final", "String", "LOGGER_FQCN", "=", "JBossLoggerAdapter", ".", "class", ".", "getName", "(", ")", ";", "JBossLoggerAdapter", "(", "org", ".", "jboss", ".", "logging", ".", "Logger", "logger", ")", "{", "this", ".", "logger", "=", "logger", ";", "this", ".", "name", "=", "logger", ".", "getName", "(", ")", ";", "}", "@", "Override", "public", "void", "log", "(", "Marker", "marker", ",", "String", "fqcn", ",", "int", "level", ",", "String", "message", ",", "Object", "[", "]", "argArray", ",", "Throwable", "t", ")", "{", "FormattingTuple", "result", "=", "MessageFormatter", ".", "arrayFormat", "(", "message", ",", "argArray", ")", ";", "switch", "(", "level", ")", "{", "case", "LocationAwareLogger", ".", "TRACE_INT", ":", "logger", ".", "trace", "(", "fqcn", ",", "result", ".", "getMessage", "(", ")", ",", "argArray", ",", "t", ")", ";", "break", ";", "case", "LocationAwareLogger", ".", "DEBUG_INT", ":", "logger", ".", "debug", "(", "fqcn", ",", "result", ".", "getMessage", "(", ")", ",", "argArray", ",", "t", ")", ";", "break", ";", "case", "LocationAwareLogger", ".", "INFO_INT", ":", "logger", ".", "info", "(", "fqcn", ",", "result", ".", "getMessage", "(", ")", ",", "argArray", ",", "t", ")", ";", "break", ";", "case", "LocationAwareLogger", ".", "WARN_INT", ":", "logger", ".", "warn", "(", "fqcn", ",", "result", ".", "getMessage", "(", ")", ",", "argArray", ",", "t", ")", ";", "break", ";", "case", "LocationAwareLogger", ".", "ERROR_INT", ":", "logger", ".", "error", "(", "fqcn", ",", "result", ".", "getMessage", "(", ")", ",", "argArray", ",", "t", ")", ";", "break", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"", "Level number ", "\"", "+", "level", "+", "\"", " is not recognized.", "\"", ")", ";", "}", "}", "@", "Override", "public", "boolean", "isTraceEnabled", "(", ")", "{", "return", "logger", ".", "isTraceEnabled", "(", ")", ";", "}", "@", "Override", "public", "void", "trace", "(", "final", "String", "msg", ")", "{", "log", "(", "Level", ".", "TRACE", ",", "LOGGER_FQCN", ",", "msg", ")", ";", "}", "@", "Override", "public", "void", "trace", "(", "final", "String", "format", ",", "final", "Object", "arg", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg", ")", ";", "log", "(", "Level", ".", "TRACE", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg", ")", ";", "}", "}", "@", "Override", "public", "void", "trace", "(", "final", "String", "format", ",", "final", "Object", "arg1", ",", "final", "Object", "arg2", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg1", ",", "arg2", ")", ";", "log", "(", "Level", ".", "TRACE", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg1", ",", "arg2", ")", ";", "}", "}", "@", "Override", "public", "void", "trace", "(", "final", "String", "format", ",", "final", "Object", "...", "arguments", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "arrayFormat", "(", "format", ",", "arguments", ")", ";", "log", "(", "Level", ".", "TRACE", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arguments", ")", ";", "}", "}", "@", "Override", "public", "void", "trace", "(", "final", "String", "msg", ",", "final", "Throwable", "t", ")", "{", "if", "(", "logger", ".", "isTraceEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "TRACE", ",", "LOGGER_FQCN", ",", "msg", ",", "t", ")", ";", "}", "}", "@", "Override", "public", "boolean", "isDebugEnabled", "(", ")", "{", "return", "logger", ".", "isDebugEnabled", "(", ")", ";", "}", "@", "Override", "public", "void", "debug", "(", "final", "String", "msg", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "DEBUG", ",", "LOGGER_FQCN", ",", "msg", ")", ";", "}", "}", "@", "Override", "public", "void", "debug", "(", "final", "String", "format", ",", "final", "Object", "arg", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg", ")", ";", "log", "(", "Level", ".", "DEBUG", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg", ")", ";", "}", "}", "@", "Override", "public", "void", "debug", "(", "final", "String", "format", ",", "final", "Object", "arg1", ",", "final", "Object", "arg2", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg1", ",", "arg2", ")", ";", "log", "(", "Level", ".", "DEBUG", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg1", ",", "arg2", ")", ";", "}", "}", "@", "Override", "public", "void", "debug", "(", "final", "String", "format", ",", "final", "Object", "...", "arguments", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "arrayFormat", "(", "format", ",", "arguments", ")", ";", "log", "(", "Level", ".", "DEBUG", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arguments", ")", ";", "}", "}", "@", "Override", "public", "void", "debug", "(", "final", "String", "msg", ",", "final", "Throwable", "t", ")", "{", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "DEBUG", ",", "LOGGER_FQCN", ",", "msg", ",", "t", ")", ";", "}", "}", "@", "Override", "public", "boolean", "isInfoEnabled", "(", ")", "{", "return", "logger", ".", "isInfoEnabled", "(", ")", ";", "}", "@", "Override", "public", "void", "info", "(", "final", "String", "msg", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "INFO", ",", "LOGGER_FQCN", ",", "msg", ")", ";", "}", "}", "@", "Override", "public", "void", "info", "(", "final", "String", "format", ",", "final", "Object", "arg", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg", ")", ";", "log", "(", "Level", ".", "INFO", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg", ")", ";", "}", "}", "@", "Override", "public", "void", "info", "(", "final", "String", "format", ",", "final", "Object", "arg1", ",", "final", "Object", "arg2", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg1", ",", "arg2", ")", ";", "log", "(", "Level", ".", "INFO", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg1", ",", "arg2", ")", ";", "}", "}", "@", "Override", "public", "void", "info", "(", "final", "String", "format", ",", "final", "Object", "...", "arguments", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "arrayFormat", "(", "format", ",", "arguments", ")", ";", "log", "(", "Level", ".", "INFO", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arguments", ")", ";", "}", "}", "@", "Override", "public", "void", "info", "(", "final", "String", "msg", ",", "final", "Throwable", "t", ")", "{", "if", "(", "logger", ".", "isInfoEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "INFO", ",", "LOGGER_FQCN", ",", "msg", ",", "t", ")", ";", "}", "}", "@", "Override", "public", "boolean", "isWarnEnabled", "(", ")", "{", "return", "logger", ".", "isEnabled", "(", "Level", ".", "WARN", ")", ";", "}", "@", "Override", "public", "void", "warn", "(", "final", "String", "msg", ")", "{", "if", "(", "isWarnEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "WARN", ",", "LOGGER_FQCN", ",", "msg", ")", ";", "}", "}", "@", "Override", "public", "void", "warn", "(", "final", "String", "format", ",", "final", "Object", "arg", ")", "{", "if", "(", "isWarnEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg", ")", ";", "log", "(", "Level", ".", "WARN", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg", ")", ";", "}", "}", "@", "Override", "public", "void", "warn", "(", "final", "String", "format", ",", "final", "Object", "...", "arguments", ")", "{", "if", "(", "isWarnEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "arrayFormat", "(", "format", ",", "arguments", ")", ";", "log", "(", "Level", ".", "WARN", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arguments", ")", ";", "}", "}", "@", "Override", "public", "void", "warn", "(", "final", "String", "format", ",", "final", "Object", "arg1", ",", "final", "Object", "arg2", ")", "{", "if", "(", "isWarnEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg1", ",", "arg2", ")", ";", "log", "(", "Level", ".", "WARN", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg1", ",", "arg2", ")", ";", "}", "}", "@", "Override", "public", "void", "warn", "(", "final", "String", "msg", ",", "final", "Throwable", "t", ")", "{", "if", "(", "isWarnEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "WARN", ",", "LOGGER_FQCN", ",", "msg", ",", "t", ")", ";", "}", "}", "@", "Override", "public", "boolean", "isErrorEnabled", "(", ")", "{", "return", "logger", ".", "isEnabled", "(", "Level", ".", "ERROR", ")", ";", "}", "@", "Override", "public", "void", "error", "(", "final", "String", "msg", ")", "{", "if", "(", "isErrorEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "ERROR", ",", "LOGGER_FQCN", ",", "msg", ")", ";", "}", "}", "@", "Override", "public", "void", "error", "(", "final", "String", "format", ",", "final", "Object", "arg", ")", "{", "if", "(", "isErrorEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg", ")", ";", "log", "(", "Level", ".", "ERROR", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg", ")", ";", "}", "}", "@", "Override", "public", "void", "error", "(", "final", "String", "format", ",", "final", "Object", "arg1", ",", "final", "Object", "arg2", ")", "{", "if", "(", "isErrorEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "format", "(", "format", ",", "arg1", ",", "arg2", ")", ";", "log", "(", "Level", ".", "ERROR", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arg1", ",", "arg2", ")", ";", "}", "}", "@", "Override", "public", "void", "error", "(", "final", "String", "format", ",", "final", "Object", "...", "arguments", ")", "{", "if", "(", "isErrorEnabled", "(", ")", ")", "{", "final", "FormattingTuple", "formattingTuple", "=", "MessageFormatter", ".", "arrayFormat", "(", "format", ",", "arguments", ")", ";", "log", "(", "Level", ".", "ERROR", ",", "LOGGER_FQCN", ",", "formattingTuple", ".", "getMessage", "(", ")", ",", "formattingTuple", ".", "getThrowable", "(", ")", ",", "arguments", ")", ";", "}", "}", "@", "Override", "public", "void", "error", "(", "final", "String", "msg", ",", "final", "Throwable", "t", ")", "{", "if", "(", "isErrorEnabled", "(", ")", ")", "{", "log", "(", "Level", ".", "ERROR", ",", "LOGGER_FQCN", ",", "msg", ",", "t", ")", ";", "}", "}", "private", "void", "log", "(", "final", "org", ".", "jboss", ".", "logging", ".", "Logger", ".", "Level", "level", ",", "final", "String", "fqcn", ",", "final", "Object", "message", ")", "{", "log", "(", "level", ",", "fqcn", ",", "message", ",", "null", ")", ";", "}", "private", "void", "log", "(", "final", "org", ".", "jboss", ".", "logging", ".", "Logger", ".", "Level", "level", ",", "final", "String", "fqcn", ",", "final", "Object", "message", ",", "final", "Throwable", "t", ")", "{", "logger", ".", "log", "(", "fqcn", ",", "level", ",", "message", ",", "null", ",", "t", ")", ";", "}", "private", "void", "log", "(", "final", "org", ".", "jboss", ".", "logging", ".", "Logger", ".", "Level", "level", ",", "final", "String", "fqcn", ",", "final", "Object", "message", ",", "final", "Throwable", "t", ",", "Object", "...", "args", ")", "{", "logger", ".", "log", "(", "fqcn", ",", "level", ",", "message", ",", "args", ",", "t", ")", ";", "}", "}" ]
A wrapper over {@link org.jboss.logging.Logger org.jboss.logging.Logger} in conformance with the {@link Logger} interface.
[ "A", "wrapper", "over", "{", "@link", "org", ".", "jboss", ".", "logging", ".", "Logger", "org", ".", "jboss", ".", "logging", ".", "Logger", "}", "in", "conformance", "with", "the", "{", "@link", "Logger", "}", "interface", "." ]
[ "// package access so that only JBossLoggerFactory be able to create one.\r" ]
[ { "param": "MarkerIgnoringBase", "type": null }, { "param": "LocationAwareLogger", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "MarkerIgnoringBase", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "LocationAwareLogger", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
1,992
114
db815fb00217a01695d76763e5d6e4a94fcf9bda
rocchiele/azure-powershell
src/SqlVirtualMachine/SqlVirtualMachine/Common/AzureSqlVirtualMachineCmdletBase.cs
[ "MIT" ]
C#
AzureSqlVirtualMachineCmdletBase
/// <summary> /// The base class for all Azure Sql virtual machne cmdlets. /// </summary> /// <typeparam name="M">Type of the model the cmdlet will be working on (e.g. AzureSqlVirtualMachineModel)</typeparam> /// <typeparam name="A">Adapter used to call the REST APIs to perform actions on the specified model</typeparam>
The base class for all Azure Sql virtual machne cmdlets.
[ "The", "base", "class", "for", "all", "Azure", "Sql", "virtual", "machne", "cmdlets", "." ]
public abstract class AzureSqlVirtualMachineCmdletBase<M, A> : AzureRMCmdlet { public A ModelAdapter { get; internal set; } protected virtual string GetResourceId(M model) { var resource = model as IEnumerable<object>; if (resource != null) { if (resource != null) { var resourceIdProperty = resource.GetType().GetProperty("ResourceId"); var resourceIdValue = resourceIdProperty != null ? resourceIdProperty.GetValue(resource) : null; string resourceId = resourceIdValue != null ? resourceIdValue.ToString() : ""; if (!string.IsNullOrEmpty(resourceId)) { return resourceId; } } } return string.Empty; } protected abstract M GetEntity(); protected virtual M ApplyUserInputToModel(M model) { return model; } protected virtual M PersistChanges(M entity) { return default(M); } protected virtual bool WriteResult() { return true; } protected abstract A InitModelAdapter(); protected virtual object TransformModelToOutputObject(M model) { return model; } protected virtual string GetConfirmActionProcessMessage() { return MyInvocation.MyCommand.Name.Split('-')[0].ToLower(); } protected virtual void ParseInput() { } public override void ExecuteCmdlet() { ModelAdapter = InitModelAdapter(); ParseInput(); M model = GetEntity(); M updatedModel = ApplyUserInputToModel(model); M responseModel = default(M); ConfirmAction(GetConfirmActionProcessMessage(), GetResourceId(updatedModel), () => { responseModel = PersistChanges(updatedModel); }); if (responseModel != null) { if (WriteResult()) { WriteObject(TransformModelToOutputObject(responseModel), true); } } else { if (WriteResult()) { WriteObject(TransformModelToOutputObject(updatedModel)); } } } }
[ "public", "abstract", "class", "AzureSqlVirtualMachineCmdletBase", "<", "M", ",", "A", ">", ":", "AzureRMCmdlet", "{", "public", "A", "ModelAdapter", "{", "get", ";", "internal", "set", ";", "}", "protected", "virtual", "string", "GetResourceId", "(", "M", "model", ")", "{", "var", "resource", "=", "model", "as", "IEnumerable", "<", "object", ">", ";", "if", "(", "resource", "!=", "null", ")", "{", "if", "(", "resource", "!=", "null", ")", "{", "var", "resourceIdProperty", "=", "resource", ".", "GetType", "(", ")", ".", "GetProperty", "(", "\"", "ResourceId", "\"", ")", ";", "var", "resourceIdValue", "=", "resourceIdProperty", "!=", "null", "?", "resourceIdProperty", ".", "GetValue", "(", "resource", ")", ":", "null", ";", "string", "resourceId", "=", "resourceIdValue", "!=", "null", "?", "resourceIdValue", ".", "ToString", "(", ")", ":", "\"", "\"", ";", "if", "(", "!", "string", ".", "IsNullOrEmpty", "(", "resourceId", ")", ")", "{", "return", "resourceId", ";", "}", "}", "}", "return", "string", ".", "Empty", ";", "}", "protected", "abstract", "M", "GetEntity", "(", ")", ";", "protected", "virtual", "M", "ApplyUserInputToModel", "(", "M", "model", ")", "{", "return", "model", ";", "}", "protected", "virtual", "M", "PersistChanges", "(", "M", "entity", ")", "{", "return", "default", "(", "M", ")", ";", "}", "protected", "virtual", "bool", "WriteResult", "(", ")", "{", "return", "true", ";", "}", "protected", "abstract", "A", "InitModelAdapter", "(", ")", ";", "protected", "virtual", "object", "TransformModelToOutputObject", "(", "M", "model", ")", "{", "return", "model", ";", "}", "protected", "virtual", "string", "GetConfirmActionProcessMessage", "(", ")", "{", "return", "MyInvocation", ".", "MyCommand", ".", "Name", ".", "Split", "(", "'", "-", "'", ")", "[", "0", "]", ".", "ToLower", "(", ")", ";", "}", "protected", "virtual", "void", "ParseInput", "(", ")", "{", "}", "public", "override", "void", "ExecuteCmdlet", "(", ")", "{", "ModelAdapter", "=", "InitModelAdapter", "(", ")", ";", "ParseInput", "(", ")", ";", "M", "model", "=", "GetEntity", "(", ")", ";", "M", "updatedModel", "=", "ApplyUserInputToModel", "(", "model", ")", ";", "M", "responseModel", "=", "default", "(", "M", ")", ";", "ConfirmAction", "(", "GetConfirmActionProcessMessage", "(", ")", ",", "GetResourceId", "(", "updatedModel", ")", ",", "(", ")", "=>", "{", "responseModel", "=", "PersistChanges", "(", "updatedModel", ")", ";", "}", ")", ";", "if", "(", "responseModel", "!=", "null", ")", "{", "if", "(", "WriteResult", "(", ")", ")", "{", "WriteObject", "(", "TransformModelToOutputObject", "(", "responseModel", ")", ",", "true", ")", ";", "}", "}", "else", "{", "if", "(", "WriteResult", "(", ")", ")", "{", "WriteObject", "(", "TransformModelToOutputObject", "(", "updatedModel", ")", ")", ";", "}", "}", "}", "}" ]
The base class for all Azure Sql virtual machne cmdlets.
[ "The", "base", "class", "for", "all", "Azure", "Sql", "virtual", "machne", "cmdlets", "." ]
[ "/// <summary>", "/// Adapter used to call the REST APIs to perform actions on the specified model", "/// </summary>", "/// <summary>", "/// Get the ResourceId property value of the model provided.", "/// </summary>", "/// <param name=\"model\"></param>", "/// <returns></returns>", "/// <summary>", "/// Gets an entity from the service", "/// </summary>", "/// <returns>A model object</returns>", "/// <summary>", "/// Updates the given model element with the cmdlet specific operation ", "/// </summary>", "/// <param name=\"model\">A model object</param>", "/// <summary>", "/// This method is responsible to call the right API in the communication layer that will eventually send the information in the ", "/// object to the REST endpoint", "/// </summary>", "/// <param name=\"entity\">The model object with the data to be sent to the REST endpoints</param>", "/// <summary>", "/// Returns true if the model object that was constructed by this cmdlet should be written out", "/// </summary>", "/// <returns>True if the model object should be written out, False otherwise</returns>", "/// <summary>", "/// Creation and initialization of the ModelAdapter object", "/// </summary>", "/// <returns>An initialized and ready to use ModelAdapter object</returns>", "/// <summary>", "/// Transforms the given model object to be an object that is written out", "/// </summary>", "/// <param name=\"model\">The about to be written model object</param>", "/// <returns>The prepared object to be written out</returns>", "/// <summary>", "/// Get the name of the action to be displayed in the request of confirmation for this cmdlet", "/// </summary>", "/// <returns>The name of the cmdlet that is being executed</returns>", "/// <summary>", "/// Parse the input provided to the cmdlet", "/// </summary>", "/// <summary>", "/// General method thaat outline which operations should be executed during the execution of a sqlvirtualmachine cmdlet", "/// </summary>", "// Initialize the adapter class that is responsible for the convertion between the powershell resource and the .NET one", "// Parse the parameter set given as input", "// Retrieve the Azure entity the cmdlet is refearing to", "// Apply the cmdlet to the recovered object", "// If the confirmation level requires it, prompt the user for confirmation", "// Apply the changes to the response model", "// Convert the response model in a powershell object", "// See Microsoft.Azure.PowerShell.Cmdlets.SqlVirtualMachine.generated.format.ps1xml file for more information on the response format" ]
[ { "param": "AzureRMCmdlet", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AzureRMCmdlet", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "Type of the model the cmdlet will be working on", "docstring_tokens": [ "Type", "of", "the", "model", "the", "cmdlet", "will", "be", "working", "on" ] }, { "identifier": "typeparam", "docstring": "Adapter used to call the REST APIs to perform actions on the specified model", "docstring_tokens": [ "Adapter", "used", "to", "call", "the", "REST", "APIs", "to", "perform", "actions", "on", "the", "specified", "model" ] } ] }
false
16
406
76
6aa5ca7173cfda8875a0fb208cdf2715dbf0f3c2
AustralianDisabilityLimited/MultiversePlatform
mvsm/DetailVeg.cs
[ "MIT" ]
C#
DetailVeg
/// <summary> /// Implement billboarded detail vegitation (grass, small shrubs, flowers, etc) in the area /// around the camera. /// /// A single vegitation block is created, with plants laid out within that block in 2d(no height). /// 9 Instances of the block are created, with heights computed to match the landscape. /// /// The vegitation textures are all taken from a single texture atlas, which is organized /// with all the textures in a single row. /// </summary>
Implement billboarded detail vegitation (grass, small shrubs, flowers, etc) in the area around the camera. A single vegitation block is created, with plants laid out within that block in 2d(no height). 9 Instances of the block are created, with heights computed to match the landscape. The vegitation textures are all taken from a single texture atlas, which is organized with all the textures in a single row.
[ "Implement", "billboarded", "detail", "vegitation", "(", "grass", "small", "shrubs", "flowers", "etc", ")", "in", "the", "area", "around", "the", "camera", ".", "A", "single", "vegitation", "block", "is", "created", "with", "plants", "laid", "out", "within", "that", "block", "in", "2d", "(", "no", "height", ")", ".", "9", "Instances", "of", "the", "block", "are", "created", "with", "heights", "computed", "to", "match", "the", "landscape", ".", "The", "vegitation", "textures", "are", "all", "taken", "from", "a", "single", "texture", "atlas", "which", "is", "organized", "with", "all", "the", "textures", "in", "a", "single", "row", "." ]
public class DetailVeg { private int blockSize; private Random rand; private bool enabled = true; private Vector3 cameraLocation; private PageCoord cameraPage; private SceneNode parentSceneNode; private VegetationTile[,] vegetationTiles; private float roadClearRadius = 5 * TerrainManager.oneMeter; private List<VegetationSemantic> vegetationBoundaries; private MVImageSet detailVegImageSet; public DetailVeg(int blockSize, SceneNode parent) { rand = new Random(0); this.blockSize = blockSize; parentSceneNode = parent; vegetationBoundaries = new List<VegetationSemantic>(); detailVegImageSet = MVImageSet.FindMVImageSet("DetailVeg.imageset"); } public void AddVegetationSemantic(VegetationSemantic vegetationBoundary) { vegetationBoundaries.Add(vegetationBoundary); RefreshVegetation(); } public void RemoveVegetationSemantic(VegetationSemantic vegetationBoundary) { vegetationBoundaries.Remove(vegetationBoundary); RefreshVegetation(); } private void FreeVegetationTile(VegetationTile tile) { if (tile != null) { tile.Dispose(); } } protected void Cleanup() { if (vegetationTiles != null) { foreach (VegetationTile tile in vegetationTiles) { FreeVegetationTile(tile); } vegetationTiles = null; } } public void Dispose() { Cleanup(); } public void RefreshVegetation() { Cleanup(); NewCameraPage(cameraPage); } public void PerFrameProcessing(Camera camera) { if (enabled && (camera.DerivedPosition != cameraLocation)) { CameraLocation = camera.DerivedPosition; } } private void NewCameraPage(PageCoord newPage) { if (enabled && TerrainManager.Instance.CameraSet) { VegetationTile[,] newVegetationTiles = new VegetationTile[3, 3]; if (vegetationTiles != null) { foreach (VegetationTile tile in vegetationTiles) { PageCoord pc = tile.pc; int x = pc.X - (newPage.X - 1); int z = pc.Z - (newPage.Z - 1); if ((x >= 0) && (x < 3) && (z >= 0) && (z < 3)) { newVegetationTiles[x, z] = tile; } else { FreeVegetationTile(tile); } } } vegetationTiles = newVegetationTiles; for (int x = 0; x < 3; x++) { for (int z = 0; z < 3; z++) { if (vegetationTiles[x, z] == null) { vegetationTiles[x, z] = new VegetationTile(parentSceneNode, vegetationBoundaries, x, z, newPage, blockSize, roadClearRadius, detailVegImageSet, rand); } } } cameraPage = newPage; } } public bool Enabled { get { return enabled; } set { enabled = value; } } public Vector3 CameraLocation { get { return cameraLocation; } set { cameraLocation = value; PageCoord newCameraPage = new PageCoord(cameraLocation, blockSize); if (newCameraPage != cameraPage) { NewCameraPage(newCameraPage); } } } public float RoadClearRadius { get { return roadClearRadius; } set { roadClearRadius = value; } } }
[ "public", "class", "DetailVeg", "{", "private", "int", "blockSize", ";", "private", "Random", "rand", ";", "private", "bool", "enabled", "=", "true", ";", "private", "Vector3", "cameraLocation", ";", "private", "PageCoord", "cameraPage", ";", "private", "SceneNode", "parentSceneNode", ";", "private", "VegetationTile", "[", ",", "]", "vegetationTiles", ";", "private", "float", "roadClearRadius", "=", "5", "*", "TerrainManager", ".", "oneMeter", ";", "private", "List", "<", "VegetationSemantic", ">", "vegetationBoundaries", ";", "private", "MVImageSet", "detailVegImageSet", ";", "public", "DetailVeg", "(", "int", "blockSize", ",", "SceneNode", "parent", ")", "{", "rand", "=", "new", "Random", "(", "0", ")", ";", "this", ".", "blockSize", "=", "blockSize", ";", "parentSceneNode", "=", "parent", ";", "vegetationBoundaries", "=", "new", "List", "<", "VegetationSemantic", ">", "(", ")", ";", "detailVegImageSet", "=", "MVImageSet", ".", "FindMVImageSet", "(", "\"", "DetailVeg.imageset", "\"", ")", ";", "}", "public", "void", "AddVegetationSemantic", "(", "VegetationSemantic", "vegetationBoundary", ")", "{", "vegetationBoundaries", ".", "Add", "(", "vegetationBoundary", ")", ";", "RefreshVegetation", "(", ")", ";", "}", "public", "void", "RemoveVegetationSemantic", "(", "VegetationSemantic", "vegetationBoundary", ")", "{", "vegetationBoundaries", ".", "Remove", "(", "vegetationBoundary", ")", ";", "RefreshVegetation", "(", ")", ";", "}", "private", "void", "FreeVegetationTile", "(", "VegetationTile", "tile", ")", "{", "if", "(", "tile", "!=", "null", ")", "{", "tile", ".", "Dispose", "(", ")", ";", "}", "}", "protected", "void", "Cleanup", "(", ")", "{", "if", "(", "vegetationTiles", "!=", "null", ")", "{", "foreach", "(", "VegetationTile", "tile", "in", "vegetationTiles", ")", "{", "FreeVegetationTile", "(", "tile", ")", ";", "}", "vegetationTiles", "=", "null", ";", "}", "}", "public", "void", "Dispose", "(", ")", "{", "Cleanup", "(", ")", ";", "}", "public", "void", "RefreshVegetation", "(", ")", "{", "Cleanup", "(", ")", ";", "NewCameraPage", "(", "cameraPage", ")", ";", "}", "public", "void", "PerFrameProcessing", "(", "Camera", "camera", ")", "{", "if", "(", "enabled", "&&", "(", "camera", ".", "DerivedPosition", "!=", "cameraLocation", ")", ")", "{", "CameraLocation", "=", "camera", ".", "DerivedPosition", ";", "}", "}", "private", "void", "NewCameraPage", "(", "PageCoord", "newPage", ")", "{", "if", "(", "enabled", "&&", "TerrainManager", ".", "Instance", ".", "CameraSet", ")", "{", "VegetationTile", "[", ",", "]", "newVegetationTiles", "=", "new", "VegetationTile", "[", "3", ",", "3", "]", ";", "if", "(", "vegetationTiles", "!=", "null", ")", "{", "foreach", "(", "VegetationTile", "tile", "in", "vegetationTiles", ")", "{", "PageCoord", "pc", "=", "tile", ".", "pc", ";", "int", "x", "=", "pc", ".", "X", "-", "(", "newPage", ".", "X", "-", "1", ")", ";", "int", "z", "=", "pc", ".", "Z", "-", "(", "newPage", ".", "Z", "-", "1", ")", ";", "if", "(", "(", "x", ">=", "0", ")", "&&", "(", "x", "<", "3", ")", "&&", "(", "z", ">=", "0", ")", "&&", "(", "z", "<", "3", ")", ")", "{", "newVegetationTiles", "[", "x", ",", "z", "]", "=", "tile", ";", "}", "else", "{", "FreeVegetationTile", "(", "tile", ")", ";", "}", "}", "}", "vegetationTiles", "=", "newVegetationTiles", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "3", ";", "x", "++", ")", "{", "for", "(", "int", "z", "=", "0", ";", "z", "<", "3", ";", "z", "++", ")", "{", "if", "(", "vegetationTiles", "[", "x", ",", "z", "]", "==", "null", ")", "{", "vegetationTiles", "[", "x", ",", "z", "]", "=", "new", "VegetationTile", "(", "parentSceneNode", ",", "vegetationBoundaries", ",", "x", ",", "z", ",", "newPage", ",", "blockSize", ",", "roadClearRadius", ",", "detailVegImageSet", ",", "rand", ")", ";", "}", "}", "}", "cameraPage", "=", "newPage", ";", "}", "}", "public", "bool", "Enabled", "{", "get", "{", "return", "enabled", ";", "}", "set", "{", "enabled", "=", "value", ";", "}", "}", "public", "Vector3", "CameraLocation", "{", "get", "{", "return", "cameraLocation", ";", "}", "set", "{", "cameraLocation", "=", "value", ";", "PageCoord", "newCameraPage", "=", "new", "PageCoord", "(", "cameraLocation", ",", "blockSize", ")", ";", "if", "(", "newCameraPage", "!=", "cameraPage", ")", "{", "NewCameraPage", "(", "newCameraPage", ")", ";", "}", "}", "}", "public", "float", "RoadClearRadius", "{", "get", "{", "return", "roadClearRadius", ";", "}", "set", "{", "roadClearRadius", "=", "value", ";", "}", "}", "}" ]
Implement billboarded detail vegitation (grass, small shrubs, flowers, etc) in the area around the camera.
[ "Implement", "billboarded", "detail", "vegitation", "(", "grass", "small", "shrubs", "flowers", "etc", ")", "in", "the", "area", "around", "the", "camera", "." ]
[ "// These values define the distances from the camera where the vegetation begins and", "// ends its fade out of visibility. Anything closer than nearTaperDist is fully", "// visible, and anything past farTaperDist is invisible.", "// private float nearTaperDist; (unused)", "// private float farTaperDist; (unused)", "// clear out any old vegetation", "// free the old vegetation tiles" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
850
108
1f9ff2bf77a526f3b81511374f2875a39ae4b376
xperiandri/DisposableFixer
src/DisposableFixer/Resources.Designer.cs
[ "CC-BY-4.0" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DisposableFixer.Resources", typeof(Resources).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string AnonymousObjectFromMethodInvocationTitle { get { return ResourceManager.GetString("AnonymousObjectFromMethodInvocationTitle", resourceCulture); } } internal static string AnonymousObjectFromMethodInvocationMessageFormat { get { return ResourceManager.GetString("AnonymousObjectFromMethodInvocationMessageFormat", resourceCulture); } } internal static string AnonymousObjectFromMethodInvocationDescription { get { return ResourceManager.GetString("AnonymousObjectFromMethodInvocationDescription", resourceCulture); } } internal static string AnonymousObjectFromObjectCreationMessageFormat { get { return ResourceManager.GetString("AnonymousObjectFromObjectCreationMessageFormat", resourceCulture); } } internal static string AnonymousObjectFromObjectCreationDescription { get { return ResourceManager.GetString("AnonymousObjectFromObjectCreationDescription", resourceCulture); } } internal static string AnonymousObjectFromObjectCreationTitle { get { return ResourceManager.GetString("AnonymousObjectFromObjectCreationTitle", resourceCulture); } } internal static string AssignmendFromObjectCreationToFieldNotDisposedDescription { get { return ResourceManager.GetString("AssignmendFromObjectCreationToFieldNotDisposedDescription", resourceCulture); } } internal static string AssignmendFromObjectCreationToFieldNotDisposedTitle { get { return ResourceManager.GetString("AssignmendFromObjectCreationToFieldNotDisposedTitle", resourceCulture); } } internal static string AssignmendFromObjectCreationToFieldNotDisposedMessageFormat { get { return ResourceManager.GetString("AssignmendFromObjectCreationToFieldNotDisposedMessageFormat", resourceCulture); } } internal static string AssignmendFromMethodInvocationToFieldNotDisposedDescription { get { return ResourceManager.GetString("AssignmendFromMethodInvocationToFieldNotDisposedDescription", resourceCulture); } } internal static string AssignmendFromMethodInvocationToFieldNotDisposedTitle { get { return ResourceManager.GetString("AssignmendFromMethodInvocationToFieldNotDisposedTitle", resourceCulture); } } internal static string AssignmendFromMethodInvocationToFieldNotDisposedMessageFormat { get { return ResourceManager.GetString("AssignmendFromMethodInvocationToFieldNotDisposedMessageFormat", resourceCulture); } } internal static string AssignmendFromMethodInvocationToPropertyNotDisposedDescription { get { return ResourceManager.GetString("AssignmendFromMethodInvocationToPropertyNotDisposedDescription", resourceCulture); } } internal static string AssignmendFromMethodInvocationToPropertyNotDisposedTitle { get { return ResourceManager.GetString("AssignmendFromMethodInvocationToPropertyNotDisposedTitle", resourceCulture); } } internal static string AssignmendFromMethodInvocationToPropertyNotDisposedMessageFormat { get { return ResourceManager.GetString("AssignmendFromMethodInvocationToPropertyNotDisposedMessageFormat", resourceCulture); } } internal static string AssignmendFromObjectCreationToPropertyNotDisposedDescription { get { return ResourceManager.GetString("AssignmendFromObjectCreationToPropertyNotDisposedDescription", resourceCulture); } } internal static string AssignmendFromObjectCreationToPropertyNotDisposedTitle { get { return ResourceManager.GetString("AssignmendFromObjectCreationToPropertyNotDisposedTitle", resourceCulture); } } internal static string AssignmendFromObjectCreationToPropertyNotDisposedMessageFormat { get { return ResourceManager.GetString("AssignmendFromObjectCreationToPropertyNotDisposedMessageFormat", resourceCulture); } } internal static string NotDisposedLocalVariableMessageFormat { get { return ResourceManager.GetString("NotDisposedLocalVariableMessageFormat", resourceCulture); } } internal static string NotDisposedLocalVariableTitle { get { return ResourceManager.GetString("NotDisposedLocalVariableTitle", resourceCulture); } } internal static string NotDisposedLocalVariableDescription { get { return ResourceManager.GetString("NotDisposedLocalVariableDescription", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "DisposableFixer.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "GetTypeInfo", "(", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "AnonymousObjectFromMethodInvocationTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AnonymousObjectFromMethodInvocationTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AnonymousObjectFromMethodInvocationMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AnonymousObjectFromMethodInvocationMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AnonymousObjectFromMethodInvocationDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AnonymousObjectFromMethodInvocationDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AnonymousObjectFromObjectCreationMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AnonymousObjectFromObjectCreationMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AnonymousObjectFromObjectCreationDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AnonymousObjectFromObjectCreationDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AnonymousObjectFromObjectCreationTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AnonymousObjectFromObjectCreationTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromObjectCreationToFieldNotDisposedDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromObjectCreationToFieldNotDisposedDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromObjectCreationToFieldNotDisposedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromObjectCreationToFieldNotDisposedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromObjectCreationToFieldNotDisposedMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromObjectCreationToFieldNotDisposedMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromMethodInvocationToFieldNotDisposedDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromMethodInvocationToFieldNotDisposedDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromMethodInvocationToFieldNotDisposedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromMethodInvocationToFieldNotDisposedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromMethodInvocationToFieldNotDisposedMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromMethodInvocationToFieldNotDisposedMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromMethodInvocationToPropertyNotDisposedDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromMethodInvocationToPropertyNotDisposedDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromMethodInvocationToPropertyNotDisposedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromMethodInvocationToPropertyNotDisposedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromMethodInvocationToPropertyNotDisposedMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromMethodInvocationToPropertyNotDisposedMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromObjectCreationToPropertyNotDisposedDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromObjectCreationToPropertyNotDisposedDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromObjectCreationToPropertyNotDisposedTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromObjectCreationToPropertyNotDisposedTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "AssignmendFromObjectCreationToPropertyNotDisposedMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AssignmendFromObjectCreationToPropertyNotDisposedMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NotDisposedLocalVariableMessageFormat", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NotDisposedLocalVariableMessageFormat", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NotDisposedLocalVariableTitle", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NotDisposedLocalVariableTitle", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "NotDisposedLocalVariableDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NotDisposedLocalVariableDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Undisposed ressource..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Method returns an anonymous object that is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Method returns an anonymous object that is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This ObjectCreation returns an object that is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This ObjectCreation returns an object that is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This ObjectCreation returns an object that is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "// <summary>", "/// Looks up a localized string similar to Property is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Property is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Property is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Field is not disposed..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Local variable is not disposed.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Local variable is not disposed.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Local variable is not disposed.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,084
84
7e99064a4652b41c0297a7c5f76880d28a9b67e6
kmaterna/SlipPy
slippy/tikhonov.py
[ "MIT" ]
Python
Neighbors
iterates over the flattened elements of C, returning the element and its forward and backward looking neighbors for each axis. Example ------- >> C = np.array([[1,2,3], [4,5,6]]) >> for i in ForwardNeighbors(C): print(i) [4,2],1 [5,3,1],2 [6,2],3 [5,1],4 [6,2,4],5 [3,5],6
iterates over the flattened elements of C, returning the element and its forward and backward looking neighbors for each axis. Example
[ "iterates", "over", "the", "flattened", "elements", "of", "C", "returning", "the", "element", "and", "its", "forward", "and", "backward", "looking", "neighbors", "for", "each", "axis", ".", "Example" ]
class Neighbors: ''' iterates over the flattened elements of C, returning the element and its forward and backward looking neighbors for each axis. Example ------- >> C = np.array([[1,2,3], [4,5,6]]) >> for i in ForwardNeighbors(C): print(i) [4,2],1 [5,3,1],2 [6,2],3 [5,1],4 [6,2,4],5 [3,5],6 ''' def __init__(self,C): self.C = np.asarray(C) self.itr = 0 def next(self): return self.__next__() def __iter__(self): return self def __next__(self): if self.itr == self.C.size: raise StopIteration else: out = [] idx = flat_to_array_index(self.itr,self.C.shape) for idx_pert in Perturb(idx,1): # this checks if the perturbed indices are valid for C if any(i>=j for i,j in zip(idx_pert,self.C.shape)): continue out += [self.C[tuple(idx_pert)]] for idx_pert in Perturb(idx,-1): # this checks if the perturbed indices are valid for C if any(i<0 for i in idx_pert): continue out += [self.C[tuple(idx_pert)]] self.itr += 1 return out,self.C[idx]
[ "class", "Neighbors", ":", "def", "__init__", "(", "self", ",", "C", ")", ":", "self", ".", "C", "=", "np", ".", "asarray", "(", "C", ")", "self", ".", "itr", "=", "0", "def", "next", "(", "self", ")", ":", "return", "self", ".", "__next__", "(", ")", "def", "__iter__", "(", "self", ")", ":", "return", "self", "def", "__next__", "(", "self", ")", ":", "if", "self", ".", "itr", "==", "self", ".", "C", ".", "size", ":", "raise", "StopIteration", "else", ":", "out", "=", "[", "]", "idx", "=", "flat_to_array_index", "(", "self", ".", "itr", ",", "self", ".", "C", ".", "shape", ")", "for", "idx_pert", "in", "Perturb", "(", "idx", ",", "1", ")", ":", "if", "any", "(", "i", ">=", "j", "for", "i", ",", "j", "in", "zip", "(", "idx_pert", ",", "self", ".", "C", ".", "shape", ")", ")", ":", "continue", "out", "+=", "[", "self", ".", "C", "[", "tuple", "(", "idx_pert", ")", "]", "]", "for", "idx_pert", "in", "Perturb", "(", "idx", ",", "-", "1", ")", ":", "if", "any", "(", "i", "<", "0", "for", "i", "in", "idx_pert", ")", ":", "continue", "out", "+=", "[", "self", ".", "C", "[", "tuple", "(", "idx_pert", ")", "]", "]", "self", ".", "itr", "+=", "1", "return", "out", ",", "self", ".", "C", "[", "idx", "]" ]
iterates over the flattened elements of C, returning the element and its forward and backward looking neighbors for each axis.
[ "iterates", "over", "the", "flattened", "elements", "of", "C", "returning", "the", "element", "and", "its", "forward", "and", "backward", "looking", "neighbors", "for", "each", "axis", "." ]
[ "''' \n iterates over the flattened elements of C, returning the element and \n its forward and backward looking neighbors for each axis.\n \n Example\n -------\n >> C = np.array([[1,2,3],\n [4,5,6]]) \n >> for i in ForwardNeighbors(C):\n print(i)\n [4,2],1\n [5,3,1],2\n [6,2],3\n [5,1],4\n [6,2,4],5\n [3,5],6\n '''", "# this checks if the perturbed indices are valid for C", "# this checks if the perturbed indices are valid for C" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
352
121
cc18910512d8e8717dae744e31f3c162d52d5582
joshualucas84/jasper-soft-server
jasperserver/jasperserver-api/engine/src/main/java/com/jaspersoft/jasperserver/api/engine/scheduling/domain/jaxb/OutputFormatXmlAdapter.java
[ "Apache-2.0" ]
Java
OutputFormatXmlAdapter
/** * This adapter is used for ReportJob.outputFormats serialization. * ReportJobOutputFormatsWrapper is used for serialization because of no ability to use @XmlElementWrapper together with @XmlJavaTypeAdapter. * See http://java.net/jira/browse/JAXB-787 * * @author Yaroslav.Kovalchyk * @version $Id: OutputFormatXmlAdapter.java 54934 2015-04-30 19:56:16Z lchirita $ */
This adapter is used for ReportJob.outputFormats serialization. ReportJobOutputFormatsWrapper is used for serialization because of no ability to use @XmlElementWrapper together with @XmlJavaTypeAdapter. @author Yaroslav.Kovalchyk @version $Id: OutputFormatXmlAdapter.java 54934 2015-04-30 19:56:16Z lchirita $
[ "This", "adapter", "is", "used", "for", "ReportJob", ".", "outputFormats", "serialization", ".", "ReportJobOutputFormatsWrapper", "is", "used", "for", "serialization", "because", "of", "no", "ability", "to", "use", "@XmlElementWrapper", "together", "with", "@XmlJavaTypeAdapter", ".", "@author", "Yaroslav", ".", "Kovalchyk", "@version", "$Id", ":", "OutputFormatXmlAdapter", ".", "java", "54934", "2015", "-", "04", "-", "30", "19", ":", "56", ":", "16Z", "lchirita", "$" ]
public class OutputFormatXmlAdapter extends XmlAdapter<ReportJobOutputFormatsWrapper, Set<Byte>> { private enum SupportedOutputFormat implements NamedPropertyHolder<Byte>{ PDF(ReportJob.OUTPUT_FORMAT_PDF), HTML(ReportJob.OUTPUT_FORMAT_HTML), XLS(ReportJob.OUTPUT_FORMAT_XLS), RTF(ReportJob.OUTPUT_FORMAT_RTF), CSV(ReportJob.OUTPUT_FORMAT_CSV), ODT(ReportJob.OUTPUT_FORMAT_ODT), TXT(ReportJob.OUTPUT_FORMAT_TXT), DOCX(ReportJob.OUTPUT_FORMAT_DOCX), ODS(ReportJob.OUTPUT_FORMAT_ODS), XLSX(ReportJob.OUTPUT_FORMAT_XLSX), XLS_NOPAG(ReportJob.OUTPUT_FORMAT_XLS_NOPAG), XLSX_NOPAG(ReportJob.OUTPUT_FORMAT_XLSX_NOPAG), DATA_SNAPSHOT(ReportJob.OUTPUT_FORMAT_DATA_SNAPSHOT), PPTX(ReportJob.OUTPUT_FORMAT_PPTX), JSON(ReportJob.OUTPUT_FORMAT_JSON); private final Byte byteValue; private SupportedOutputFormat(Byte byteValue) { this.byteValue = byteValue; } public Byte getProperty() { return this.byteValue; } } @Override public Set<Byte> unmarshal(ReportJobOutputFormatsWrapper v) throws Exception { Set<Byte> result = null; if (v != null && v.getFormats() != null && !v.getFormats().isEmpty()) { result = new HashSet<Byte>(); SingleOutputFormatAdapter adapter = new SingleOutputFormatAdapter(); for (String currentValue : v.getFormats()) { Byte currentByteValue = adapter.unmarshal(currentValue); if (currentByteValue != null) result.add(currentByteValue); } } return result; } @Override public ReportJobOutputFormatsWrapper marshal(Set<Byte> v) throws Exception { ReportJobOutputFormatsWrapper result = null; if (v != null && !v.isEmpty()) { Set<String> set = new HashSet<String>(); SingleOutputFormatAdapter adapter = new SingleOutputFormatAdapter(); for (Byte currentValue : v) { String currentStringValue = adapter.marshal(currentValue); if (currentStringValue != null) set.add(currentStringValue); } if(!set.isEmpty()){ result = new ReportJobOutputFormatsWrapper(); result.setFormats(set); } } return result; } private class SingleOutputFormatAdapter extends AbstractEnumXmlAdapter<Byte> { @Override protected NamedPropertyHolder<Byte>[] getEnumConstantsArray() { return SupportedOutputFormat.values(); } } }
[ "public", "class", "OutputFormatXmlAdapter", "extends", "XmlAdapter", "<", "ReportJobOutputFormatsWrapper", ",", "Set", "<", "Byte", ">", ">", "{", "private", "enum", "SupportedOutputFormat", "implements", "NamedPropertyHolder", "<", "Byte", ">", "{", "PDF", "(", "ReportJob", ".", "OUTPUT_FORMAT_PDF", ")", ",", "HTML", "(", "ReportJob", ".", "OUTPUT_FORMAT_HTML", ")", ",", "XLS", "(", "ReportJob", ".", "OUTPUT_FORMAT_XLS", ")", ",", "RTF", "(", "ReportJob", ".", "OUTPUT_FORMAT_RTF", ")", ",", "CSV", "(", "ReportJob", ".", "OUTPUT_FORMAT_CSV", ")", ",", "ODT", "(", "ReportJob", ".", "OUTPUT_FORMAT_ODT", ")", ",", "TXT", "(", "ReportJob", ".", "OUTPUT_FORMAT_TXT", ")", ",", "DOCX", "(", "ReportJob", ".", "OUTPUT_FORMAT_DOCX", ")", ",", "ODS", "(", "ReportJob", ".", "OUTPUT_FORMAT_ODS", ")", ",", "XLSX", "(", "ReportJob", ".", "OUTPUT_FORMAT_XLSX", ")", ",", "XLS_NOPAG", "(", "ReportJob", ".", "OUTPUT_FORMAT_XLS_NOPAG", ")", ",", "XLSX_NOPAG", "(", "ReportJob", ".", "OUTPUT_FORMAT_XLSX_NOPAG", ")", ",", "DATA_SNAPSHOT", "(", "ReportJob", ".", "OUTPUT_FORMAT_DATA_SNAPSHOT", ")", ",", "PPTX", "(", "ReportJob", ".", "OUTPUT_FORMAT_PPTX", ")", ",", "JSON", "(", "ReportJob", ".", "OUTPUT_FORMAT_JSON", ")", ";", "private", "final", "Byte", "byteValue", ";", "private", "SupportedOutputFormat", "(", "Byte", "byteValue", ")", "{", "this", ".", "byteValue", "=", "byteValue", ";", "}", "public", "Byte", "getProperty", "(", ")", "{", "return", "this", ".", "byteValue", ";", "}", "}", "@", "Override", "public", "Set", "<", "Byte", ">", "unmarshal", "(", "ReportJobOutputFormatsWrapper", "v", ")", "throws", "Exception", "{", "Set", "<", "Byte", ">", "result", "=", "null", ";", "if", "(", "v", "!=", "null", "&&", "v", ".", "getFormats", "(", ")", "!=", "null", "&&", "!", "v", ".", "getFormats", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "result", "=", "new", "HashSet", "<", "Byte", ">", "(", ")", ";", "SingleOutputFormatAdapter", "adapter", "=", "new", "SingleOutputFormatAdapter", "(", ")", ";", "for", "(", "String", "currentValue", ":", "v", ".", "getFormats", "(", ")", ")", "{", "Byte", "currentByteValue", "=", "adapter", ".", "unmarshal", "(", "currentValue", ")", ";", "if", "(", "currentByteValue", "!=", "null", ")", "result", ".", "add", "(", "currentByteValue", ")", ";", "}", "}", "return", "result", ";", "}", "@", "Override", "public", "ReportJobOutputFormatsWrapper", "marshal", "(", "Set", "<", "Byte", ">", "v", ")", "throws", "Exception", "{", "ReportJobOutputFormatsWrapper", "result", "=", "null", ";", "if", "(", "v", "!=", "null", "&&", "!", "v", ".", "isEmpty", "(", ")", ")", "{", "Set", "<", "String", ">", "set", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "SingleOutputFormatAdapter", "adapter", "=", "new", "SingleOutputFormatAdapter", "(", ")", ";", "for", "(", "Byte", "currentValue", ":", "v", ")", "{", "String", "currentStringValue", "=", "adapter", ".", "marshal", "(", "currentValue", ")", ";", "if", "(", "currentStringValue", "!=", "null", ")", "set", ".", "add", "(", "currentStringValue", ")", ";", "}", "if", "(", "!", "set", ".", "isEmpty", "(", ")", ")", "{", "result", "=", "new", "ReportJobOutputFormatsWrapper", "(", ")", ";", "result", ".", "setFormats", "(", "set", ")", ";", "}", "}", "return", "result", ";", "}", "private", "class", "SingleOutputFormatAdapter", "extends", "AbstractEnumXmlAdapter", "<", "Byte", ">", "{", "@", "Override", "protected", "NamedPropertyHolder", "<", "Byte", ">", "[", "]", "getEnumConstantsArray", "(", ")", "{", "return", "SupportedOutputFormat", ".", "values", "(", ")", ";", "}", "}", "}" ]
This adapter is used for ReportJob.outputFormats serialization.
[ "This", "adapter", "is", "used", "for", "ReportJob", ".", "outputFormats", "serialization", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
568
113
c16dba6fd7e564faca4e572ac605339521464b57
SafetyCone/R5T.S0030
source/R5T.S0030/Code/Operations/O104_AddDependencyDefinitionsToRepository.cs
[ "MIT" ]
C#
O104_AddDependencyDefinitionsToRepository
/// <summary> /// Initial attempt. /// See <see cref="O105B_AddServiceImplementationsToRepository"/>. /// /// Foreach service implementation in the repository, determine the *zero, one, or many* service definitions upon which the service implementation depends. /// Make the assumption that a service implementation only depends on service definitions (i.e. that a service implementation will not have service implementation as a dependency). /// TODO: this should be service *components* not definitions, but we'll go with definitions for now. /// /// For each service implementation in the repository, examine the code file, find the implementation class, then find the class's constructor, it if has one. /// * If the class has no constructor, then we are done: the service implementation has no service definition dependencies. /// * If the class has more than one constructor, look for the constructor marked with the R5T.T0064.ServiceImplementationConstructorMarkerAttribute. /// * If none is found, warn that we are going with the first constructor. /// * If one constructor is found, use it. /// /// Then examine all input parameter types for the constructor. /// * If all parameter types are recognized as service definitions, then add the service definitions as dependencies of the service implementation. /// * If any of the parameter types are *not* recognized as service definitions, do not add the service definitions as dependencies of the service implementation. /// </summary>
Initial attempt. See . Foreach service implementation in the repository, determine the *zero, one, or many* service definitions upon which the service implementation depends. Make the assumption that a service implementation only depends on service definitions . TODO: this should be service *components* not definitions, but we'll go with definitions for now. For each service implementation in the repository, examine the code file, find the implementation class, then find the class's constructor, it if has one. If the class has no constructor, then we are done: the service implementation has no service definition dependencies. If the class has more than one constructor, look for the constructor marked with the R5T.T0064.ServiceImplementationConstructorMarkerAttribute. If none is found, warn that we are going with the first constructor. If one constructor is found, use it. Then examine all input parameter types for the constructor. If all parameter types are recognized as service definitions, then add the service definitions as dependencies of the service implementation. If any of the parameter types are *not* recognized as service definitions, do not add the service definitions as dependencies of the service implementation.
[ "Initial", "attempt", ".", "See", ".", "Foreach", "service", "implementation", "in", "the", "repository", "determine", "the", "*", "zero", "one", "or", "many", "*", "service", "definitions", "upon", "which", "the", "service", "implementation", "depends", ".", "Make", "the", "assumption", "that", "a", "service", "implementation", "only", "depends", "on", "service", "definitions", ".", "TODO", ":", "this", "should", "be", "service", "*", "components", "*", "not", "definitions", "but", "we", "'", "ll", "go", "with", "definitions", "for", "now", ".", "For", "each", "service", "implementation", "in", "the", "repository", "examine", "the", "code", "file", "find", "the", "implementation", "class", "then", "find", "the", "class", "'", "s", "constructor", "it", "if", "has", "one", ".", "If", "the", "class", "has", "no", "constructor", "then", "we", "are", "done", ":", "the", "service", "implementation", "has", "no", "service", "definition", "dependencies", ".", "If", "the", "class", "has", "more", "than", "one", "constructor", "look", "for", "the", "constructor", "marked", "with", "the", "R5T", ".", "T0064", ".", "ServiceImplementationConstructorMarkerAttribute", ".", "If", "none", "is", "found", "warn", "that", "we", "are", "going", "with", "the", "first", "constructor", ".", "If", "one", "constructor", "is", "found", "use", "it", ".", "Then", "examine", "all", "input", "parameter", "types", "for", "the", "constructor", ".", "If", "all", "parameter", "types", "are", "recognized", "as", "service", "definitions", "then", "add", "the", "service", "definitions", "as", "dependencies", "of", "the", "service", "implementation", ".", "If", "any", "of", "the", "parameter", "types", "are", "*", "not", "*", "recognized", "as", "service", "definitions", "do", "not", "add", "the", "service", "definitions", "as", "dependencies", "of", "the", "service", "implementation", "." ]
[OperationMarker] public class O104_AddDependencyDefinitionsToRepository : IActionOperation { private IHumanOutput HumanOutput { get; } private IHumanOutputFilePathProvider HumanOutputFilePathProvider { get; } private ILogger Logger { get; } private IMainFileContextFilePathsProvider MainFileContextFilePathsProvider { get; } private INotepadPlusPlusOperator NotepadPlusPlusOperator { get; } private IOutputFilePathProvider OutputFilePathProvider { get; } private IServiceRepository ServiceRepository { get; } public O104_AddDependencyDefinitionsToRepository( IHumanOutput humanOutput, IHumanOutputFilePathProvider humanOutputFilePathProvider, ILogger<O103_AddImplementedDefinitionToRepository> logger, IMainFileContextFilePathsProvider mainFileContextFilePathsProvider, INotepadPlusPlusOperator notepadPlusPlusOperator, IOutputFilePathProvider outputFilePathProvider, IServiceRepository serviceRepository) { this.HumanOutput = humanOutput; this.HumanOutputFilePathProvider = humanOutputFilePathProvider; this.Logger = logger; this.MainFileContextFilePathsProvider = mainFileContextFilePathsProvider; this.NotepadPlusPlusOperator = notepadPlusPlusOperator; this.OutputFilePathProvider = outputFilePathProvider; this.ServiceRepository = serviceRepository; } public async Task Run() { this.Logger.LogInformation("Getting all current service implementations and service definitions..."); var implementations = await this.ServiceRepository.GetAllServiceImplementations(); var definitions = await this.ServiceRepository.GetAllServiceDefinitions(); var implementationsCount = implementations.Length; this.HumanOutput.WriteLine($"Found {implementationsCount} service implementations and {definitions.Length} service definitions..."); this.Logger.LogInformation($"Found {implementationsCount} service implementations and {definitions.Length} service definitions..."); definitions.VerifyDistinctByName(); var definitionsByNamespacedTypeNames = definitions .ToDictionary( x => x.TypeName); var availableDefinitionNamespacedTypeNames = definitionsByNamespacedTypeNames.Keys; var failures = new List<Failure<ServiceImplementation>>(); var warnings = new List<Warning<ServiceImplementation>>(); var noDependencies = new List<Message<ServiceImplementation>>(); var dependencySetsByImplementation = new Dictionary<ServiceImplementation, ServiceDefinition[]>(); foreach (var implementation in implementations) { var implementationDescription = $"{Instances.NamespacedTypeNameOperator.GetTypeName(implementation.TypeName)}: {implementation.TypeName}"; this.Logger.LogInformation($"Processing service implementation '{implementationDescription}'..."); var codeFileExists = Instances.FileSystemOperator.FileExists(implementation.CodeFilePath); if (!codeFileExists) { failures.Add( Failure.Of(implementation, $"Unable to find code file: {implementation.CodeFilePath}")); this.Logger.LogError($"Unable to find code file for service implementation {implementation.TypeName}:\n{implementation.CodeFilePath}"); continue; } var originalCompilationUnit = await Instances.CompilationUnitOperator_Old.Load(implementation.CodeFilePath); var compilationUnit = originalCompilationUnit; var implementationNamespacedTypeName = implementation.TypeName; var implementationNamespaceName = Instances.NamespacedTypeNameOperator.GetNamespaceName(implementationNamespacedTypeName); var implementationClassName = Instances.NamespacedTypeNameOperator.GetTypeName(implementationNamespacedTypeName); var namespaceWasFound = originalCompilationUnit.HasNamespace_HandleNested(implementationNamespaceName); if (!namespaceWasFound) { failures.Add( Failure.Of(implementation, $"Unable to find namespace '{implementationNamespaceName}'.")); this.Logger.LogError($"Unable to find namespace '{implementationNamespaceName}' in code file:\n{implementation.CodeFilePath}"); continue; } var classWasFound = namespaceWasFound.Result.HasClass(implementationClassName); if (!classWasFound) { failures.Add( Failure.Of(implementation, $"Unable to find class '{implementationClassName}'.")); this.Logger.LogError($"Unable to find class '{implementationClassName}' in namespace: {implementationNamespaceName}."); continue; } var constructors = classWasFound.Result .GetConstructors() .Now(); var constructorCount = constructors.Length; if (constructorCount < 1) { noDependencies.Add( Message.For(implementation, "No dependencies found: no constructor method found.")); this.Logger.LogInformation($"No contructor found for service implementation {implementationClassName}, so no service depenencies."); continue; } var constructor = constructors.First(); if(constructorCount > 1) { var constructorsWithMarkerAttribute = constructors .Where(x => x.HasAttributeOfType<T0064.ServiceImplementationConstructorMarkerAttribute>()) .Now(); var constructorsWithMarkerAttributeCount = constructorsWithMarkerAttribute.Length; if(constructorsWithMarkerAttributeCount < 1) { warnings.Add( Warning.For(implementation, $"Multiple constructors found for service implementation {implementationClassName}, but none had the {nameof(T0064.ServiceImplementationConstructorMarkerAttribute)} attribute. Thus, the first constructor will be used.")); this.Logger.LogWarning($"Multiple constructors found for service implementation {implementationClassName}, but none had the {nameof(T0064.ServiceImplementationConstructorMarkerAttribute)} attribute. Thus, the first constructor will be used."); } else { constructor = constructorsWithMarkerAttribute.First(); if(constructorsWithMarkerAttributeCount > 1) { warnings.Add( Warning.For(implementation, $"Multiple constructors found for service implementation {implementationClassName} with the {nameof(T0064.ServiceImplementationConstructorMarkerAttribute)} attribute. Thus, the first constructor with the attribute will be used.")); this.Logger.LogWarning($"Multiple constructors found for service implementation {implementationClassName} with the {nameof(T0064.ServiceImplementationConstructorMarkerAttribute)} attribute. Thus, the first constructor with the attribute will be used."); } } } var parameters = constructor .GetParameters() .Now(); var parametersCount = parameters.Length; if(parametersCount < 1) { noDependencies.Add( Message.For(implementation, "No dependencies found: no input parameters for constructor method found.")); this.Logger.LogInformation($"No parameters found for for contructor for service implementation {implementationClassName}, so no service depenencies."); continue; } var parameterTypes = parameters .Select(x => x.Type) .Now(); compilationUnit = compilationUnit.AnnotateNodes_Typed( parameterTypes, out var typedAnnotationsByParameterTypes); var parameterTypesByTypedAnnotation = typedAnnotationsByParameterTypes.Invert(); var parameterDefinitionNamespacedTypeNamesByTypedAnnotation = Instances.Operation.TryGuessNamespacedTypeNames( availableDefinitionNamespacedTypeNames, compilationUnit, parameterTypesByTypedAnnotation.Keys); var parameterDefinitionNamespacedTypeNamesFound = parameterDefinitionNamespacedTypeNamesByTypedAnnotation.Values .Where(x => x.Exists) .Select(x => x.Result) .Now(); var noParameterDefinitionNamespacedTypeNameWasFound = parameterDefinitionNamespacedTypeNamesFound.None(); if (noParameterDefinitionNamespacedTypeNameWasFound) { failures.Add( Failure.Of(implementation, $"No service definitions found among the parameter types for the chosen constructor of implementation class '{implementationClassName}'.")); this.Logger.LogError($"No service definitions found among the parameter types for the chosen constructor of implementation class '{implementationClassName}'."); continue; } var allParametersAreDefinitions = parameters.Length == parameterDefinitionNamespacedTypeNamesFound.Length; if(!allParametersAreDefinitions) { failures.Add( Failure.Of(implementation, $"Not all input parameters of the chosen constructor were service definitions found among the available service definitions for implementation class '{implementationClassName}'.")); this.Logger.LogError($"Not all input parameters of the chosen constructor were service definitions found among the available service definitions for implementation class '{implementationClassName}'."); continue; } var dependencyServiceDefinitions = parameterDefinitionNamespacedTypeNamesFound .Select(x => definitionsByNamespacedTypeNames[x]) .Now(); dependencySetsByImplementation.Add(implementation, dependencyServiceDefinitions); this.Logger.LogInformation($"Processed service implementation {implementationDescription}, found {dependencyServiceDefinitions.Length} dependency services."); } this.Logger.LogInformation("Finished processing service implementations."); var failureCount = failures.Count; var warningsCount = warnings.Count; var noDependenciesCount = noDependencies.Count; var successesCount = dependencySetsByImplementation.Count; var resultsCount = failureCount + successesCount + noDependenciesCount; this.HumanOutput.WriteLine($"Determined service definitions for {implementations.Length} service implementations:\n\t+ {failureCount} failures,\n\t+ {successesCount} successes,\n\t+ {noDependenciesCount} no dependencies,\n\t= {resultsCount} (all accounted for: {(resultsCount == implementationsCount).YesOrNo().ToUpperInvariant()})\n\tAdditionally, {warningsCount} warnings."); this.Logger.LogInformation("Determining new and departed service implementation-to-dependency definition mappings..."); var dependencyDefinitionsByImplementation = await this.ServiceRepository.HasDependencyDefinitions( dependencySetsByImplementation.Keys); var dependencySetsJoinedByImplementations = dependencySetsByImplementation .Join(dependencyDefinitionsByImplementation, x => x.Key, x => x.Key, (x, y) => new { Implementation = x.Key, CurrentDependencies = x.Value, RepositoryDependencies = y.Value.Result }, NamedFilePathedEqualityComparer.Instance) ; var departedDependencyDefinitionMappings = dependencySetsJoinedByImplementations .SelectMany(x => { var departed = x.RepositoryDependencies .Except(x.CurrentDependencies, NamedFilePathedEqualityComparer<ServiceDefinition>.Instance) .Select(xServiceDefinition => DependencyDefinitionMapping.From(x.Implementation, xServiceDefinition)) ; return departed; }) .Now(); var newDependencyDefinitionMappings = dependencySetsJoinedByImplementations .SelectMany(x => { var departed = x.CurrentDependencies .Except(x.RepositoryDependencies, NamedFilePathedEqualityComparer<ServiceDefinition>.Instance) .Select(xServiceDefinition => DependencyDefinitionMapping.From(x.Implementation, xServiceDefinition)) ; return departed; }) .Now(); var departedImplementedDefinitionMappingsCount = departedDependencyDefinitionMappings.Length; this.HumanOutput.WriteLine($"Found {departedImplementedDefinitionMappingsCount} departed service implementation-to-dependency definition mappings."); var newImplementedDefinitionMappingsCount = newDependencyDefinitionMappings.Length; this.HumanOutput.WriteLine($"Found {newImplementedDefinitionMappingsCount} new service implementation-to-dependency definition mappings."); this.Logger.LogInformation("Removing departed service implementation-to-dependency definition mappings from the repository..."); await this.ServiceRepository.DeleteDependencyDefinitions(departedDependencyDefinitionMappings); this.Logger.LogInformation("Adding new service implementation-to-dependency definition mappings to the repository..."); await this.ServiceRepository.AddDependencyDefinitions(newDependencyDefinitionMappings); this.Logger.LogInformation("Finished updating service repository."); var humanOutputFilePath = await this.HumanOutputFilePathProvider.GetHumanOutputFilePath(); await this.NotepadPlusPlusOperator.OpenFilePath(humanOutputFilePath); this.Logger.LogInformation("Writing output files."); var outputFilePath = await this.OutputFilePathProvider.GetOutputFilePath("Implementation Dependency Results.txt"); var lines = failures .OrderBy(x => x.Value.TypeName) .Select(x => $"{x.Value.TypeName}:\n\t{x.Message}\n({x.Value.CodeFilePath})\n") ; await FileHelper.WriteAllLines( outputFilePath, lines); await this.NotepadPlusPlusOperator.OpenFilePath(outputFilePath); var toDependencyDefinitionMappingsJsonFilePath = await this.MainFileContextFilePathsProvider.GetToDependencyDefinitionMappingsJsonFilePath(); await this.NotepadPlusPlusOperator.OpenFilePath(toDependencyDefinitionMappingsJsonFilePath); } }
[ "[", "OperationMarker", "]", "public", "class", "O104_AddDependencyDefinitionsToRepository", ":", "IActionOperation", "{", "private", "IHumanOutput", "HumanOutput", "{", "get", ";", "}", "private", "IHumanOutputFilePathProvider", "HumanOutputFilePathProvider", "{", "get", ";", "}", "private", "ILogger", "Logger", "{", "get", ";", "}", "private", "IMainFileContextFilePathsProvider", "MainFileContextFilePathsProvider", "{", "get", ";", "}", "private", "INotepadPlusPlusOperator", "NotepadPlusPlusOperator", "{", "get", ";", "}", "private", "IOutputFilePathProvider", "OutputFilePathProvider", "{", "get", ";", "}", "private", "IServiceRepository", "ServiceRepository", "{", "get", ";", "}", "public", "O104_AddDependencyDefinitionsToRepository", "(", "IHumanOutput", "humanOutput", ",", "IHumanOutputFilePathProvider", "humanOutputFilePathProvider", ",", "ILogger", "<", "O103_AddImplementedDefinitionToRepository", ">", "logger", ",", "IMainFileContextFilePathsProvider", "mainFileContextFilePathsProvider", ",", "INotepadPlusPlusOperator", "notepadPlusPlusOperator", ",", "IOutputFilePathProvider", "outputFilePathProvider", ",", "IServiceRepository", "serviceRepository", ")", "{", "this", ".", "HumanOutput", "=", "humanOutput", ";", "this", ".", "HumanOutputFilePathProvider", "=", "humanOutputFilePathProvider", ";", "this", ".", "Logger", "=", "logger", ";", "this", ".", "MainFileContextFilePathsProvider", "=", "mainFileContextFilePathsProvider", ";", "this", ".", "NotepadPlusPlusOperator", "=", "notepadPlusPlusOperator", ";", "this", ".", "OutputFilePathProvider", "=", "outputFilePathProvider", ";", "this", ".", "ServiceRepository", "=", "serviceRepository", ";", "}", "public", "async", "Task", "Run", "(", ")", "{", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Getting all current service implementations and service definitions...", "\"", ")", ";", "var", "implementations", "=", "await", "this", ".", "ServiceRepository", ".", "GetAllServiceImplementations", "(", ")", ";", "var", "definitions", "=", "await", "this", ".", "ServiceRepository", ".", "GetAllServiceDefinitions", "(", ")", ";", "var", "implementationsCount", "=", "implementations", ".", "Length", ";", "this", ".", "HumanOutput", ".", "WriteLine", "(", "$\"", "Found ", "{", "implementationsCount", "}", " service implementations and ", "{", "definitions", ".", "Length", "}", " service definitions...", "\"", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "$\"", "Found ", "{", "implementationsCount", "}", " service implementations and ", "{", "definitions", ".", "Length", "}", " service definitions...", "\"", ")", ";", "definitions", ".", "VerifyDistinctByName", "(", ")", ";", "var", "definitionsByNamespacedTypeNames", "=", "definitions", ".", "ToDictionary", "(", "x", "=>", "x", ".", "TypeName", ")", ";", "var", "availableDefinitionNamespacedTypeNames", "=", "definitionsByNamespacedTypeNames", ".", "Keys", ";", "var", "failures", "=", "new", "List", "<", "Failure", "<", "ServiceImplementation", ">", ">", "(", ")", ";", "var", "warnings", "=", "new", "List", "<", "Warning", "<", "ServiceImplementation", ">", ">", "(", ")", ";", "var", "noDependencies", "=", "new", "List", "<", "Message", "<", "ServiceImplementation", ">", ">", "(", ")", ";", "var", "dependencySetsByImplementation", "=", "new", "Dictionary", "<", "ServiceImplementation", ",", "ServiceDefinition", "[", "]", ">", "(", ")", ";", "foreach", "(", "var", "implementation", "in", "implementations", ")", "{", "var", "implementationDescription", "=", "$\"", "{", "Instances", ".", "NamespacedTypeNameOperator", ".", "GetTypeName", "(", "implementation", ".", "TypeName", ")", "}", ": ", "{", "implementation", ".", "TypeName", "}", "\"", ";", "this", ".", "Logger", ".", "LogInformation", "(", "$\"", "Processing service implementation '", "{", "implementationDescription", "}", "'...", "\"", ")", ";", "var", "codeFileExists", "=", "Instances", ".", "FileSystemOperator", ".", "FileExists", "(", "implementation", ".", "CodeFilePath", ")", ";", "if", "(", "!", "codeFileExists", ")", "{", "failures", ".", "Add", "(", "Failure", ".", "Of", "(", "implementation", ",", "$\"", "Unable to find code file: ", "{", "implementation", ".", "CodeFilePath", "}", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogError", "(", "$\"", "Unable to find code file for service implementation ", "{", "implementation", ".", "TypeName", "}", ":", "\\n", "{", "implementation", ".", "CodeFilePath", "}", "\"", ")", ";", "continue", ";", "}", "var", "originalCompilationUnit", "=", "await", "Instances", ".", "CompilationUnitOperator_Old", ".", "Load", "(", "implementation", ".", "CodeFilePath", ")", ";", "var", "compilationUnit", "=", "originalCompilationUnit", ";", "var", "implementationNamespacedTypeName", "=", "implementation", ".", "TypeName", ";", "var", "implementationNamespaceName", "=", "Instances", ".", "NamespacedTypeNameOperator", ".", "GetNamespaceName", "(", "implementationNamespacedTypeName", ")", ";", "var", "implementationClassName", "=", "Instances", ".", "NamespacedTypeNameOperator", ".", "GetTypeName", "(", "implementationNamespacedTypeName", ")", ";", "var", "namespaceWasFound", "=", "originalCompilationUnit", ".", "HasNamespace_HandleNested", "(", "implementationNamespaceName", ")", ";", "if", "(", "!", "namespaceWasFound", ")", "{", "failures", ".", "Add", "(", "Failure", ".", "Of", "(", "implementation", ",", "$\"", "Unable to find namespace '", "{", "implementationNamespaceName", "}", "'.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogError", "(", "$\"", "Unable to find namespace '", "{", "implementationNamespaceName", "}", "' in code file:", "\\n", "{", "implementation", ".", "CodeFilePath", "}", "\"", ")", ";", "continue", ";", "}", "var", "classWasFound", "=", "namespaceWasFound", ".", "Result", ".", "HasClass", "(", "implementationClassName", ")", ";", "if", "(", "!", "classWasFound", ")", "{", "failures", ".", "Add", "(", "Failure", ".", "Of", "(", "implementation", ",", "$\"", "Unable to find class '", "{", "implementationClassName", "}", "'.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogError", "(", "$\"", "Unable to find class '", "{", "implementationClassName", "}", "' in namespace: ", "{", "implementationNamespaceName", "}", ".", "\"", ")", ";", "continue", ";", "}", "var", "constructors", "=", "classWasFound", ".", "Result", ".", "GetConstructors", "(", ")", ".", "Now", "(", ")", ";", "var", "constructorCount", "=", "constructors", ".", "Length", ";", "if", "(", "constructorCount", "<", "1", ")", "{", "noDependencies", ".", "Add", "(", "Message", ".", "For", "(", "implementation", ",", "\"", "No dependencies found: no constructor method found.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "$\"", "No contructor found for service implementation ", "{", "implementationClassName", "}", ", so no service depenencies.", "\"", ")", ";", "continue", ";", "}", "var", "constructor", "=", "constructors", ".", "First", "(", ")", ";", "if", "(", "constructorCount", ">", "1", ")", "{", "var", "constructorsWithMarkerAttribute", "=", "constructors", ".", "Where", "(", "x", "=>", "x", ".", "HasAttributeOfType", "<", "T0064", ".", "ServiceImplementationConstructorMarkerAttribute", ">", "(", ")", ")", ".", "Now", "(", ")", ";", "var", "constructorsWithMarkerAttributeCount", "=", "constructorsWithMarkerAttribute", ".", "Length", ";", "if", "(", "constructorsWithMarkerAttributeCount", "<", "1", ")", "{", "warnings", ".", "Add", "(", "Warning", ".", "For", "(", "implementation", ",", "$\"", "Multiple constructors found for service implementation ", "{", "implementationClassName", "}", ", but none had the ", "{", "nameof", "(", "T0064", ".", "ServiceImplementationConstructorMarkerAttribute", ")", "}", " attribute. Thus, the first constructor will be used.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogWarning", "(", "$\"", "Multiple constructors found for service implementation ", "{", "implementationClassName", "}", ", but none had the ", "{", "nameof", "(", "T0064", ".", "ServiceImplementationConstructorMarkerAttribute", ")", "}", " attribute. Thus, the first constructor will be used.", "\"", ")", ";", "}", "else", "{", "constructor", "=", "constructorsWithMarkerAttribute", ".", "First", "(", ")", ";", "if", "(", "constructorsWithMarkerAttributeCount", ">", "1", ")", "{", "warnings", ".", "Add", "(", "Warning", ".", "For", "(", "implementation", ",", "$\"", "Multiple constructors found for service implementation ", "{", "implementationClassName", "}", " with the ", "{", "nameof", "(", "T0064", ".", "ServiceImplementationConstructorMarkerAttribute", ")", "}", " attribute. Thus, the first constructor with the attribute will be used.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogWarning", "(", "$\"", "Multiple constructors found for service implementation ", "{", "implementationClassName", "}", " with the ", "{", "nameof", "(", "T0064", ".", "ServiceImplementationConstructorMarkerAttribute", ")", "}", " attribute. Thus, the first constructor with the attribute will be used.", "\"", ")", ";", "}", "}", "}", "var", "parameters", "=", "constructor", ".", "GetParameters", "(", ")", ".", "Now", "(", ")", ";", "var", "parametersCount", "=", "parameters", ".", "Length", ";", "if", "(", "parametersCount", "<", "1", ")", "{", "noDependencies", ".", "Add", "(", "Message", ".", "For", "(", "implementation", ",", "\"", "No dependencies found: no input parameters for constructor method found.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "$\"", "No parameters found for for contructor for service implementation ", "{", "implementationClassName", "}", ", so no service depenencies.", "\"", ")", ";", "continue", ";", "}", "var", "parameterTypes", "=", "parameters", ".", "Select", "(", "x", "=>", "x", ".", "Type", ")", ".", "Now", "(", ")", ";", "compilationUnit", "=", "compilationUnit", ".", "AnnotateNodes_Typed", "(", "parameterTypes", ",", "out", "var", "typedAnnotationsByParameterTypes", ")", ";", "var", "parameterTypesByTypedAnnotation", "=", "typedAnnotationsByParameterTypes", ".", "Invert", "(", ")", ";", "var", "parameterDefinitionNamespacedTypeNamesByTypedAnnotation", "=", "Instances", ".", "Operation", ".", "TryGuessNamespacedTypeNames", "(", "availableDefinitionNamespacedTypeNames", ",", "compilationUnit", ",", "parameterTypesByTypedAnnotation", ".", "Keys", ")", ";", "var", "parameterDefinitionNamespacedTypeNamesFound", "=", "parameterDefinitionNamespacedTypeNamesByTypedAnnotation", ".", "Values", ".", "Where", "(", "x", "=>", "x", ".", "Exists", ")", ".", "Select", "(", "x", "=>", "x", ".", "Result", ")", ".", "Now", "(", ")", ";", "var", "noParameterDefinitionNamespacedTypeNameWasFound", "=", "parameterDefinitionNamespacedTypeNamesFound", ".", "None", "(", ")", ";", "if", "(", "noParameterDefinitionNamespacedTypeNameWasFound", ")", "{", "failures", ".", "Add", "(", "Failure", ".", "Of", "(", "implementation", ",", "$\"", "No service definitions found among the parameter types for the chosen constructor of implementation class '", "{", "implementationClassName", "}", "'.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogError", "(", "$\"", "No service definitions found among the parameter types for the chosen constructor of implementation class '", "{", "implementationClassName", "}", "'.", "\"", ")", ";", "continue", ";", "}", "var", "allParametersAreDefinitions", "=", "parameters", ".", "Length", "==", "parameterDefinitionNamespacedTypeNamesFound", ".", "Length", ";", "if", "(", "!", "allParametersAreDefinitions", ")", "{", "failures", ".", "Add", "(", "Failure", ".", "Of", "(", "implementation", ",", "$\"", "Not all input parameters of the chosen constructor were service definitions found among the available service definitions for implementation class '", "{", "implementationClassName", "}", "'.", "\"", ")", ")", ";", "this", ".", "Logger", ".", "LogError", "(", "$\"", "Not all input parameters of the chosen constructor were service definitions found among the available service definitions for implementation class '", "{", "implementationClassName", "}", "'.", "\"", ")", ";", "continue", ";", "}", "var", "dependencyServiceDefinitions", "=", "parameterDefinitionNamespacedTypeNamesFound", ".", "Select", "(", "x", "=>", "definitionsByNamespacedTypeNames", "[", "x", "]", ")", ".", "Now", "(", ")", ";", "dependencySetsByImplementation", ".", "Add", "(", "implementation", ",", "dependencyServiceDefinitions", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "$\"", "Processed service implementation ", "{", "implementationDescription", "}", ", found ", "{", "dependencyServiceDefinitions", ".", "Length", "}", " dependency services.", "\"", ")", ";", "}", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Finished processing service implementations.", "\"", ")", ";", "var", "failureCount", "=", "failures", ".", "Count", ";", "var", "warningsCount", "=", "warnings", ".", "Count", ";", "var", "noDependenciesCount", "=", "noDependencies", ".", "Count", ";", "var", "successesCount", "=", "dependencySetsByImplementation", ".", "Count", ";", "var", "resultsCount", "=", "failureCount", "+", "successesCount", "+", "noDependenciesCount", ";", "this", ".", "HumanOutput", ".", "WriteLine", "(", "$\"", "Determined service definitions for ", "{", "implementations", ".", "Length", "}", " service implementations:", "\\n", "\\t", "+ ", "{", "failureCount", "}", " failures,", "\\n", "\\t", "+ ", "{", "successesCount", "}", " successes,", "\\n", "\\t", "+ ", "{", "noDependenciesCount", "}", " no dependencies,", "\\n", "\\t", "= ", "{", "resultsCount", "}", " (all accounted for: ", "{", "(", "resultsCount", "==", "implementationsCount", ")", ".", "YesOrNo", "(", ")", ".", "ToUpperInvariant", "(", ")", "}", ")", "\\n", "\\t", "Additionally, ", "{", "warningsCount", "}", " warnings.", "\"", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Determining new and departed service implementation-to-dependency definition mappings...", "\"", ")", ";", "var", "dependencyDefinitionsByImplementation", "=", "await", "this", ".", "ServiceRepository", ".", "HasDependencyDefinitions", "(", "dependencySetsByImplementation", ".", "Keys", ")", ";", "var", "dependencySetsJoinedByImplementations", "=", "dependencySetsByImplementation", ".", "Join", "(", "dependencyDefinitionsByImplementation", ",", "x", "=>", "x", ".", "Key", ",", "x", "=>", "x", ".", "Key", ",", "(", "x", ",", "y", ")", "=>", "new", "{", "Implementation", "=", "x", ".", "Key", ",", "CurrentDependencies", "=", "x", ".", "Value", ",", "RepositoryDependencies", "=", "y", ".", "Value", ".", "Result", "}", ",", "NamedFilePathedEqualityComparer", ".", "Instance", ")", ";", "var", "departedDependencyDefinitionMappings", "=", "dependencySetsJoinedByImplementations", ".", "SelectMany", "(", "x", "=>", "{", "var", "departed", "=", "x", ".", "RepositoryDependencies", ".", "Except", "(", "x", ".", "CurrentDependencies", ",", "NamedFilePathedEqualityComparer", "<", "ServiceDefinition", ">", ".", "Instance", ")", ".", "Select", "(", "xServiceDefinition", "=>", "DependencyDefinitionMapping", ".", "From", "(", "x", ".", "Implementation", ",", "xServiceDefinition", ")", ")", ";", "return", "departed", ";", "}", ")", ".", "Now", "(", ")", ";", "var", "newDependencyDefinitionMappings", "=", "dependencySetsJoinedByImplementations", ".", "SelectMany", "(", "x", "=>", "{", "var", "departed", "=", "x", ".", "CurrentDependencies", ".", "Except", "(", "x", ".", "RepositoryDependencies", ",", "NamedFilePathedEqualityComparer", "<", "ServiceDefinition", ">", ".", "Instance", ")", ".", "Select", "(", "xServiceDefinition", "=>", "DependencyDefinitionMapping", ".", "From", "(", "x", ".", "Implementation", ",", "xServiceDefinition", ")", ")", ";", "return", "departed", ";", "}", ")", ".", "Now", "(", ")", ";", "var", "departedImplementedDefinitionMappingsCount", "=", "departedDependencyDefinitionMappings", ".", "Length", ";", "this", ".", "HumanOutput", ".", "WriteLine", "(", "$\"", "Found ", "{", "departedImplementedDefinitionMappingsCount", "}", " departed service implementation-to-dependency definition mappings.", "\"", ")", ";", "var", "newImplementedDefinitionMappingsCount", "=", "newDependencyDefinitionMappings", ".", "Length", ";", "this", ".", "HumanOutput", ".", "WriteLine", "(", "$\"", "Found ", "{", "newImplementedDefinitionMappingsCount", "}", " new service implementation-to-dependency definition mappings.", "\"", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Removing departed service implementation-to-dependency definition mappings from the repository...", "\"", ")", ";", "await", "this", ".", "ServiceRepository", ".", "DeleteDependencyDefinitions", "(", "departedDependencyDefinitionMappings", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Adding new service implementation-to-dependency definition mappings to the repository...", "\"", ")", ";", "await", "this", ".", "ServiceRepository", ".", "AddDependencyDefinitions", "(", "newDependencyDefinitionMappings", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Finished updating service repository.", "\"", ")", ";", "var", "humanOutputFilePath", "=", "await", "this", ".", "HumanOutputFilePathProvider", ".", "GetHumanOutputFilePath", "(", ")", ";", "await", "this", ".", "NotepadPlusPlusOperator", ".", "OpenFilePath", "(", "humanOutputFilePath", ")", ";", "this", ".", "Logger", ".", "LogInformation", "(", "\"", "Writing output files.", "\"", ")", ";", "var", "outputFilePath", "=", "await", "this", ".", "OutputFilePathProvider", ".", "GetOutputFilePath", "(", "\"", "Implementation Dependency Results.txt", "\"", ")", ";", "var", "lines", "=", "failures", ".", "OrderBy", "(", "x", "=>", "x", ".", "Value", ".", "TypeName", ")", ".", "Select", "(", "x", "=>", "$\"", "{", "x", ".", "Value", ".", "TypeName", "}", ":", "\\n", "\\t", "{", "x", ".", "Message", "}", "\\n", "(", "{", "x", ".", "Value", ".", "CodeFilePath", "}", ")", "\\n", "\"", ")", ";", "await", "FileHelper", ".", "WriteAllLines", "(", "outputFilePath", ",", "lines", ")", ";", "await", "this", ".", "NotepadPlusPlusOperator", ".", "OpenFilePath", "(", "outputFilePath", ")", ";", "var", "toDependencyDefinitionMappingsJsonFilePath", "=", "await", "this", ".", "MainFileContextFilePathsProvider", ".", "GetToDependencyDefinitionMappingsJsonFilePath", "(", ")", ";", "await", "this", ".", "NotepadPlusPlusOperator", ".", "OpenFilePath", "(", "toDependencyDefinitionMappingsJsonFilePath", ")", ";", "}", "}" ]
Initial attempt.
[ "Initial", "attempt", "." ]
[ "/// Get input data.", "//// For debugging.", "//implementations = implementations.Where(x => x.TypeName == \"R5T.S0030.ProjectFilePathsProvider\").Now();", "// Verify. Can disaggregate service definitions with the same namespaced type name using to-project mapping information, but that is lots of extra work!", "// For now just error.", "/// Determine implemented service definitions for each service implementation.", "// No need to do anything since the implementation has no dependencies.", "// Do *not* check properties of the implementation since it's only the constructor that is actually used by the DI container.", "// Use the first constructor regardless of whether there are one or more.", "// If there are more, and a constructor other than the first has the marker attribute, the first constructor with the marker attribute will be used.", "// Do any of the constructors have the T0064.ServiceImplementationConstructorMarkerAttribute?", "// The first constructor with the marker attribute will be used regardless of wehther ther are one or more.", "// No need to do anything since the implementation has no dependencies.", "// Do *not* check properties of the implementation since it's only the constructor that is actually used by the DI container.", "// Type should not be null, be apparently could be, since I think the parameter syntax is used both on the caller and callee sides, and the caller would not specify the type.", "// Disregard the service dependencies that were found since not all were found.", "/// Summarize.", "/// Update the repository (with the successes).", "// Delete first (in case any mappings have changed, so we don't violate the uniqueness constraint on implementation).", "// Then add new.", "/// Display human output.", "/// Write and show output unique to the operation.", "/// Display results." ]
[ { "param": "IActionOperation", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IActionOperation", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
26
2,460
296
4c005c0e28d7352dde38d3a78f86ca7e4d30bde6
longgediyi999/sparrow
packages/sparrow-utils/dist/events.js
[ "MIT" ]
JavaScript
Events
/** * @module eventDispatcher * * Has two important methods: * - {Function} on - appends subscriber to the event. If event doesn't exist - creates new one * - {Function} emit - fires all subscribers with data * - {Function off - unsubsribes callback * * @version 1.0.0 * * @typedef {Events} Events * @property {Object} subscribers - all subscribers grouped by event name */
@module eventDispatcher Has two important methods: - {Function} on - appends subscriber to the event. @typedef {Events} Events @property {Object} subscribers - all subscribers grouped by event name
[ "@module", "eventDispatcher", "Has", "two", "important", "methods", ":", "-", "{", "Function", "}", "on", "-", "appends", "subscriber", "to", "the", "event", ".", "@typedef", "{", "Events", "}", "Events", "@property", "{", "Object", "}", "subscribers", "-", "all", "subscribers", "grouped", "by", "event", "name" ]
class Events { constructor() { /** * Object with events` names as key and array of callback functions as value * @type {{}} */ this.subscribers = {}; } /** * Subscribe any event on callback * * @param {String} eventName - event name * @param {Function} callback - subscriber */ on(eventName, callback) { if (!(eventName in this.subscribers)) { this.subscribers[eventName] = []; } // group by events this.subscribers[eventName].push(callback); } /** * Emit callbacks with passed data * * @param {String} eventName - event name * @param {Object} data - subscribers get this data when they were fired */ emit(eventName, data) { if (!this.subscribers[eventName]) { return; } this.subscribers[eventName].reduce((previousData, currentHandler) => { const newData = currentHandler(previousData); return newData ? newData : previousData; }, data); } /** * Unsubsribe callback from event * * @param eventName * @param callback */ off(eventName, callback) { for (let i = 0; i < this.subscribers[eventName].length; i++) { if (this.subscribers[eventName][i] === callback) { delete this.subscribers[eventName][i]; break; } } } /** * Destroyer * clears subsribers list */ destroy() { this.subscribers = null; } }
[ "class", "Events", "{", "constructor", "(", ")", "{", "this", ".", "subscribers", "=", "{", "}", ";", "}", "on", "(", "eventName", ",", "callback", ")", "{", "if", "(", "!", "(", "eventName", "in", "this", ".", "subscribers", ")", ")", "{", "this", ".", "subscribers", "[", "eventName", "]", "=", "[", "]", ";", "}", "this", ".", "subscribers", "[", "eventName", "]", ".", "push", "(", "callback", ")", ";", "}", "emit", "(", "eventName", ",", "data", ")", "{", "if", "(", "!", "this", ".", "subscribers", "[", "eventName", "]", ")", "{", "return", ";", "}", "this", ".", "subscribers", "[", "eventName", "]", ".", "reduce", "(", "(", "previousData", ",", "currentHandler", ")", "=>", "{", "const", "newData", "=", "currentHandler", "(", "previousData", ")", ";", "return", "newData", "?", "newData", ":", "previousData", ";", "}", ",", "data", ")", ";", "}", "off", "(", "eventName", ",", "callback", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "this", ".", "subscribers", "[", "eventName", "]", ".", "length", ";", "i", "++", ")", "{", "if", "(", "this", ".", "subscribers", "[", "eventName", "]", "[", "i", "]", "===", "callback", ")", "{", "delete", "this", ".", "subscribers", "[", "eventName", "]", "[", "i", "]", ";", "break", ";", "}", "}", "}", "destroy", "(", ")", "{", "this", ".", "subscribers", "=", "null", ";", "}", "}" ]
@module eventDispatcher Has two important methods: - {Function} on - appends subscriber to the event.
[ "@module", "eventDispatcher", "Has", "two", "important", "methods", ":", "-", "{", "Function", "}", "on", "-", "appends", "subscriber", "to", "the", "event", "." ]
[ "/**\n * Object with events` names as key and array of callback functions as value\n * @type {{}}\n */", "/**\n * Subscribe any event on callback\n *\n * @param {String} eventName - event name\n * @param {Function} callback - subscriber\n */", "// group by events", "/**\n * Emit callbacks with passed data\n *\n * @param {String} eventName - event name\n * @param {Object} data - subscribers get this data when they were fired\n */", "/**\n * Unsubsribe callback from event\n *\n * @param eventName\n * @param callback\n */", "/**\n * Destroyer\n * clears subsribers list\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
354
102
66890e4084ebceb706fd404c061038824560f07f
james1236/voluntary.app
src/lib/ideal/ProtoClass.js
[ "MIT" ]
JavaScript
ProtoClass
/* working on moving Proto to ES6 classes problems and potential solutions: P: getting list of classes? S: call registerClass() on each class after defined, use ProtoClass.allClasses() to get list P: inheriting proto ivars? S: Use class variables instead? P: protos as singletons? S: Yse ClassName.shared() instead P: interactively adding, removing, changing protos? S: ? */
working on moving Proto to ES6 classes problems and potential solutions. getting list of classes. S: call registerClass() on each class after defined, use ProtoClass.allClasses() to get list inheriting proto ivars. protos as singletons. interactively adding, removing, changing protos.
[ "working", "on", "moving", "Proto", "to", "ES6", "classes", "problems", "and", "potential", "solutions", ".", "getting", "list", "of", "classes", ".", "S", ":", "call", "registerClass", "()", "on", "each", "class", "after", "defined", "use", "ProtoClass", ".", "allClasses", "()", "to", "get", "list", "inheriting", "proto", "ivars", ".", "protos", "as", "singletons", ".", "interactively", "adding", "removing", "changing", "protos", "." ]
class ProtoClass { // --- class slots and variables --- static getClassVariable(key, defaultValue) { if (!(key in this)) { this[key] = defaultValue } return this[key] } static setClassVariable(key, value) { this[key] = value return this } static shared() { if (!this.getClassVariable("_shared")) { this.setClassVariable("_shared", this.clone()) } return this.getClassVariable("_shared") } static allClasses () { return this.getClassVariable("_allClasses", []) } static registerThisClass () { //console.log("registerThisClass: ", this) if (this.allClasses().indexOf(this) == -1) { this.allClasses().push(this) } return this } static self () { return this } self () { return this } /* static setupSlots () { //super.setupSlotsIfNeeded() console.log(this.type() + ".setupSlots()") } static setupSlotsIfNeeded () { if (!this.getClassVariable("_hasSetupSlots", false)) { console.log("--- begin ---") this.setupSlots() if (this.type() != "ProtoClass") { super.setupSlotsIfNeeded() } console.log("--- end ---") this.setClassVariable("_hasSetupSlots", true) } } */ // adding instance slots via class --- static newSlots(slots) { this.prototype.newSlots(slots) return this; } static setSlots(slots) { this.prototype.setSlots(slots) return this; } // --- instance --- constructor() { } static clone () { //this.setupSlotsIfNeeded() var obj = new this() obj.assignUniqueId() obj.init() return obj } init() { // subclasses should override to initialize } static type() { return this.name } type() { return this.constructor.name } newSlot(slotName, initialValue) { if (typeof (slotName) != "string") { throw new Error("name must be a string"); } if (initialValue === undefined) { initialValue = null; }; var privateName = "_" + slotName; this[privateName] = initialValue; if (!this[slotName]) { this[slotName] = function () { return this[privateName]; } } var setterName = "set" + slotName.capitalized() if (!this[setterName]) { this[setterName] = function (newValue) { //this[privateName] = newValue; this.updateSlot(slotName, privateName, newValue); return this; } } return this; } newSlots(slots) { Object.eachSlot(slots, (slotName, initialValue) => { this.newSlot(slotName, initialValue); }); return this; } updateSlot(slotName, privateName, newValue) { var oldValue = this[privateName]; if (oldValue != newValue) { this[privateName] = newValue; this.didUpdateSlot(slotName, oldValue, newValue) //this.mySlotChanged(name, oldValue, newValue); } return this; } didUpdateSlot(slotName, oldValue, newValue) { // persistence system can hook this } setSlots(slots) { Object.eachSlot(slots, (name, initialValue) => { this.setSlot(name, initialValue); }); return this; } setSlot(name, initialValue) { this[name] = initialValue return this } childProtos () { var result = ProtoClass.allClasses().select((proto) => { return proto._parentProto == this }) return result } /* extend () { var obj = this.cloneWithoutInit() Proto._allProtos.push(obj) obj._parentProto = this //console.log("Proto._allProtos.length = ", Proto._allProtos.length) return obj; } */ uniqueId () { return this._uniqueId } typeId () { return this.type() + this.uniqueId() } hasUniqueId () { return Number.isInteger(this._uniqueId) } assertHasUniqueId () { assert(this.hasUniqueId()) } assignUniqueId () { assert(!this.hasUniqueId()) // error may mean attempt to clone a singleton this._uniqueId = ProtoClass.newUniqueId(); this.assertHasUniqueId() return this } cloneWithoutInit () { var obj = Object.clone(this); obj.__proto__ = this; obj.assignUniqueId(); return obj; } clone () { var obj = this.cloneWithoutInit(); obj.init(); return obj; } withSets (sets) { return this.clone().performSets(sets); } withSlots (slots) { return this.clone().setSlots(slots); } init () { // subclasses should override to do initialization } toString () { return this._type; } setSlotsIfAbsent (slots) { Object.eachSlot(slots, (name, value) => { if (!this[name]) { this.setSlot(name, value); } }); return this; } /* mySlotChanged (slotName, oldValue, newValue) { this.perform(slotName + "SlotChanged", oldValue, newValue); } */ ownsSlot (name) { return this.hasOwnProperty(name); } /* aliasSlot (slotName, aliasName) { this[aliasName] = this[slotName]; this["set" + aliasName.capitalized()] = this["set" + slotName.capitalized()]; return this; } */ argsAsArray (args) { return Array.prototype.slice.call(args); } canPerform (message) { return this[message] && typeof (this[message]) == "function"; } performWithArgList (message, argList) { return this[message].apply(this, argList); } perform (message) { if (this[message] && this[message].apply) { return this[message].apply(this, this.argsAsArray(arguments).slice(1)); } throw new Error(this, ".perform(" + message + ") missing method") return this; } setterNameMap () { return this.getClassVariable("_setterNameMap", {}) } setterNameForSlot (name) { // cache these as there aren't too many and it will avoid extra string operations var setter = this.setterNameMap()[name] if (!setter) { setter = "set" + name.capitalized() this.setterNameMap()[name] = setter } return setter } /* performSet (name, value) { return this.perform("set" + name.capitalized(), value); } performSets (slots) { Object.eachSlot(slots, (name, value) => { this.perform("set" + name.capitalized(), value); }); return this; } performGets (slots) { var object = {}; slots.forEach( (slot) => { object[slot] = this.perform(slot); }); return object; } */ static newUniqueId() { var key = "_uniqueIdCounter" var uid = this.getClassVariable(key, 0) uid ++; this.setClassVariable(key, uid) return uid } uniqueId () { return this._uniqueId } isKindOf (aProto) { // TODO: test this for ES6 classes if (this.__proto__) { if (this.__proto__ === aProto) { return true } if (this.__proto__.isKindOf) { return this.__proto__.isKindOf(aProto) } } return false } toString () { return this.type() + "." + this.uniqueId(); } // --- ancestors --- ancestors () { // TODO: test this for ES6 classes var results = [] var obj = this; while (obj.__proto__ && obj.type) { results.push(obj) if (results.length > 100) { throw new Error("proto loop detected?") } obj = obj.__proto__ } return results } ancestorTypes () { return this.ancestors().map((obj) => { return obj.type() }) } firstAncestorWithMatchingPostfixClass (aPostfix) { // not a great name but this walks back the ancestors and tries to find an // existing class with the same name as the ancestor + the given postfix // useful for things like type + "View" or type + "RowView", etc //console.log(this.type() + " firstAncestorWithMatchingPostfixClass(" + aPostfix + ")") var match = this.ancestors().detect((obj) => { var name = obj.type() + aPostfix var proto = window[name] return proto }) var result = match ? window[match.type() + aPostfix] : null return result } }
[ "class", "ProtoClass", "{", "static", "getClassVariable", "(", "key", ",", "defaultValue", ")", "{", "if", "(", "!", "(", "key", "in", "this", ")", ")", "{", "this", "[", "key", "]", "=", "defaultValue", "}", "return", "this", "[", "key", "]", "}", "static", "setClassVariable", "(", "key", ",", "value", ")", "{", "this", "[", "key", "]", "=", "value", "return", "this", "}", "static", "shared", "(", ")", "{", "if", "(", "!", "this", ".", "getClassVariable", "(", "\"_shared\"", ")", ")", "{", "this", ".", "setClassVariable", "(", "\"_shared\"", ",", "this", ".", "clone", "(", ")", ")", "}", "return", "this", ".", "getClassVariable", "(", "\"_shared\"", ")", "}", "static", "allClasses", "(", ")", "{", "return", "this", ".", "getClassVariable", "(", "\"_allClasses\"", ",", "[", "]", ")", "}", "static", "registerThisClass", "(", ")", "{", "if", "(", "this", ".", "allClasses", "(", ")", ".", "indexOf", "(", "this", ")", "==", "-", "1", ")", "{", "this", ".", "allClasses", "(", ")", ".", "push", "(", "this", ")", "}", "return", "this", "}", "static", "self", "(", ")", "{", "return", "this", "}", "self", "(", ")", "{", "return", "this", "}", "static", "newSlots", "(", "slots", ")", "{", "this", ".", "prototype", ".", "newSlots", "(", "slots", ")", "return", "this", ";", "}", "static", "setSlots", "(", "slots", ")", "{", "this", ".", "prototype", ".", "setSlots", "(", "slots", ")", "return", "this", ";", "}", "constructor", "(", ")", "{", "}", "static", "clone", "(", ")", "{", "var", "obj", "=", "new", "this", "(", ")", "obj", ".", "assignUniqueId", "(", ")", "obj", ".", "init", "(", ")", "return", "obj", "}", "init", "(", ")", "{", "}", "static", "type", "(", ")", "{", "return", "this", ".", "name", "}", "type", "(", ")", "{", "return", "this", ".", "constructor", ".", "name", "}", "newSlot", "(", "slotName", ",", "initialValue", ")", "{", "if", "(", "typeof", "(", "slotName", ")", "!=", "\"string\"", ")", "{", "throw", "new", "Error", "(", "\"name must be a string\"", ")", ";", "}", "if", "(", "initialValue", "===", "undefined", ")", "{", "initialValue", "=", "null", ";", "}", ";", "var", "privateName", "=", "\"_\"", "+", "slotName", ";", "this", "[", "privateName", "]", "=", "initialValue", ";", "if", "(", "!", "this", "[", "slotName", "]", ")", "{", "this", "[", "slotName", "]", "=", "function", "(", ")", "{", "return", "this", "[", "privateName", "]", ";", "}", "}", "var", "setterName", "=", "\"set\"", "+", "slotName", ".", "capitalized", "(", ")", "if", "(", "!", "this", "[", "setterName", "]", ")", "{", "this", "[", "setterName", "]", "=", "function", "(", "newValue", ")", "{", "this", ".", "updateSlot", "(", "slotName", ",", "privateName", ",", "newValue", ")", ";", "return", "this", ";", "}", "}", "return", "this", ";", "}", "newSlots", "(", "slots", ")", "{", "Object", ".", "eachSlot", "(", "slots", ",", "(", "slotName", ",", "initialValue", ")", "=>", "{", "this", ".", "newSlot", "(", "slotName", ",", "initialValue", ")", ";", "}", ")", ";", "return", "this", ";", "}", "updateSlot", "(", "slotName", ",", "privateName", ",", "newValue", ")", "{", "var", "oldValue", "=", "this", "[", "privateName", "]", ";", "if", "(", "oldValue", "!=", "newValue", ")", "{", "this", "[", "privateName", "]", "=", "newValue", ";", "this", ".", "didUpdateSlot", "(", "slotName", ",", "oldValue", ",", "newValue", ")", "}", "return", "this", ";", "}", "didUpdateSlot", "(", "slotName", ",", "oldValue", ",", "newValue", ")", "{", "}", "setSlots", "(", "slots", ")", "{", "Object", ".", "eachSlot", "(", "slots", ",", "(", "name", ",", "initialValue", ")", "=>", "{", "this", ".", "setSlot", "(", "name", ",", "initialValue", ")", ";", "}", ")", ";", "return", "this", ";", "}", "setSlot", "(", "name", ",", "initialValue", ")", "{", "this", "[", "name", "]", "=", "initialValue", "return", "this", "}", "childProtos", "(", ")", "{", "var", "result", "=", "ProtoClass", ".", "allClasses", "(", ")", ".", "select", "(", "(", "proto", ")", "=>", "{", "return", "proto", ".", "_parentProto", "==", "this", "}", ")", "return", "result", "}", "uniqueId", "(", ")", "{", "return", "this", ".", "_uniqueId", "}", "typeId", "(", ")", "{", "return", "this", ".", "type", "(", ")", "+", "this", ".", "uniqueId", "(", ")", "}", "hasUniqueId", "(", ")", "{", "return", "Number", ".", "isInteger", "(", "this", ".", "_uniqueId", ")", "}", "assertHasUniqueId", "(", ")", "{", "assert", "(", "this", ".", "hasUniqueId", "(", ")", ")", "}", "assignUniqueId", "(", ")", "{", "assert", "(", "!", "this", ".", "hasUniqueId", "(", ")", ")", "this", ".", "_uniqueId", "=", "ProtoClass", ".", "newUniqueId", "(", ")", ";", "this", ".", "assertHasUniqueId", "(", ")", "return", "this", "}", "cloneWithoutInit", "(", ")", "{", "var", "obj", "=", "Object", ".", "clone", "(", "this", ")", ";", "obj", ".", "__proto__", "=", "this", ";", "obj", ".", "assignUniqueId", "(", ")", ";", "return", "obj", ";", "}", "clone", "(", ")", "{", "var", "obj", "=", "this", ".", "cloneWithoutInit", "(", ")", ";", "obj", ".", "init", "(", ")", ";", "return", "obj", ";", "}", "withSets", "(", "sets", ")", "{", "return", "this", ".", "clone", "(", ")", ".", "performSets", "(", "sets", ")", ";", "}", "withSlots", "(", "slots", ")", "{", "return", "this", ".", "clone", "(", ")", ".", "setSlots", "(", "slots", ")", ";", "}", "init", "(", ")", "{", "}", "toString", "(", ")", "{", "return", "this", ".", "_type", ";", "}", "setSlotsIfAbsent", "(", "slots", ")", "{", "Object", ".", "eachSlot", "(", "slots", ",", "(", "name", ",", "value", ")", "=>", "{", "if", "(", "!", "this", "[", "name", "]", ")", "{", "this", ".", "setSlot", "(", "name", ",", "value", ")", ";", "}", "}", ")", ";", "return", "this", ";", "}", "ownsSlot", "(", "name", ")", "{", "return", "this", ".", "hasOwnProperty", "(", "name", ")", ";", "}", "argsAsArray", "(", "args", ")", "{", "return", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "args", ")", ";", "}", "canPerform", "(", "message", ")", "{", "return", "this", "[", "message", "]", "&&", "typeof", "(", "this", "[", "message", "]", ")", "==", "\"function\"", ";", "}", "performWithArgList", "(", "message", ",", "argList", ")", "{", "return", "this", "[", "message", "]", ".", "apply", "(", "this", ",", "argList", ")", ";", "}", "perform", "(", "message", ")", "{", "if", "(", "this", "[", "message", "]", "&&", "this", "[", "message", "]", ".", "apply", ")", "{", "return", "this", "[", "message", "]", ".", "apply", "(", "this", ",", "this", ".", "argsAsArray", "(", "arguments", ")", ".", "slice", "(", "1", ")", ")", ";", "}", "throw", "new", "Error", "(", "this", ",", "\".perform(\"", "+", "message", "+", "\") missing method\"", ")", "return", "this", ";", "}", "setterNameMap", "(", ")", "{", "return", "this", ".", "getClassVariable", "(", "\"_setterNameMap\"", ",", "{", "}", ")", "}", "setterNameForSlot", "(", "name", ")", "{", "var", "setter", "=", "this", ".", "setterNameMap", "(", ")", "[", "name", "]", "if", "(", "!", "setter", ")", "{", "setter", "=", "\"set\"", "+", "name", ".", "capitalized", "(", ")", "this", ".", "setterNameMap", "(", ")", "[", "name", "]", "=", "setter", "}", "return", "setter", "}", "static", "newUniqueId", "(", ")", "{", "var", "key", "=", "\"_uniqueIdCounter\"", "var", "uid", "=", "this", ".", "getClassVariable", "(", "key", ",", "0", ")", "uid", "++", ";", "this", ".", "setClassVariable", "(", "key", ",", "uid", ")", "return", "uid", "}", "uniqueId", "(", ")", "{", "return", "this", ".", "_uniqueId", "}", "isKindOf", "(", "aProto", ")", "{", "if", "(", "this", ".", "__proto__", ")", "{", "if", "(", "this", ".", "__proto__", "===", "aProto", ")", "{", "return", "true", "}", "if", "(", "this", ".", "__proto__", ".", "isKindOf", ")", "{", "return", "this", ".", "__proto__", ".", "isKindOf", "(", "aProto", ")", "}", "}", "return", "false", "}", "toString", "(", ")", "{", "return", "this", ".", "type", "(", ")", "+", "\".\"", "+", "this", ".", "uniqueId", "(", ")", ";", "}", "ancestors", "(", ")", "{", "var", "results", "=", "[", "]", "var", "obj", "=", "this", ";", "while", "(", "obj", ".", "__proto__", "&&", "obj", ".", "type", ")", "{", "results", ".", "push", "(", "obj", ")", "if", "(", "results", ".", "length", ">", "100", ")", "{", "throw", "new", "Error", "(", "\"proto loop detected?\"", ")", "}", "obj", "=", "obj", ".", "__proto__", "}", "return", "results", "}", "ancestorTypes", "(", ")", "{", "return", "this", ".", "ancestors", "(", ")", ".", "map", "(", "(", "obj", ")", "=>", "{", "return", "obj", ".", "type", "(", ")", "}", ")", "}", "firstAncestorWithMatchingPostfixClass", "(", "aPostfix", ")", "{", "var", "match", "=", "this", ".", "ancestors", "(", ")", ".", "detect", "(", "(", "obj", ")", "=>", "{", "var", "name", "=", "obj", ".", "type", "(", ")", "+", "aPostfix", "var", "proto", "=", "window", "[", "name", "]", "return", "proto", "}", ")", "var", "result", "=", "match", "?", "window", "[", "match", ".", "type", "(", ")", "+", "aPostfix", "]", ":", "null", "return", "result", "}", "}" ]
working on moving Proto to ES6 classes problems and potential solutions:
[ "working", "on", "moving", "Proto", "to", "ES6", "classes", "problems", "and", "potential", "solutions", ":" ]
[ "// --- class slots and variables ---", "//console.log(\"registerThisClass: \", this)", "/*\n static setupSlots () {\n //super.setupSlotsIfNeeded()\n console.log(this.type() + \".setupSlots()\")\n }\n\n static setupSlotsIfNeeded () {\n if (!this.getClassVariable(\"_hasSetupSlots\", false)) {\n console.log(\"--- begin ---\")\n this.setupSlots()\n if (this.type() != \"ProtoClass\") {\n super.setupSlotsIfNeeded()\n }\n console.log(\"--- end ---\")\n this.setClassVariable(\"_hasSetupSlots\", true)\n }\n }\n */", "// adding instance slots via class ---", "// --- instance ---", "//this.setupSlotsIfNeeded()", "// subclasses should override to initialize", "//this[privateName] = newValue;", "//this.mySlotChanged(name, oldValue, newValue);", "// persistence system can hook this", "/*\n\n extend () {\n var obj = this.cloneWithoutInit()\n Proto._allProtos.push(obj)\n obj._parentProto = this\n //console.log(\"Proto._allProtos.length = \", Proto._allProtos.length)\n return obj;\n }\n */", "// error may mean attempt to clone a singleton", "// subclasses should override to do initialization", "/*\n\n mySlotChanged (slotName, oldValue, newValue) {\n this.perform(slotName + \"SlotChanged\", oldValue, newValue);\n }\n */", "/*\n aliasSlot (slotName, aliasName) {\n this[aliasName] = this[slotName];\n this[\"set\" + aliasName.capitalized()] = this[\"set\" + slotName.capitalized()];\n return this;\n }\n */", "// cache these as there aren't too many and it will avoid extra string operations", "/*\n performSet (name, value) {\n return this.perform(\"set\" + name.capitalized(), value);\n }\n\n performSets (slots) {\n Object.eachSlot(slots, (name, value) => {\n this.perform(\"set\" + name.capitalized(), value);\n });\n\n return this;\n }\n\n performGets (slots) {\n var object = {};\n slots.forEach( (slot) => {\n object[slot] = this.perform(slot);\n });\n\n return object;\n }\n */", "// TODO: test this for ES6 classes", "// --- ancestors ---", "// TODO: test this for ES6 classes", "// not a great name but this walks back the ancestors and tries to find an", "// existing class with the same name as the ancestor + the given postfix", "// useful for things like type + \"View\" or type + \"RowView\", etc", "//console.log(this.type() + \" firstAncestorWithMatchingPostfixClass(\" + aPostfix + \")\")" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
2,052
102
3b087626b9680a3e309ebfdaabe84de2f3200b6b
Mysize/wordpress-heroku
web/wp/wp-includes/js/dist/widgets.js
[ "MIT" ]
JavaScript
control_Control
/** * An API for creating and loading a widget control (a <div class="widget"> * element) that is compatible with most third party widget scripts. By not * using React for this, we ensure that we have complete contorl over the DOM * and do not accidentally remove any elements that a third party widget script * has attached an event listener to. * * @property {Element} element The control's DOM element. */
An API for creating and loading a widget control (a element) that is compatible with most third party widget scripts. By not using React for this, we ensure that we have complete contorl over the DOM and do not accidentally remove any elements that a third party widget script has attached an event listener to. @property {Element} element The control's DOM element.
[ "An", "API", "for", "creating", "and", "loading", "a", "widget", "control", "(", "a", "element", ")", "that", "is", "compatible", "with", "most", "third", "party", "widget", "scripts", ".", "By", "not", "using", "React", "for", "this", "we", "ensure", "that", "we", "have", "complete", "contorl", "over", "the", "DOM", "and", "do", "not", "accidentally", "remove", "any", "elements", "that", "a", "third", "party", "widget", "script", "has", "attached", "an", "event", "listener", "to", ".", "@property", "{", "Element", "}", "element", "The", "control", "'", "s", "DOM", "element", "." ]
class control_Control { /** * Creates and loads a new control. * * @access public * @param {Object} params * @param {string} params.id * @param {string} params.idBase * @param {Object} params.instance * @param {Function} params.onChangeInstance * @param {Function} params.onChangeHasPreview * @param {Function} params.onError */ constructor({ id, idBase, instance, onChangeInstance, onChangeHasPreview, onError }) { this.id = id; this.idBase = idBase; this._instance = instance; this._hasPreview = null; this.onChangeInstance = onChangeInstance; this.onChangeHasPreview = onChangeHasPreview; this.onError = onError; // We can't use the real widget number as this is calculated by the // server and we may not ever *actually* save this widget. Instead, use // a fake but unique number. this.number = ++lastNumber; this.handleFormChange = Object(external_lodash_["debounce"])(this.handleFormChange.bind(this), 200); this.handleFormSubmit = this.handleFormSubmit.bind(this); this.initDOM(); this.bindEvents(); this.loadContent(); } /** * Clean up the control so that it can be garabge collected. * * @access public */ destroy() { this.unbindEvents(); this.element.remove(); // TODO: How do we make third party widget scripts remove their event // listeners? } /** * Creates the control's DOM structure. * * @access private */ initDOM() { var _this$id, _this$idBase; this.element = el('div', { class: 'widget open' }, [el('div', { class: 'widget-inside' }, [this.form = el('form', { class: 'form', method: 'post' }, [// These hidden form inputs are what most widgets' scripts // use to access data about the widget. el('input', { class: 'widget-id', type: 'hidden', name: 'widget-id', value: (_this$id = this.id) !== null && _this$id !== void 0 ? _this$id : `${this.idBase}-${this.number}` }), el('input', { class: 'id_base', type: 'hidden', name: 'id_base', value: (_this$idBase = this.idBase) !== null && _this$idBase !== void 0 ? _this$idBase : this.id }), el('input', { class: 'widget-width', type: 'hidden', name: 'widget-width', value: '250' }), el('input', { class: 'widget-height', type: 'hidden', name: 'widget-height', value: '200' }), el('input', { class: 'widget_number', type: 'hidden', name: 'widget_number', value: this.idBase ? this.number.toString() : '' }), this.content = el('div', { class: 'widget-content' }), // Non-multi widgets can be saved via a Save button. this.id && el('button', { class: 'button is-primary', type: 'submit' }, Object(external_wp_i18n_["__"])('Save'))])])]); } /** * Adds the control's event listeners. * * @access private */ bindEvents() { // Prefer jQuery 'change' event instead of the native 'change' event // because many widgets use jQuery's event bus to trigger an update. if (window.jQuery) { const { jQuery: $ } = window; $(this.form).on('change', null, this.handleFormChange); $(this.form).on('input', null, this.handleFormChange); $(this.form).on('submit', this.handleFormSubmit); } else { this.form.addEventListener('change', this.handleFormChange); this.form.addEventListener('input', this.handleFormChange); this.form.addEventListener('submit', this.handleFormSubmit); } } /** * Removes the control's event listeners. * * @access private */ unbindEvents() { if (window.jQuery) { const { jQuery: $ } = window; $(this.form).off('change', null, this.handleFormChange); $(this.form).off('input', null, this.handleFormChange); $(this.form).off('submit', this.handleFormSubmit); } else { this.form.removeEventListener('change', this.handleFormChange); this.form.removeEventListener('input', this.handleFormChange); this.form.removeEventListener('submit', this.handleFormSubmit); } } /** * Fetches the widget's form HTML from the REST API and loads it into the * control's form. * * @access private */ async loadContent() { try { if (this.id) { const { form } = await saveWidget(this.id); this.content.innerHTML = form; } else if (this.idBase) { const { form, preview } = await encodeWidget({ idBase: this.idBase, instance: this.instance, number: this.number }); this.content.innerHTML = form; this.hasPreview = !isEmptyHTML(preview); // If we don't have an instance, perform a save right away. This // happens when creating a new Legacy Widget block. if (!this.instance.hash) { const { instance } = await encodeWidget({ idBase: this.idBase, instance: this.instance, number: this.number, formData: serializeForm(this.form) }); this.instance = instance; } } // Trigger 'widget-added' when widget is ready. This event is what // widgets' scripts use to initialize, attach events, etc. The event // must be fired using jQuery's event bus as this is what widget // scripts expect. If jQuery is not loaded, do nothing - some // widgets will still work regardless. if (window.jQuery) { const { jQuery: $ } = window; $(document).trigger('widget-added', [$(this.element)]); } } catch (error) { this.onError(error); } } /** * Perform a save when a multi widget's form is changed. Non-multi widgets * are saved manually. * * @access private */ handleFormChange() { if (this.idBase) { this.saveForm(); } } /** * Perform a save when the control's form is manually submitted. * * @access private * @param {Event} event */ handleFormSubmit(event) { event.preventDefault(); this.saveForm(); } /** * Serialize the control's form, send it to the REST API, and update the * instance with the encoded instance that the REST API returns. * * @access private */ async saveForm() { const formData = serializeForm(this.form); try { if (this.id) { const { form } = await saveWidget(this.id, formData); this.content.innerHTML = form; if (window.jQuery) { const { jQuery: $ } = window; $(document).trigger('widget-updated', [$(this.element)]); } } else if (this.idBase) { const { instance, preview } = await encodeWidget({ idBase: this.idBase, instance: this.instance, number: this.number, formData }); this.instance = instance; this.hasPreview = !isEmptyHTML(preview); } } catch (error) { this.onError(error); } } /** * The widget's instance object. * * @access private */ get instance() { return this._instance; } /** * The widget's instance object. * * @access private */ set instance(instance) { if (this._instance !== instance) { this._instance = instance; this.onChangeInstance(instance); } } /** * Whether or not the widget can be previewed. * * @access public */ get hasPreview() { return this._hasPreview; } /** * Whether or not the widget can be previewed. * * @access private */ set hasPreview(hasPreview) { if (this._hasPreview !== hasPreview) { this._hasPreview = hasPreview; this.onChangeHasPreview(hasPreview); } } }
[ "class", "control_Control", "{", "constructor", "(", "{", "id", ",", "idBase", ",", "instance", ",", "onChangeInstance", ",", "onChangeHasPreview", ",", "onError", "}", ")", "{", "this", ".", "id", "=", "id", ";", "this", ".", "idBase", "=", "idBase", ";", "this", ".", "_instance", "=", "instance", ";", "this", ".", "_hasPreview", "=", "null", ";", "this", ".", "onChangeInstance", "=", "onChangeInstance", ";", "this", ".", "onChangeHasPreview", "=", "onChangeHasPreview", ";", "this", ".", "onError", "=", "onError", ";", "this", ".", "number", "=", "++", "lastNumber", ";", "this", ".", "handleFormChange", "=", "Object", "(", "external_lodash_", "[", "\"debounce\"", "]", ")", "(", "this", ".", "handleFormChange", ".", "bind", "(", "this", ")", ",", "200", ")", ";", "this", ".", "handleFormSubmit", "=", "this", ".", "handleFormSubmit", ".", "bind", "(", "this", ")", ";", "this", ".", "initDOM", "(", ")", ";", "this", ".", "bindEvents", "(", ")", ";", "this", ".", "loadContent", "(", ")", ";", "}", "destroy", "(", ")", "{", "this", ".", "unbindEvents", "(", ")", ";", "this", ".", "element", ".", "remove", "(", ")", ";", "}", "initDOM", "(", ")", "{", "var", "_this$id", ",", "_this$idBase", ";", "this", ".", "element", "=", "el", "(", "'div'", ",", "{", "class", ":", "'widget open'", "}", ",", "[", "el", "(", "'div'", ",", "{", "class", ":", "'widget-inside'", "}", ",", "[", "this", ".", "form", "=", "el", "(", "'form'", ",", "{", "class", ":", "'form'", ",", "method", ":", "'post'", "}", ",", "[", "el", "(", "'input'", ",", "{", "class", ":", "'widget-id'", ",", "type", ":", "'hidden'", ",", "name", ":", "'widget-id'", ",", "value", ":", "(", "_this$id", "=", "this", ".", "id", ")", "!==", "null", "&&", "_this$id", "!==", "void", "0", "?", "_this$id", ":", "`", "${", "this", ".", "idBase", "}", "${", "this", ".", "number", "}", "`", "}", ")", ",", "el", "(", "'input'", ",", "{", "class", ":", "'id_base'", ",", "type", ":", "'hidden'", ",", "name", ":", "'id_base'", ",", "value", ":", "(", "_this$idBase", "=", "this", ".", "idBase", ")", "!==", "null", "&&", "_this$idBase", "!==", "void", "0", "?", "_this$idBase", ":", "this", ".", "id", "}", ")", ",", "el", "(", "'input'", ",", "{", "class", ":", "'widget-width'", ",", "type", ":", "'hidden'", ",", "name", ":", "'widget-width'", ",", "value", ":", "'250'", "}", ")", ",", "el", "(", "'input'", ",", "{", "class", ":", "'widget-height'", ",", "type", ":", "'hidden'", ",", "name", ":", "'widget-height'", ",", "value", ":", "'200'", "}", ")", ",", "el", "(", "'input'", ",", "{", "class", ":", "'widget_number'", ",", "type", ":", "'hidden'", ",", "name", ":", "'widget_number'", ",", "value", ":", "this", ".", "idBase", "?", "this", ".", "number", ".", "toString", "(", ")", ":", "''", "}", ")", ",", "this", ".", "content", "=", "el", "(", "'div'", ",", "{", "class", ":", "'widget-content'", "}", ")", ",", "this", ".", "id", "&&", "el", "(", "'button'", ",", "{", "class", ":", "'button is-primary'", ",", "type", ":", "'submit'", "}", ",", "Object", "(", "external_wp_i18n_", "[", "\"__\"", "]", ")", "(", "'Save'", ")", ")", "]", ")", "]", ")", "]", ")", ";", "}", "bindEvents", "(", ")", "{", "if", "(", "window", ".", "jQuery", ")", "{", "const", "{", "jQuery", ":", "$", "}", "=", "window", ";", "$", "(", "this", ".", "form", ")", ".", "on", "(", "'change'", ",", "null", ",", "this", ".", "handleFormChange", ")", ";", "$", "(", "this", ".", "form", ")", ".", "on", "(", "'input'", ",", "null", ",", "this", ".", "handleFormChange", ")", ";", "$", "(", "this", ".", "form", ")", ".", "on", "(", "'submit'", ",", "this", ".", "handleFormSubmit", ")", ";", "}", "else", "{", "this", ".", "form", ".", "addEventListener", "(", "'change'", ",", "this", ".", "handleFormChange", ")", ";", "this", ".", "form", ".", "addEventListener", "(", "'input'", ",", "this", ".", "handleFormChange", ")", ";", "this", ".", "form", ".", "addEventListener", "(", "'submit'", ",", "this", ".", "handleFormSubmit", ")", ";", "}", "}", "unbindEvents", "(", ")", "{", "if", "(", "window", ".", "jQuery", ")", "{", "const", "{", "jQuery", ":", "$", "}", "=", "window", ";", "$", "(", "this", ".", "form", ")", ".", "off", "(", "'change'", ",", "null", ",", "this", ".", "handleFormChange", ")", ";", "$", "(", "this", ".", "form", ")", ".", "off", "(", "'input'", ",", "null", ",", "this", ".", "handleFormChange", ")", ";", "$", "(", "this", ".", "form", ")", ".", "off", "(", "'submit'", ",", "this", ".", "handleFormSubmit", ")", ";", "}", "else", "{", "this", ".", "form", ".", "removeEventListener", "(", "'change'", ",", "this", ".", "handleFormChange", ")", ";", "this", ".", "form", ".", "removeEventListener", "(", "'input'", ",", "this", ".", "handleFormChange", ")", ";", "this", ".", "form", ".", "removeEventListener", "(", "'submit'", ",", "this", ".", "handleFormSubmit", ")", ";", "}", "}", "async", "loadContent", "(", ")", "{", "try", "{", "if", "(", "this", ".", "id", ")", "{", "const", "{", "form", "}", "=", "await", "saveWidget", "(", "this", ".", "id", ")", ";", "this", ".", "content", ".", "innerHTML", "=", "form", ";", "}", "else", "if", "(", "this", ".", "idBase", ")", "{", "const", "{", "form", ",", "preview", "}", "=", "await", "encodeWidget", "(", "{", "idBase", ":", "this", ".", "idBase", ",", "instance", ":", "this", ".", "instance", ",", "number", ":", "this", ".", "number", "}", ")", ";", "this", ".", "content", ".", "innerHTML", "=", "form", ";", "this", ".", "hasPreview", "=", "!", "isEmptyHTML", "(", "preview", ")", ";", "if", "(", "!", "this", ".", "instance", ".", "hash", ")", "{", "const", "{", "instance", "}", "=", "await", "encodeWidget", "(", "{", "idBase", ":", "this", ".", "idBase", ",", "instance", ":", "this", ".", "instance", ",", "number", ":", "this", ".", "number", ",", "formData", ":", "serializeForm", "(", "this", ".", "form", ")", "}", ")", ";", "this", ".", "instance", "=", "instance", ";", "}", "}", "if", "(", "window", ".", "jQuery", ")", "{", "const", "{", "jQuery", ":", "$", "}", "=", "window", ";", "$", "(", "document", ")", ".", "trigger", "(", "'widget-added'", ",", "[", "$", "(", "this", ".", "element", ")", "]", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "this", ".", "onError", "(", "error", ")", ";", "}", "}", "handleFormChange", "(", ")", "{", "if", "(", "this", ".", "idBase", ")", "{", "this", ".", "saveForm", "(", ")", ";", "}", "}", "handleFormSubmit", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "this", ".", "saveForm", "(", ")", ";", "}", "async", "saveForm", "(", ")", "{", "const", "formData", "=", "serializeForm", "(", "this", ".", "form", ")", ";", "try", "{", "if", "(", "this", ".", "id", ")", "{", "const", "{", "form", "}", "=", "await", "saveWidget", "(", "this", ".", "id", ",", "formData", ")", ";", "this", ".", "content", ".", "innerHTML", "=", "form", ";", "if", "(", "window", ".", "jQuery", ")", "{", "const", "{", "jQuery", ":", "$", "}", "=", "window", ";", "$", "(", "document", ")", ".", "trigger", "(", "'widget-updated'", ",", "[", "$", "(", "this", ".", "element", ")", "]", ")", ";", "}", "}", "else", "if", "(", "this", ".", "idBase", ")", "{", "const", "{", "instance", ",", "preview", "}", "=", "await", "encodeWidget", "(", "{", "idBase", ":", "this", ".", "idBase", ",", "instance", ":", "this", ".", "instance", ",", "number", ":", "this", ".", "number", ",", "formData", "}", ")", ";", "this", ".", "instance", "=", "instance", ";", "this", ".", "hasPreview", "=", "!", "isEmptyHTML", "(", "preview", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "this", ".", "onError", "(", "error", ")", ";", "}", "}", "get", "instance", "(", ")", "{", "return", "this", ".", "_instance", ";", "}", "set", "instance", "(", "instance", ")", "{", "if", "(", "this", ".", "_instance", "!==", "instance", ")", "{", "this", ".", "_instance", "=", "instance", ";", "this", ".", "onChangeInstance", "(", "instance", ")", ";", "}", "}", "get", "hasPreview", "(", ")", "{", "return", "this", ".", "_hasPreview", ";", "}", "set", "hasPreview", "(", "hasPreview", ")", "{", "if", "(", "this", ".", "_hasPreview", "!==", "hasPreview", ")", "{", "this", ".", "_hasPreview", "=", "hasPreview", ";", "this", ".", "onChangeHasPreview", "(", "hasPreview", ")", ";", "}", "}", "}" ]
An API for creating and loading a widget control (a <div class="widget"> element) that is compatible with most third party widget scripts.
[ "An", "API", "for", "creating", "and", "loading", "a", "widget", "control", "(", "a", "<div", "class", "=", "\"", "widget", "\"", ">", "element", ")", "that", "is", "compatible", "with", "most", "third", "party", "widget", "scripts", "." ]
[ "/**\n * Creates and loads a new control.\n *\n * @access public\n * @param {Object} params\n * @param {string} params.id\n * @param {string} params.idBase\n * @param {Object} params.instance\n * @param {Function} params.onChangeInstance\n * @param {Function} params.onChangeHasPreview\n * @param {Function} params.onError\n */", "// We can't use the real widget number as this is calculated by the", "// server and we may not ever *actually* save this widget. Instead, use", "// a fake but unique number.", "/**\n * Clean up the control so that it can be garabge collected.\n *\n * @access public\n */", "// TODO: How do we make third party widget scripts remove their event", "// listeners?", "/**\n * Creates the control's DOM structure.\n *\n * @access private\n */", "// These hidden form inputs are what most widgets' scripts", "// use to access data about the widget.", "// Non-multi widgets can be saved via a Save button.", "/**\n * Adds the control's event listeners.\n *\n * @access private\n */", "// Prefer jQuery 'change' event instead of the native 'change' event", "// because many widgets use jQuery's event bus to trigger an update.", "/**\n * Removes the control's event listeners.\n *\n * @access private\n */", "/**\n * Fetches the widget's form HTML from the REST API and loads it into the\n * control's form.\n *\n * @access private\n */", "// If we don't have an instance, perform a save right away. This", "// happens when creating a new Legacy Widget block.", "// Trigger 'widget-added' when widget is ready. This event is what", "// widgets' scripts use to initialize, attach events, etc. The event", "// must be fired using jQuery's event bus as this is what widget", "// scripts expect. If jQuery is not loaded, do nothing - some", "// widgets will still work regardless.", "/**\n * Perform a save when a multi widget's form is changed. Non-multi widgets\n * are saved manually.\n *\n * @access private\n */", "/**\n * Perform a save when the control's form is manually submitted.\n *\n * @access private\n * @param {Event} event\n */", "/**\n * Serialize the control's form, send it to the REST API, and update the\n * instance with the encoded instance that the REST API returns.\n *\n * @access private\n */", "/**\n * The widget's instance object.\n *\n * @access private\n */", "/**\n * The widget's instance object.\n *\n * @access private\n */", "/**\n * Whether or not the widget can be previewed.\n *\n * @access public\n */", "/**\n * Whether or not the widget can be previewed.\n *\n * @access private\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
27
1,952
92
b06c2c7cb7ee6a709680d4e29671787c5c1309da
pashcovich/Mathematical-Mesh
Confirm/Goedel.Confirm/SchemaConfirm.cs
[ "MIT" ]
C#
AccountEntry
/// <summary> /// /// Represents the collection of data associated with an account. This structure /// is not used in the protocol itself and does not appear in the on-the-wire /// format. It is included here so that it can be used as a reference point for /// describing the semantics of the protocol transaction. It is possible that this /// record format may prove of use in specifying archive and interchange protocols. /// </summary>
Represents the collection of data associated with an account. This structure is not used in the protocol itself and does not appear in the on-the-wire format. It is included here so that it can be used as a reference point for describing the semantics of the protocol transaction. It is possible that this record format may prove of use in specifying archive and interchange protocols.
[ "Represents", "the", "collection", "of", "data", "associated", "with", "an", "account", ".", "This", "structure", "is", "not", "used", "in", "the", "protocol", "itself", "and", "does", "not", "appear", "in", "the", "on", "-", "the", "-", "wire", "format", ".", "It", "is", "included", "here", "so", "that", "it", "can", "be", "used", "as", "a", "reference", "point", "for", "describing", "the", "semantics", "of", "the", "protocol", "transaction", ".", "It", "is", "possible", "that", "this", "record", "format", "may", "prove", "of", "use", "in", "specifying", "archive", "and", "interchange", "protocols", "." ]
public partial class AccountEntry : ConfirmProtocol { public virtual string ResponderAccount {get; set;} public virtual List<string> RequestIDs {get; set;} public virtual List<string> ResponseIDs {get; set;} public virtual List<string> ArchivedIDs {get; set;} public override string _Tag { get; } = "AccountEntry"; public static new JSONObject _Factory () { return new AccountEntry(); } public override void Serialize (Writer Writer, bool wrap, ref bool first) { SerializeX (Writer, wrap, ref first); } public new void SerializeX (Writer _Writer, bool _wrap, ref bool _first) { if (_wrap) { _Writer.WriteObjectStart (); } if (ResponderAccount != null) { _Writer.WriteObjectSeparator (ref _first); _Writer.WriteToken ("ResponderAccount", 1); _Writer.WriteString (ResponderAccount); } if (RequestIDs != null) { _Writer.WriteObjectSeparator (ref _first); _Writer.WriteToken ("RequestIDs", 1); _Writer.WriteArrayStart (); bool _firstarray = true; foreach (var _index in RequestIDs) { _Writer.WriteArraySeparator (ref _firstarray); _Writer.WriteString (_index); } _Writer.WriteArrayEnd (); } if (ResponseIDs != null) { _Writer.WriteObjectSeparator (ref _first); _Writer.WriteToken ("ResponseIDs", 1); _Writer.WriteArrayStart (); bool _firstarray = true; foreach (var _index in ResponseIDs) { _Writer.WriteArraySeparator (ref _firstarray); _Writer.WriteString (_index); } _Writer.WriteArrayEnd (); } if (ArchivedIDs != null) { _Writer.WriteObjectSeparator (ref _first); _Writer.WriteToken ("ArchivedIDs", 1); _Writer.WriteArrayStart (); bool _firstarray = true; foreach (var _index in ArchivedIDs) { _Writer.WriteArraySeparator (ref _firstarray); _Writer.WriteString (_index); } _Writer.WriteArrayEnd (); } if (_wrap) { _Writer.WriteObjectEnd (); } } public static new AccountEntry FromJSON (JSONReader JSONReader, bool Tagged=true) { if (JSONReader == null) { return null; } if (Tagged) { var Out = JSONReader.ReadTaggedObject (_TagDictionary); return Out as AccountEntry; } var Result = new AccountEntry (); Result.Deserialize (JSONReader); return Result; } public override void DeserializeToken (JSONReader JSONReader, string Tag) { switch (Tag) { case "ResponderAccount" : { ResponderAccount = JSONReader.ReadString (); break; } case "RequestIDs" : { bool _Going = JSONReader.StartArray (); RequestIDs = new List <string> (); while (_Going) { string _Item = JSONReader.ReadString (); RequestIDs.Add (_Item); _Going = JSONReader.NextArray (); } break; } case "ResponseIDs" : { bool _Going = JSONReader.StartArray (); ResponseIDs = new List <string> (); while (_Going) { string _Item = JSONReader.ReadString (); ResponseIDs.Add (_Item); _Going = JSONReader.NextArray (); } break; } case "ArchivedIDs" : { bool _Going = JSONReader.StartArray (); ArchivedIDs = new List <string> (); while (_Going) { string _Item = JSONReader.ReadString (); ArchivedIDs.Add (_Item); _Going = JSONReader.NextArray (); } break; } default : { break; } } } }
[ "public", "partial", "class", "AccountEntry", ":", "ConfirmProtocol", "{", "public", "virtual", "string", "ResponderAccount", "{", "get", ";", "set", ";", "}", "public", "virtual", "List", "<", "string", ">", "RequestIDs", "{", "get", ";", "set", ";", "}", "public", "virtual", "List", "<", "string", ">", "ResponseIDs", "{", "get", ";", "set", ";", "}", "public", "virtual", "List", "<", "string", ">", "ArchivedIDs", "{", "get", ";", "set", ";", "}", "public", "override", "string", "_Tag", "{", "get", ";", "}", "=", "\"", "AccountEntry", "\"", ";", "public", "static", "new", "JSONObject", "_Factory", "(", ")", "{", "return", "new", "AccountEntry", "(", ")", ";", "}", "public", "override", "void", "Serialize", "(", "Writer", "Writer", ",", "bool", "wrap", ",", "ref", "bool", "first", ")", "{", "SerializeX", "(", "Writer", ",", "wrap", ",", "ref", "first", ")", ";", "}", "public", "new", "void", "SerializeX", "(", "Writer", "_Writer", ",", "bool", "_wrap", ",", "ref", "bool", "_first", ")", "{", "if", "(", "_wrap", ")", "{", "_Writer", ".", "WriteObjectStart", "(", ")", ";", "}", "if", "(", "ResponderAccount", "!=", "null", ")", "{", "_Writer", ".", "WriteObjectSeparator", "(", "ref", "_first", ")", ";", "_Writer", ".", "WriteToken", "(", "\"", "ResponderAccount", "\"", ",", "1", ")", ";", "_Writer", ".", "WriteString", "(", "ResponderAccount", ")", ";", "}", "if", "(", "RequestIDs", "!=", "null", ")", "{", "_Writer", ".", "WriteObjectSeparator", "(", "ref", "_first", ")", ";", "_Writer", ".", "WriteToken", "(", "\"", "RequestIDs", "\"", ",", "1", ")", ";", "_Writer", ".", "WriteArrayStart", "(", ")", ";", "bool", "_firstarray", "=", "true", ";", "foreach", "(", "var", "_index", "in", "RequestIDs", ")", "{", "_Writer", ".", "WriteArraySeparator", "(", "ref", "_firstarray", ")", ";", "_Writer", ".", "WriteString", "(", "_index", ")", ";", "}", "_Writer", ".", "WriteArrayEnd", "(", ")", ";", "}", "if", "(", "ResponseIDs", "!=", "null", ")", "{", "_Writer", ".", "WriteObjectSeparator", "(", "ref", "_first", ")", ";", "_Writer", ".", "WriteToken", "(", "\"", "ResponseIDs", "\"", ",", "1", ")", ";", "_Writer", ".", "WriteArrayStart", "(", ")", ";", "bool", "_firstarray", "=", "true", ";", "foreach", "(", "var", "_index", "in", "ResponseIDs", ")", "{", "_Writer", ".", "WriteArraySeparator", "(", "ref", "_firstarray", ")", ";", "_Writer", ".", "WriteString", "(", "_index", ")", ";", "}", "_Writer", ".", "WriteArrayEnd", "(", ")", ";", "}", "if", "(", "ArchivedIDs", "!=", "null", ")", "{", "_Writer", ".", "WriteObjectSeparator", "(", "ref", "_first", ")", ";", "_Writer", ".", "WriteToken", "(", "\"", "ArchivedIDs", "\"", ",", "1", ")", ";", "_Writer", ".", "WriteArrayStart", "(", ")", ";", "bool", "_firstarray", "=", "true", ";", "foreach", "(", "var", "_index", "in", "ArchivedIDs", ")", "{", "_Writer", ".", "WriteArraySeparator", "(", "ref", "_firstarray", ")", ";", "_Writer", ".", "WriteString", "(", "_index", ")", ";", "}", "_Writer", ".", "WriteArrayEnd", "(", ")", ";", "}", "if", "(", "_wrap", ")", "{", "_Writer", ".", "WriteObjectEnd", "(", ")", ";", "}", "}", "public", "static", "new", "AccountEntry", "FromJSON", "(", "JSONReader", "JSONReader", ",", "bool", "Tagged", "=", "true", ")", "{", "if", "(", "JSONReader", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "Tagged", ")", "{", "var", "Out", "=", "JSONReader", ".", "ReadTaggedObject", "(", "_TagDictionary", ")", ";", "return", "Out", "as", "AccountEntry", ";", "}", "var", "Result", "=", "new", "AccountEntry", "(", ")", ";", "Result", ".", "Deserialize", "(", "JSONReader", ")", ";", "return", "Result", ";", "}", "public", "override", "void", "DeserializeToken", "(", "JSONReader", "JSONReader", ",", "string", "Tag", ")", "{", "switch", "(", "Tag", ")", "{", "case", "\"", "ResponderAccount", "\"", ":", "{", "ResponderAccount", "=", "JSONReader", ".", "ReadString", "(", ")", ";", "break", ";", "}", "case", "\"", "RequestIDs", "\"", ":", "{", "bool", "_Going", "=", "JSONReader", ".", "StartArray", "(", ")", ";", "RequestIDs", "=", "new", "List", "<", "string", ">", "(", ")", ";", "while", "(", "_Going", ")", "{", "string", "_Item", "=", "JSONReader", ".", "ReadString", "(", ")", ";", "RequestIDs", ".", "Add", "(", "_Item", ")", ";", "_Going", "=", "JSONReader", ".", "NextArray", "(", ")", ";", "}", "break", ";", "}", "case", "\"", "ResponseIDs", "\"", ":", "{", "bool", "_Going", "=", "JSONReader", ".", "StartArray", "(", ")", ";", "ResponseIDs", "=", "new", "List", "<", "string", ">", "(", ")", ";", "while", "(", "_Going", ")", "{", "string", "_Item", "=", "JSONReader", ".", "ReadString", "(", ")", ";", "ResponseIDs", ".", "Add", "(", "_Item", ")", ";", "_Going", "=", "JSONReader", ".", "NextArray", "(", ")", ";", "}", "break", ";", "}", "case", "\"", "ArchivedIDs", "\"", ":", "{", "bool", "_Going", "=", "JSONReader", ".", "StartArray", "(", ")", ";", "ArchivedIDs", "=", "new", "List", "<", "string", ">", "(", ")", ";", "while", "(", "_Going", ")", "{", "string", "_Item", "=", "JSONReader", ".", "ReadString", "(", ")", ";", "ArchivedIDs", ".", "Add", "(", "_Item", ")", ";", "_Going", "=", "JSONReader", ".", "NextArray", "(", ")", ";", "}", "break", ";", "}", "default", ":", "{", "break", ";", "}", "}", "}", "}" ]
[]
[ "/// <summary>", "///The Responder account the request is directed to.", "/// </summary>", "/// <summary>", "///List of BrokerIDs of pending requests", "/// </summary>", "/// <summary>", "///List of BrokerIDs of responses", "/// </summary>", "/// <summary>", "///List of expired requests, now archived.", "/// </summary>", "/// <summary>", "/// Tag identifying this class", "/// </summary>", "/// <summary>", "/// Factory method", "/// </summary>", "/// <returns>Object of this type</returns>", "/// <summary>", "/// Serialize this object to the specified output stream.", "/// </summary>", "/// <param name=\"Writer\">Output stream</param>", "/// <param name=\"wrap\">If true, output is wrapped with object", "/// start and end sequences '{ ... }'.</param>", "/// <param name=\"first\">If true, item is the first entry in a list.</param>", "/// <summary>", "/// Serialize this object to the specified output stream.", "/// Unlike the Serlialize() method, this method is not inherited from the", "/// parent class allowing a specific version of the method to be called.", "/// </summary>", "/// <param name=\"_Writer\">Output stream</param>", "/// <param name=\"_wrap\">If true, output is wrapped with object", "/// start and end sequences '{ ... }'.</param>", "/// <param name=\"_first\">If true, item is the first entry in a list.</param>", "/// <summary>", "/// Deserialize a tagged stream", "/// </summary>", "/// <param name=\"JSONReader\">The input stream</param>", "/// <param name=\"Tagged\">If true, the input is wrapped in a tag specifying the type</param>", "/// <returns>The created object.</returns>\t\t", "/// <summary>", "/// Having read a tag, process the corresponding value data.", "/// </summary>", "/// <param name=\"JSONReader\">The input stream</param>", "/// <param name=\"Tag\">The tag</param>", "// Have a sequence of values", "// Have a sequence of values", "// Have a sequence of values", "// check up that all the required elements are present" ]
[ { "param": "ConfirmProtocol", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ConfirmProtocol", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
897
90
4aad576db3b84e14b8090fe45a8b33bcfa5b1d7b
firebolt55439/ray
python/ray/util/actor_pool.py
[ "Apache-2.0" ]
Python
ActorPool
Utility class to operate on a fixed pool of actors. Arguments: actors (list): List of Ray actor handles to use in this pool. Examples: >>> a1, a2 = Actor.remote(), Actor.remote() >>> pool = ActorPool([a1, a2]) >>> print(list(pool.map(lambda a, v: a.double.remote(v),\ ... [1, 2, 3, 4]))) [2, 4, 6, 8]
Utility class to operate on a fixed pool of actors.
[ "Utility", "class", "to", "operate", "on", "a", "fixed", "pool", "of", "actors", "." ]
class ActorPool: """Utility class to operate on a fixed pool of actors. Arguments: actors (list): List of Ray actor handles to use in this pool. Examples: >>> a1, a2 = Actor.remote(), Actor.remote() >>> pool = ActorPool([a1, a2]) >>> print(list(pool.map(lambda a, v: a.double.remote(v),\ ... [1, 2, 3, 4]))) [2, 4, 6, 8] """ def __init__(self, actors): # actors to be used self._idle_actors = list(actors) # get actor from future self._future_to_actor = {} # get future from index self._index_to_future = {} # next task to do self._next_task_index = 0 # next task to return self._next_return_index = 0 # next work depending when actors free self._pending_submits = [] def map(self, fn, values): """Apply the given function in parallel over the actors and values. This returns an ordered iterator that will return results of the map as they finish. Note that you must iterate over the iterator to force the computation to finish. Arguments: fn (func): Function that takes (actor, value) as argument and returns an ObjectRef computing the result over the value. The actor will be considered busy until the ObjectRef completes. values (list): List of values that fn(actor, value) should be applied to. Returns: Iterator over results from applying fn to the actors and values. Examples: >>> pool = ActorPool(...) >>> print(list(pool.map(lambda a, v: a.double.remote(v),\ ... [1, 2, 3, 4]))) [2, 4, 6, 8] """ for v in values: self.submit(fn, v) while self.has_next(): yield self.get_next() def map_unordered(self, fn, values): """Similar to map(), but returning an unordered iterator. This returns an unordered iterator that will return results of the map as they finish. This can be more efficient that map() if some results take longer to compute than others. Arguments: fn (func): Function that takes (actor, value) as argument and returns an ObjectRef computing the result over the value. The actor will be considered busy until the ObjectRef completes. values (list): List of values that fn(actor, value) should be applied to. Returns: Iterator over results from applying fn to the actors and values. Examples: >>> pool = ActorPool(...) >>> print(list(pool.map_unordered(lambda a, v: a.double.remote(v),\ ... [1, 2, 3, 4]))) [6, 2, 4, 8] """ for v in values: self.submit(fn, v) while self.has_next(): yield self.get_next_unordered() def submit(self, fn, value): """Schedule a single task to run in the pool. This has the same argument semantics as map(), but takes on a single value instead of a list of values. The result can be retrieved using get_next() / get_next_unordered(). Arguments: fn (func): Function that takes (actor, value) as argument and returns an ObjectRef computing the result over the value. The actor will be considered busy until the ObjectRef completes. value (object): Value to compute a result for. Examples: >>> pool = ActorPool(...) >>> pool.submit(lambda a, v: a.double.remote(v), 1) >>> pool.submit(lambda a, v: a.double.remote(v), 2) >>> print(pool.get_next(), pool.get_next()) 2, 4 """ if self._idle_actors: actor = self._idle_actors.pop() future = fn(actor, value) self._future_to_actor[future] = (self._next_task_index, actor) self._index_to_future[self._next_task_index] = future self._next_task_index += 1 else: self._pending_submits.append((fn, value)) def has_next(self): """Returns whether there are any pending results to return. Returns: True if there are any pending results not yet returned. Examples: >>> pool = ActorPool(...) >>> pool.submit(lambda a, v: a.double.remote(v), 1) >>> print(pool.has_next()) True >>> print(pool.get_next()) 2 >>> print(pool.has_next()) False """ return bool(self._future_to_actor) def get_next(self, timeout=None): """Returns the next pending result in order. This returns the next result produced by submit(), blocking for up to the specified timeout until it is available. Returns: The next result. Raises: TimeoutError if the timeout is reached. Examples: >>> pool = ActorPool(...) >>> pool.submit(lambda a, v: a.double.remote(v), 1) >>> print(pool.get_next()) 2 """ if not self.has_next(): raise StopIteration("No more results to get") if self._next_return_index >= self._next_task_index: raise ValueError("It is not allowed to call get_next() after " "get_next_unordered().") future = self._index_to_future[self._next_return_index] if timeout is not None: res, _ = ray.wait([future], timeout=timeout) if not res: raise TimeoutError("Timed out waiting for result") del self._index_to_future[self._next_return_index] self._next_return_index += 1 i, a = self._future_to_actor.pop(future) self._return_actor(a) return ray.get(future) def get_next_unordered(self, timeout=None): """Returns any of the next pending results. This returns some result produced by submit(), blocking for up to the specified timeout until it is available. Unlike get_next(), the results are not always returned in same order as submitted, which can improve performance. Returns: The next result. Raises: TimeoutError if the timeout is reached. Examples: >>> pool = ActorPool(...) >>> pool.submit(lambda a, v: a.double.remote(v), 1) >>> pool.submit(lambda a, v: a.double.remote(v), 2) >>> print(pool.get_next_unordered()) 4 >>> print(pool.get_next_unordered()) 2 """ if not self.has_next(): raise StopIteration("No more results to get") # TODO(ekl) bulk wait for performance res, _ = ray.wait( list(self._future_to_actor), num_returns=1, timeout=timeout) if res: [future] = res else: raise TimeoutError("Timed out waiting for result") i, a = self._future_to_actor.pop(future) self._return_actor(a) del self._index_to_future[i] self._next_return_index = max(self._next_return_index, i + 1) return ray.get(future) def _return_actor(self, actor): self._idle_actors.append(actor) if self._pending_submits: self.submit(*self._pending_submits.pop(0))
[ "class", "ActorPool", ":", "def", "__init__", "(", "self", ",", "actors", ")", ":", "self", ".", "_idle_actors", "=", "list", "(", "actors", ")", "self", ".", "_future_to_actor", "=", "{", "}", "self", ".", "_index_to_future", "=", "{", "}", "self", ".", "_next_task_index", "=", "0", "self", ".", "_next_return_index", "=", "0", "self", ".", "_pending_submits", "=", "[", "]", "def", "map", "(", "self", ",", "fn", ",", "values", ")", ":", "\"\"\"Apply the given function in parallel over the actors and values.\n\n This returns an ordered iterator that will return results of the map\n as they finish. Note that you must iterate over the iterator to force\n the computation to finish.\n\n Arguments:\n fn (func): Function that takes (actor, value) as argument and\n returns an ObjectRef computing the result over the value. The\n actor will be considered busy until the ObjectRef completes.\n values (list): List of values that fn(actor, value) should be\n applied to.\n\n Returns:\n Iterator over results from applying fn to the actors and values.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> print(list(pool.map(lambda a, v: a.double.remote(v),\\\n ... [1, 2, 3, 4])))\n [2, 4, 6, 8]\n \"\"\"", "for", "v", "in", "values", ":", "self", ".", "submit", "(", "fn", ",", "v", ")", "while", "self", ".", "has_next", "(", ")", ":", "yield", "self", ".", "get_next", "(", ")", "def", "map_unordered", "(", "self", ",", "fn", ",", "values", ")", ":", "\"\"\"Similar to map(), but returning an unordered iterator.\n\n This returns an unordered iterator that will return results of the map\n as they finish. This can be more efficient that map() if some results\n take longer to compute than others.\n\n Arguments:\n fn (func): Function that takes (actor, value) as argument and\n returns an ObjectRef computing the result over the value. The\n actor will be considered busy until the ObjectRef completes.\n values (list): List of values that fn(actor, value) should be\n applied to.\n\n Returns:\n Iterator over results from applying fn to the actors and values.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> print(list(pool.map_unordered(lambda a, v: a.double.remote(v),\\\n ... [1, 2, 3, 4])))\n [6, 2, 4, 8]\n \"\"\"", "for", "v", "in", "values", ":", "self", ".", "submit", "(", "fn", ",", "v", ")", "while", "self", ".", "has_next", "(", ")", ":", "yield", "self", ".", "get_next_unordered", "(", ")", "def", "submit", "(", "self", ",", "fn", ",", "value", ")", ":", "\"\"\"Schedule a single task to run in the pool.\n\n This has the same argument semantics as map(), but takes on a single\n value instead of a list of values. The result can be retrieved using\n get_next() / get_next_unordered().\n\n Arguments:\n fn (func): Function that takes (actor, value) as argument and\n returns an ObjectRef computing the result over the value. The\n actor will be considered busy until the ObjectRef completes.\n value (object): Value to compute a result for.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> pool.submit(lambda a, v: a.double.remote(v), 2)\n >>> print(pool.get_next(), pool.get_next())\n 2, 4\n \"\"\"", "if", "self", ".", "_idle_actors", ":", "actor", "=", "self", ".", "_idle_actors", ".", "pop", "(", ")", "future", "=", "fn", "(", "actor", ",", "value", ")", "self", ".", "_future_to_actor", "[", "future", "]", "=", "(", "self", ".", "_next_task_index", ",", "actor", ")", "self", ".", "_index_to_future", "[", "self", ".", "_next_task_index", "]", "=", "future", "self", ".", "_next_task_index", "+=", "1", "else", ":", "self", ".", "_pending_submits", ".", "append", "(", "(", "fn", ",", "value", ")", ")", "def", "has_next", "(", "self", ")", ":", "\"\"\"Returns whether there are any pending results to return.\n\n Returns:\n True if there are any pending results not yet returned.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> print(pool.has_next())\n True\n >>> print(pool.get_next())\n 2\n >>> print(pool.has_next())\n False\n \"\"\"", "return", "bool", "(", "self", ".", "_future_to_actor", ")", "def", "get_next", "(", "self", ",", "timeout", "=", "None", ")", ":", "\"\"\"Returns the next pending result in order.\n\n This returns the next result produced by submit(), blocking for up to\n the specified timeout until it is available.\n\n Returns:\n The next result.\n\n Raises:\n TimeoutError if the timeout is reached.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> print(pool.get_next())\n 2\n \"\"\"", "if", "not", "self", ".", "has_next", "(", ")", ":", "raise", "StopIteration", "(", "\"No more results to get\"", ")", "if", "self", ".", "_next_return_index", ">=", "self", ".", "_next_task_index", ":", "raise", "ValueError", "(", "\"It is not allowed to call get_next() after \"", "\"get_next_unordered().\"", ")", "future", "=", "self", ".", "_index_to_future", "[", "self", ".", "_next_return_index", "]", "if", "timeout", "is", "not", "None", ":", "res", ",", "_", "=", "ray", ".", "wait", "(", "[", "future", "]", ",", "timeout", "=", "timeout", ")", "if", "not", "res", ":", "raise", "TimeoutError", "(", "\"Timed out waiting for result\"", ")", "del", "self", ".", "_index_to_future", "[", "self", ".", "_next_return_index", "]", "self", ".", "_next_return_index", "+=", "1", "i", ",", "a", "=", "self", ".", "_future_to_actor", ".", "pop", "(", "future", ")", "self", ".", "_return_actor", "(", "a", ")", "return", "ray", ".", "get", "(", "future", ")", "def", "get_next_unordered", "(", "self", ",", "timeout", "=", "None", ")", ":", "\"\"\"Returns any of the next pending results.\n\n This returns some result produced by submit(), blocking for up to\n the specified timeout until it is available. Unlike get_next(), the\n results are not always returned in same order as submitted, which can\n improve performance.\n\n Returns:\n The next result.\n\n Raises:\n TimeoutError if the timeout is reached.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> pool.submit(lambda a, v: a.double.remote(v), 2)\n >>> print(pool.get_next_unordered())\n 4\n >>> print(pool.get_next_unordered())\n 2\n \"\"\"", "if", "not", "self", ".", "has_next", "(", ")", ":", "raise", "StopIteration", "(", "\"No more results to get\"", ")", "res", ",", "_", "=", "ray", ".", "wait", "(", "list", "(", "self", ".", "_future_to_actor", ")", ",", "num_returns", "=", "1", ",", "timeout", "=", "timeout", ")", "if", "res", ":", "[", "future", "]", "=", "res", "else", ":", "raise", "TimeoutError", "(", "\"Timed out waiting for result\"", ")", "i", ",", "a", "=", "self", ".", "_future_to_actor", ".", "pop", "(", "future", ")", "self", ".", "_return_actor", "(", "a", ")", "del", "self", ".", "_index_to_future", "[", "i", "]", "self", ".", "_next_return_index", "=", "max", "(", "self", ".", "_next_return_index", ",", "i", "+", "1", ")", "return", "ray", ".", "get", "(", "future", ")", "def", "_return_actor", "(", "self", ",", "actor", ")", ":", "self", ".", "_idle_actors", ".", "append", "(", "actor", ")", "if", "self", ".", "_pending_submits", ":", "self", ".", "submit", "(", "*", "self", ".", "_pending_submits", ".", "pop", "(", "0", ")", ")" ]
Utility class to operate on a fixed pool of actors.
[ "Utility", "class", "to", "operate", "on", "a", "fixed", "pool", "of", "actors", "." ]
[ "\"\"\"Utility class to operate on a fixed pool of actors.\n\n Arguments:\n actors (list): List of Ray actor handles to use in this pool.\n\n Examples:\n >>> a1, a2 = Actor.remote(), Actor.remote()\n >>> pool = ActorPool([a1, a2])\n >>> print(list(pool.map(lambda a, v: a.double.remote(v),\\\n ... [1, 2, 3, 4])))\n [2, 4, 6, 8]\n \"\"\"", "# actors to be used", "# get actor from future", "# get future from index", "# next task to do", "# next task to return", "# next work depending when actors free", "\"\"\"Apply the given function in parallel over the actors and values.\n\n This returns an ordered iterator that will return results of the map\n as they finish. Note that you must iterate over the iterator to force\n the computation to finish.\n\n Arguments:\n fn (func): Function that takes (actor, value) as argument and\n returns an ObjectRef computing the result over the value. The\n actor will be considered busy until the ObjectRef completes.\n values (list): List of values that fn(actor, value) should be\n applied to.\n\n Returns:\n Iterator over results from applying fn to the actors and values.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> print(list(pool.map(lambda a, v: a.double.remote(v),\\\n ... [1, 2, 3, 4])))\n [2, 4, 6, 8]\n \"\"\"", "\"\"\"Similar to map(), but returning an unordered iterator.\n\n This returns an unordered iterator that will return results of the map\n as they finish. This can be more efficient that map() if some results\n take longer to compute than others.\n\n Arguments:\n fn (func): Function that takes (actor, value) as argument and\n returns an ObjectRef computing the result over the value. The\n actor will be considered busy until the ObjectRef completes.\n values (list): List of values that fn(actor, value) should be\n applied to.\n\n Returns:\n Iterator over results from applying fn to the actors and values.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> print(list(pool.map_unordered(lambda a, v: a.double.remote(v),\\\n ... [1, 2, 3, 4])))\n [6, 2, 4, 8]\n \"\"\"", "\"\"\"Schedule a single task to run in the pool.\n\n This has the same argument semantics as map(), but takes on a single\n value instead of a list of values. The result can be retrieved using\n get_next() / get_next_unordered().\n\n Arguments:\n fn (func): Function that takes (actor, value) as argument and\n returns an ObjectRef computing the result over the value. The\n actor will be considered busy until the ObjectRef completes.\n value (object): Value to compute a result for.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> pool.submit(lambda a, v: a.double.remote(v), 2)\n >>> print(pool.get_next(), pool.get_next())\n 2, 4\n \"\"\"", "\"\"\"Returns whether there are any pending results to return.\n\n Returns:\n True if there are any pending results not yet returned.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> print(pool.has_next())\n True\n >>> print(pool.get_next())\n 2\n >>> print(pool.has_next())\n False\n \"\"\"", "\"\"\"Returns the next pending result in order.\n\n This returns the next result produced by submit(), blocking for up to\n the specified timeout until it is available.\n\n Returns:\n The next result.\n\n Raises:\n TimeoutError if the timeout is reached.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> print(pool.get_next())\n 2\n \"\"\"", "\"\"\"Returns any of the next pending results.\n\n This returns some result produced by submit(), blocking for up to\n the specified timeout until it is available. Unlike get_next(), the\n results are not always returned in same order as submitted, which can\n improve performance.\n\n Returns:\n The next result.\n\n Raises:\n TimeoutError if the timeout is reached.\n\n Examples:\n >>> pool = ActorPool(...)\n >>> pool.submit(lambda a, v: a.double.remote(v), 1)\n >>> pool.submit(lambda a, v: a.double.remote(v), 2)\n >>> print(pool.get_next_unordered())\n 4\n >>> print(pool.get_next_unordered())\n 2\n \"\"\"", "# TODO(ekl) bulk wait for performance" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "actors", "type": null, "docstring": "List of Ray actor handles to use in this pool.", "docstring_tokens": [ "List", "of", "Ray", "actor", "handles", "to", "use", "in", "this", "pool", "." ], "default": null, "is_optional": false } ], "others": [ { "identifier": "examples", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
14
1,647
106
415b9c2c3754193cc41de9d1dee1d19db2b7f8cb
cvanderjagt/Multiplayer-Compatibility
Source/Mods/GiddyUpRideAndRoll.cs
[ "MIT" ]
C#
GiddyUpRideAndRollCompat
/// <summary>Giddy Up! Ride and Roll by Roolo</summary> /// <remarks>Designated areas are trouble</remarks> /// <see href="https://github.com/rheirman/GiddyUpRideAndRoll"/> /// <see href="https://steamcommunity.com/sharedfiles/filedetails/?id=1331961995"/>
Giddy Up. Ride and Roll by Roolo
[ "Giddy", "Up", ".", "Ride", "and", "Roll", "by", "Roolo" ]
[MpCompatFor("Giddy-up! Ride and Roll")] public class GiddyUpRideAndRollCompat { static Type AreaGUType; static FieldInfo AreaLabelField; static MethodInfo SetSelectedAreaMethod; static Type DesignatorDropAnimalExpandType; static Type DesignatorDropAnimalClearType; static Type DesignatorNoMountExpandType; static Type DesignatorNoMountClearType; public GiddyUpRideAndRollCompat(ModContentPack mod) { MP.RegisterSyncDelegate( AccessTools.TypeByName("GiddyUpRideAndRoll.Harmony.Pawn_GetGizmos"), "<>c__DisplayClass1_0", "<CreateGizmo_LeaveRider>b__0" ); MP.RegisterSyncMethod( AccessTools.Method("GiddyUpRideAndRoll.Harmony.CaravanEnterMapUtility_Enter:MountCaravanMounts") ); { MP.RegisterSyncMethod(AccessTools.Method("GiddyUpRideAndRoll.PawnColumns.PawnColumnWorker_RR_Mountable_Anyone:SetValue")); MP.RegisterSyncMethod(AccessTools.Method("GiddyUpRideAndRoll.PawnColumns.PawnColumnWorker_RR_Mountable_Master:SetValue")); } { AreaGUType = AccessTools.TypeByName("GiddyUpCore.Zones.Area_GU"); MpCompat.harmony.Patch(AccessTools.Method("Verse.AreaManager:AddStartingAreas"), postfix: new HarmonyMethod(typeof(GiddyUpRideAndRollCompat), nameof(AddStartingAreasPostfix)) ); MpCompat.harmony.Patch(AccessTools.Method(AreaGUType, "GetUniqueLoadID"), postfix: new HarmonyMethod(typeof(GiddyUpRideAndRollCompat), nameof(GetUniqueLoadIDPostfix)) ); } { Type type = AccessTools.TypeByName("GiddyUpCore.Zones.Designator_GU"); AreaLabelField = AccessTools.Field(type, "areaLabel"); SetSelectedAreaMethod = AccessTools.Method(type, "setSelectedArea"); MP.RegisterSyncWorker<Designator>(DesignatorGU, type, true); DesignatorDropAnimalExpandType = AccessTools.TypeByName("GiddyUpRideAndRoll.Zones.Designator_GU_DropAnimal_Expand"); DesignatorDropAnimalClearType = AccessTools.TypeByName("GiddyUpRideAndRoll.Zones.Designator_GU_DropAnimal_Clear"); DesignatorNoMountExpandType = AccessTools.TypeByName("GiddyUpRideAndRoll.Zones.Designator_GU_NoMount_Expand"); DesignatorNoMountClearType = AccessTools.TypeByName("GiddyUpRideAndRoll.Zones.Designator_GU_NoMount_Clear"); } } #region Designators static void DesignatorGU(SyncWorker sync, ref Designator designator) { if (sync.isWriting) { Type t = designator.GetType(); byte tByte = ByteFromType(t); sync.Write(tByte); } else { byte tByte = sync.Read<byte>(); Type t = TypeFromByte(tByte); designator = (Designator) Activator.CreateInstance(t); string label = (string) AreaLabelField.GetValue(designator); SetSelectedAreaMethod.Invoke(designator, new object[] { label }); } } static Type TypeFromByte(byte tByte) { switch (tByte) { case 1: return DesignatorDropAnimalExpandType; case 2: return DesignatorDropAnimalClearType; case 3: return DesignatorNoMountExpandType; case 4: return DesignatorNoMountClearType; default: throw new Exception("Unknown Designator for GiddyUP"); } } static byte ByteFromType(Type type) { if (type == DesignatorDropAnimalExpandType) { return 1; } if (type == DesignatorDropAnimalClearType) { return 2; } if (type == DesignatorNoMountExpandType) { return 3; } if (type == DesignatorNoMountClearType) { return 4; } throw new Exception("Unknown Designator for GiddyUP"); } #endregion #region AreaGU static void AddStartingAreasPostfix(AreaManager __instance) { string[] zoneNames = { "Gu_Area_DropMount", "Gu_Area_NoMount", }; foreach(string name in zoneNames) { var areaGU = (Area) Activator.CreateInstance(AreaGUType, new object[] { __instance, name }); __instance.areas.Add(areaGU); } } static void GetUniqueLoadIDPostfix(Area __instance, ref string __result) { __result = __result + "_" + __instance.ID; } #endregion }
[ "[", "MpCompatFor", "(", "\"", "Giddy-up! Ride and Roll", "\"", ")", "]", "public", "class", "GiddyUpRideAndRollCompat", "{", "static", "Type", "AreaGUType", ";", "static", "FieldInfo", "AreaLabelField", ";", "static", "MethodInfo", "SetSelectedAreaMethod", ";", "static", "Type", "DesignatorDropAnimalExpandType", ";", "static", "Type", "DesignatorDropAnimalClearType", ";", "static", "Type", "DesignatorNoMountExpandType", ";", "static", "Type", "DesignatorNoMountClearType", ";", "public", "GiddyUpRideAndRollCompat", "(", "ModContentPack", "mod", ")", "{", "MP", ".", "RegisterSyncDelegate", "(", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpRideAndRoll.Harmony.Pawn_GetGizmos", "\"", ")", ",", "\"", "<>c__DisplayClass1_0", "\"", ",", "\"", "<CreateGizmo_LeaveRider>b__0", "\"", ")", ";", "MP", ".", "RegisterSyncMethod", "(", "AccessTools", ".", "Method", "(", "\"", "GiddyUpRideAndRoll.Harmony.CaravanEnterMapUtility_Enter:MountCaravanMounts", "\"", ")", ")", ";", "{", "MP", ".", "RegisterSyncMethod", "(", "AccessTools", ".", "Method", "(", "\"", "GiddyUpRideAndRoll.PawnColumns.PawnColumnWorker_RR_Mountable_Anyone:SetValue", "\"", ")", ")", ";", "MP", ".", "RegisterSyncMethod", "(", "AccessTools", ".", "Method", "(", "\"", "GiddyUpRideAndRoll.PawnColumns.PawnColumnWorker_RR_Mountable_Master:SetValue", "\"", ")", ")", ";", "}", "{", "AreaGUType", "=", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpCore.Zones.Area_GU", "\"", ")", ";", "MpCompat", ".", "harmony", ".", "Patch", "(", "AccessTools", ".", "Method", "(", "\"", "Verse.AreaManager:AddStartingAreas", "\"", ")", ",", "postfix", ":", "new", "HarmonyMethod", "(", "typeof", "(", "GiddyUpRideAndRollCompat", ")", ",", "nameof", "(", "AddStartingAreasPostfix", ")", ")", ")", ";", "MpCompat", ".", "harmony", ".", "Patch", "(", "AccessTools", ".", "Method", "(", "AreaGUType", ",", "\"", "GetUniqueLoadID", "\"", ")", ",", "postfix", ":", "new", "HarmonyMethod", "(", "typeof", "(", "GiddyUpRideAndRollCompat", ")", ",", "nameof", "(", "GetUniqueLoadIDPostfix", ")", ")", ")", ";", "}", "{", "Type", "type", "=", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpCore.Zones.Designator_GU", "\"", ")", ";", "AreaLabelField", "=", "AccessTools", ".", "Field", "(", "type", ",", "\"", "areaLabel", "\"", ")", ";", "SetSelectedAreaMethod", "=", "AccessTools", ".", "Method", "(", "type", ",", "\"", "setSelectedArea", "\"", ")", ";", "MP", ".", "RegisterSyncWorker", "<", "Designator", ">", "(", "DesignatorGU", ",", "type", ",", "true", ")", ";", "DesignatorDropAnimalExpandType", "=", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpRideAndRoll.Zones.Designator_GU_DropAnimal_Expand", "\"", ")", ";", "DesignatorDropAnimalClearType", "=", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpRideAndRoll.Zones.Designator_GU_DropAnimal_Clear", "\"", ")", ";", "DesignatorNoMountExpandType", "=", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpRideAndRoll.Zones.Designator_GU_NoMount_Expand", "\"", ")", ";", "DesignatorNoMountClearType", "=", "AccessTools", ".", "TypeByName", "(", "\"", "GiddyUpRideAndRoll.Zones.Designator_GU_NoMount_Clear", "\"", ")", ";", "}", "}", "region", " Designators", "static", "void", "DesignatorGU", "(", "SyncWorker", "sync", ",", "ref", "Designator", "designator", ")", "{", "if", "(", "sync", ".", "isWriting", ")", "{", "Type", "t", "=", "designator", ".", "GetType", "(", ")", ";", "byte", "tByte", "=", "ByteFromType", "(", "t", ")", ";", "sync", ".", "Write", "(", "tByte", ")", ";", "}", "else", "{", "byte", "tByte", "=", "sync", ".", "Read", "<", "byte", ">", "(", ")", ";", "Type", "t", "=", "TypeFromByte", "(", "tByte", ")", ";", "designator", "=", "(", "Designator", ")", "Activator", ".", "CreateInstance", "(", "t", ")", ";", "string", "label", "=", "(", "string", ")", "AreaLabelField", ".", "GetValue", "(", "designator", ")", ";", "SetSelectedAreaMethod", ".", "Invoke", "(", "designator", ",", "new", "object", "[", "]", "{", "label", "}", ")", ";", "}", "}", "static", "Type", "TypeFromByte", "(", "byte", "tByte", ")", "{", "switch", "(", "tByte", ")", "{", "case", "1", ":", "return", "DesignatorDropAnimalExpandType", ";", "case", "2", ":", "return", "DesignatorDropAnimalClearType", ";", "case", "3", ":", "return", "DesignatorNoMountExpandType", ";", "case", "4", ":", "return", "DesignatorNoMountClearType", ";", "default", ":", "throw", "new", "Exception", "(", "\"", "Unknown Designator for GiddyUP", "\"", ")", ";", "}", "}", "static", "byte", "ByteFromType", "(", "Type", "type", ")", "{", "if", "(", "type", "==", "DesignatorDropAnimalExpandType", ")", "{", "return", "1", ";", "}", "if", "(", "type", "==", "DesignatorDropAnimalClearType", ")", "{", "return", "2", ";", "}", "if", "(", "type", "==", "DesignatorNoMountExpandType", ")", "{", "return", "3", ";", "}", "if", "(", "type", "==", "DesignatorNoMountClearType", ")", "{", "return", "4", ";", "}", "throw", "new", "Exception", "(", "\"", "Unknown Designator for GiddyUP", "\"", ")", ";", "}", "endregion", "region", " AreaGU", "static", "void", "AddStartingAreasPostfix", "(", "AreaManager", "__instance", ")", "{", "string", "[", "]", "zoneNames", "=", "{", "\"", "Gu_Area_DropMount", "\"", ",", "\"", "Gu_Area_NoMount", "\"", ",", "}", ";", "foreach", "(", "string", "name", "in", "zoneNames", ")", "{", "var", "areaGU", "=", "(", "Area", ")", "Activator", ".", "CreateInstance", "(", "AreaGUType", ",", "new", "object", "[", "]", "{", "__instance", ",", "name", "}", ")", ";", "__instance", ".", "areas", ".", "Add", "(", "areaGU", ")", ";", "}", "}", "static", "void", "GetUniqueLoadIDPostfix", "(", "Area", "__instance", ",", "ref", "string", "__result", ")", "{", "__result", "=", "__result", "+", "\"", "_", "\"", "+", "__instance", ".", "ID", ";", "}", "endregion", "}" ]
Giddy Up!
[ "Giddy", "Up!" ]
[ "// Stop waiting", "// Unsure... May not be needed. Harmless to have it.", "// Pawn Column Workers", "// AreaGU Randomness", "// Designators", "// This prevents GiddyUP from creating the areas while the game is already going", "// Multiplayer supports many player factions, GiddyUP assumes their areas are unique", "// This seems to do the job just fine with no side effects" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "Designated areas are trouble", "docstring_tokens": [ "Designated", "areas", "are", "trouble" ] }, { "identifier": "see", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "see", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
17
1,044
78
4fafd656182e8cbcb87ba045e3e35bbec85decd2
andreas-nesheim/maui
src/Compatibility/ControlGallery/src/Issues.Shared/Issue2976.cs
[ "MIT" ]
C#
NativeListViewPage2
/// <summary> /// This page uses a custom renderer that wraps native list controls: /// iOS : UITableView /// Android : ListView (do not confuse with Xamarin.Forms ListView) /// Windows Phone : ? /// /// It uses a CUSTOM row/cell class that is defined natively which /// is still faster than a Xamarin.Forms-defined ViewCell subclass. /// </summary>
It uses a CUSTOM row/cell class that is defined natively which is still faster than a Xamarin.Forms-defined ViewCell subclass.
[ "It", "uses", "a", "CUSTOM", "row", "/", "cell", "class", "that", "is", "defined", "natively", "which", "is", "still", "faster", "than", "a", "Xamarin", ".", "Forms", "-", "defined", "ViewCell", "subclass", "." ]
[Preserve(AllMembers = true)] public class NativeListViewPage2 : ContentPage { public NativeListViewPage2() { var nativeListView2 = new NativeListView2(); nativeListView2.VerticalOptions = LayoutOptions.FillAndExpand; nativeListView2.Items = DataSource.GetList(); nativeListView2.ItemSelected += async (sender, e) => { await DisplayAlert("clicked", "one of the rows was clicked", "ok"); }; Content = new StackLayout { Padding = Device.RuntimePlatform == Device.iOS ? new Thickness(0, 20, 0, 0) : new Thickness(0), Children = { new Label { HorizontalTextAlignment = TextAlignment.Center, Text = Device.RuntimePlatform == Device.iOS ? "Custom UITableView+UICell" : Device.RuntimePlatform == Device.Android ? "Custom ListView+Cell" : "Custom renderer todo" }, nativeListView2 } }; } }
[ "[", "Preserve", "(", "AllMembers", "=", "true", ")", "]", "public", "class", "NativeListViewPage2", ":", "ContentPage", "{", "public", "NativeListViewPage2", "(", ")", "{", "var", "nativeListView2", "=", "new", "NativeListView2", "(", ")", ";", "nativeListView2", ".", "VerticalOptions", "=", "LayoutOptions", ".", "FillAndExpand", ";", "nativeListView2", ".", "Items", "=", "DataSource", ".", "GetList", "(", ")", ";", "nativeListView2", ".", "ItemSelected", "+=", "async", "(", "sender", ",", "e", ")", "=>", "{", "await", "DisplayAlert", "(", "\"", "clicked", "\"", ",", "\"", "one of the rows was clicked", "\"", ",", "\"", "ok", "\"", ")", ";", "}", ";", "Content", "=", "new", "StackLayout", "{", "Padding", "=", "Device", ".", "RuntimePlatform", "==", "Device", ".", "iOS", "?", "new", "Thickness", "(", "0", ",", "20", ",", "0", ",", "0", ")", ":", "new", "Thickness", "(", "0", ")", ",", "Children", "=", "{", "new", "Label", "{", "HorizontalTextAlignment", "=", "TextAlignment", ".", "Center", ",", "Text", "=", "Device", ".", "RuntimePlatform", "==", "Device", ".", "iOS", "?", "\"", "Custom UITableView+UICell", "\"", ":", "Device", ".", "RuntimePlatform", "==", "Device", ".", "Android", "?", "\"", "Custom ListView+Cell", "\"", ":", "\"", "Custom renderer todo", "\"", "}", ",", "nativeListView2", "}", "}", ";", "}", "}" ]
This page uses a custom renderer that wraps native list controls: iOS : UITableView Android : ListView (do not confuse with Xamarin.Forms ListView) Windows Phone : ?
[ "This", "page", "uses", "a", "custom", "renderer", "that", "wraps", "native", "list", "controls", ":", "iOS", ":", "UITableView", "Android", ":", "ListView", "(", "do", "not", "confuse", "with", "Xamarin", ".", "Forms", "ListView", ")", "Windows", "Phone", ":", "?" ]
[ "// CUSTOM RENDERER using a native control", "// REQUIRED: To share a scrollable view with other views in a StackLayout, it should have a VerticalOptions of FillAndExpand.", "//await Navigation.PushModalAsync (new DetailPage(e.SelectedItem));", "// The root page of your application" ]
[ { "param": "ContentPage", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ContentPage", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
18
228
81
c1f2ab6c2879f690c9f9bda6392b761660acd68d
yasielsegui/hackabot
node_modules/skype-sdk/lib/calling/model/recognition-option.js
[ "MIT" ]
JavaScript
RecognitionOption
/** * This is part of the "recognize" action. If the customer wants to speech/dtmf choice based recognition - this needs to be specified. * Ex: say "Sales" or enter 1 for Sales department * * @extends AbstractModelType * * @property {String} name - Name of the choice. Once a choice matches, this name is conveyed back to the customer in the outcome. * @property {String} speechVariation - optional. Speech variations which form the grammar for the choice ( Ex: Name : "Yes" , SpeechVariation : {"Yes", "yeah", "ya", "yo" ). * @property {String[]} dtmfVariation - optional. Dtmf variations for the choice, Ex: Name : "Yes" , DtmfVariation : {'1'} */
This is part of the "recognize" action. If the customer wants to speech/dtmf choice based recognition - this needs to be specified. Ex: say "Sales" or enter 1 for Sales department @property {String} name - Name of the choice. Once a choice matches, this name is conveyed back to the customer in the outcome. @property {String} speechVariation - optional.
[ "This", "is", "part", "of", "the", "\"", "recognize", "\"", "action", ".", "If", "the", "customer", "wants", "to", "speech", "/", "dtmf", "choice", "based", "recognition", "-", "this", "needs", "to", "be", "specified", ".", "Ex", ":", "say", "\"", "Sales", "\"", "or", "enter", "1", "for", "Sales", "department", "@property", "{", "String", "}", "name", "-", "Name", "of", "the", "choice", ".", "Once", "a", "choice", "matches", "this", "name", "is", "conveyed", "back", "to", "the", "customer", "in", "the", "outcome", ".", "@property", "{", "String", "}", "speechVariation", "-", "optional", "." ]
class RecognitionOption extends AbstractModelType { /** * Creates a new recognition option * * @param {object} inputData - the object received from Calling service, or null if constructing from scratch. */ constructor(inputData) { super(); this.name = null; this.speechVariation = null; this.dtmfVariation = null; if(inputData != null) this.populatePlainInput(inputData); } /** * validates the object instance * * @param context * @returns {Array} - validation errors */ validate(context) { var errors = []; errors = errors.concat(ModelValidation.validateString(context, this.name, 'RecognitionOption.name')); var speechVariationSet = this.speechVariation != null; var dmftVariationSet = this.dtmfVariation != null; if(!speechVariationSet && !dmftVariationSet) { errors.push('Neither RecognitionOption.speechVariation or RecognitionOption.dmftVariation is set'); } else { if(speechVariationSet) { errors = errors.concat(ModelValidation.validateArray(context, this.speechVariation, 'RecognitionOption.speechVariation', false, false, CallingModelLimits.NumberOfSpeechVariations.Max)); if(errors.length == 0) { this.speechVariation.forEach(function(item){ errors = errors.concat(ModelValidation.validateString(context, item, 'RecognitionOption.speechVariation item', false)); }); } } if(dmftVariationSet) { errors = errors.concat(DtmfsValidaton.validateDtmfs(context, this.dtmfVariation, 'RecognitionOption.dtmfVariation')); } } return errors; } }
[ "class", "RecognitionOption", "extends", "AbstractModelType", "{", "constructor", "(", "inputData", ")", "{", "super", "(", ")", ";", "this", ".", "name", "=", "null", ";", "this", ".", "speechVariation", "=", "null", ";", "this", ".", "dtmfVariation", "=", "null", ";", "if", "(", "inputData", "!=", "null", ")", "this", ".", "populatePlainInput", "(", "inputData", ")", ";", "}", "validate", "(", "context", ")", "{", "var", "errors", "=", "[", "]", ";", "errors", "=", "errors", ".", "concat", "(", "ModelValidation", ".", "validateString", "(", "context", ",", "this", ".", "name", ",", "'RecognitionOption.name'", ")", ")", ";", "var", "speechVariationSet", "=", "this", ".", "speechVariation", "!=", "null", ";", "var", "dmftVariationSet", "=", "this", ".", "dtmfVariation", "!=", "null", ";", "if", "(", "!", "speechVariationSet", "&&", "!", "dmftVariationSet", ")", "{", "errors", ".", "push", "(", "'Neither RecognitionOption.speechVariation or RecognitionOption.dmftVariation is set'", ")", ";", "}", "else", "{", "if", "(", "speechVariationSet", ")", "{", "errors", "=", "errors", ".", "concat", "(", "ModelValidation", ".", "validateArray", "(", "context", ",", "this", ".", "speechVariation", ",", "'RecognitionOption.speechVariation'", ",", "false", ",", "false", ",", "CallingModelLimits", ".", "NumberOfSpeechVariations", ".", "Max", ")", ")", ";", "if", "(", "errors", ".", "length", "==", "0", ")", "{", "this", ".", "speechVariation", ".", "forEach", "(", "function", "(", "item", ")", "{", "errors", "=", "errors", ".", "concat", "(", "ModelValidation", ".", "validateString", "(", "context", ",", "item", ",", "'RecognitionOption.speechVariation item'", ",", "false", ")", ")", ";", "}", ")", ";", "}", "}", "if", "(", "dmftVariationSet", ")", "{", "errors", "=", "errors", ".", "concat", "(", "DtmfsValidaton", ".", "validateDtmfs", "(", "context", ",", "this", ".", "dtmfVariation", ",", "'RecognitionOption.dtmfVariation'", ")", ")", ";", "}", "}", "return", "errors", ";", "}", "}" ]
This is part of the "recognize" action.
[ "This", "is", "part", "of", "the", "\"", "recognize", "\"", "action", "." ]
[ "/**\n * Creates a new recognition option\n *\n * @param {object} inputData - the object received from Calling service, or null if constructing from scratch.\n */", "/**\n * validates the object instance\n *\n * @param context\n * @returns {Array} - validation errors\n */" ]
[ { "param": "AbstractModelType", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "AbstractModelType", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
24
392
173
8ef98db40f02b282f5d3c3b2a7d4a2fbb20f11aa
Tape-Worm/Gorgon
Examples/Gorgon.FileSystem/MultiSource/FormMain.cs
[ "MIT" ]
C#
FormMain
/// <summary> /// Main application interface. /// </summary> /// <remarks> /// In this example we will mount two different data sources into a virtual file system. /// /// The file system is able to mount different data sources into the same file system which will allow for access /// to multiple sets of files as a unified file system. Here we mount a physical file system folder as the root /// of the file system and a zip file as a virtual subdirectory in the virtual file system. Accessing these /// files is just a matter of getting the file entry and loading the data as a stream. /// /// You may mount multiple data sources into the same virtual directory (i.e. the root, or a sub directory) and the /// files from each data source will be merged. However, the caveat here is the order in which the file systems /// are mounted. If 2 or more data sources contain the same file names, then the data source that was mounted /// last will take precedence over the previous file systems. For example, if D:\directory\filename.txt exists in /// the virtual root as "/filename.txt" and we mount a zip file that has filename.txt in the root of the zip file, /// then when we open filename.txt from the virtual file system we will be opening the file from the zip file. /// /// We begin the example by loading the file system provider for zip files, and then mounting a physical folder /// and then the zip file into a virtual subdirectory. From there we enumerate the files and virtual sub directories /// into the tree view. Opening a file can be done either from the file entry as shown in the example, or it can be /// opened via the file system interface (allowing the user to pass a full path to the file). Files can be returned /// as a stream (OpenStream) or an array of bytes (ReadFile). Please note that writing to these file systems is not /// supported and can only be done when a write directory is set. This will be covered in another example. /// </remarks>
Main application interface.
[ "Main", "application", "interface", "." ]
public partial class FormMain : Form { #region Variables. private GorgonFileSystem _fileSystem; private PictureBox _picture; private Image _image; private TextBox _textDisplay; private Font _textFont; private Label _instructions; #endregion #region Methods. private void TreeFileSystem_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) { if (splitFileSystem.Panel2.Controls.Count > 0) { splitFileSystem.Panel2.Controls.RemoveAt(0); } try { if (!(e.Node?.Tag is IGorgonVirtualFile)) { splitFileSystem.Panel2.Controls.Add(_instructions); return; } _picture.Image = null; _textDisplay.Text = string.Empty; var file = (IGorgonVirtualFile)e.Node.Tag; using (Stream fileStream = file.OpenStream()) { switch (file.Extension.ToLower()) { case ".jpg": case ".jpeg": case ".bmp": case ".png": if (_image != null) { _image.Dispose(); _image = null; } _image = Image.FromStream(fileStream); _picture.Image = _image; _picture.SizeMode = PictureBoxSizeMode.Zoom; splitFileSystem.Panel2.Controls.Add(_picture); _picture.Dock = DockStyle.Fill; break; default: byte[] textData = new byte[fileStream.Length]; fileStream.Read(textData, 0, textData.Length); _textDisplay.Text = Encoding.UTF8.GetString(textData); _textDisplay.Multiline = true; _textDisplay.ReadOnly = true; _textDisplay.ScrollBars = ScrollBars.Both; _textDisplay.Dock = DockStyle.Fill; splitFileSystem.Panel2.Controls.Add(_textDisplay); break; } } } catch (Exception ex) { ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), Program.Log); splitFileSystem.Panel2.Controls.Add(_instructions); } } private void TreeFileSystem_BeforeExpand(object sender, TreeViewCancelEventArgs e) { try { if (!(e.Node.Tag is IGorgonVirtualDirectory directory)) { e.Cancel = true; return; } FillTree(directory); } catch (Exception ex) { ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), Program.Log); } } private void TreeFileSystem_BeforeCollapse(object sender, TreeViewCancelEventArgs e) { var directory = e.Node.Tag as IGorgonVirtualDirectory; try { if (directory == _fileSystem.RootDirectory) { e.Cancel = true; } } catch (Exception ex) { ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), Program.Log); } } private void LoadZipFileSystemProvider() { const string zipProviderPlugInName = "Gorgon.IO.Zip.ZipProvider"; using (var pluginAssemblies = new GorgonMefPlugInCache(Program.Log)) { pluginAssemblies.LoadPlugInAssemblies(Program.PlugInPath, "Gorgon.FileSystem.Zip.DLL"); var providerFactory = new GorgonFileSystemProviderFactory( new GorgonMefPlugInService(pluginAssemblies), Program.Log); _fileSystem = new GorgonFileSystem(providerFactory.CreateProvider(zipProviderPlugInName), Program.Log); } } private void FillTree(IGorgonVirtualDirectory directory) { TreeNodeCollection nodes; TreeNode parentNode; if (directory == null) { directory = _fileSystem.RootDirectory; nodes = treeFileSystem.Nodes; parentNode = new TreeNode("/") { Name = "/" }; parentNode.SelectedImageIndex = parentNode.ImageIndex = 0; } else { TreeNode[] searchNodes = treeFileSystem.Nodes.Find(directory.FullPath, true); if (searchNodes.Length > 0) { parentNode = searchNodes[0]; nodes = parentNode.Nodes; } else { GorgonDialogs.ErrorBox(this, "Could not find the virtual directory '" + directory.FullPath + "'"); return; } } parentNode.Tag = directory; treeFileSystem.BeforeExpand -= TreeFileSystem_BeforeExpand; try { treeFileSystem.BeginUpdate(); nodes.Clear(); if (parentNode.Tag == _fileSystem.RootDirectory) { nodes.Add(parentNode); } IOrderedEnumerable<IGorgonVirtualDirectory> directories = directory.Directories.OrderBy(item => item.Name); IEnumerable<IGorgonVirtualFile> files = directory.Files.OrderBy(item => item.Name).Where(item => item.Extension != ".gorSprite" && item.Extension != ".gal"); foreach (IGorgonVirtualDirectory subDirectory in directories) { var directoryNode = new TreeNode(subDirectory.Name) { Name = subDirectory.FullPath, Tag = subDirectory }; if (subDirectory.Name != "ZipFile") { directoryNode.SelectedImageIndex = directoryNode.ImageIndex = 0; } else { directoryNode.SelectedImageIndex = directoryNode.ImageIndex = 2; } if ((subDirectory.Directories.Count > 0) || (subDirectory.Files.Count(item => item.Extension != ".gorSprite" && item.Extension != ".gal") > 0)) { directoryNode.Nodes.Add(new TreeNode("This is a dummy node.")); } parentNode.Nodes.Add(directoryNode); } foreach (IGorgonVirtualFile file in files) { if (file.Extension == ".gorSprite") { continue; } var fileNode = new TreeNode(file.Name) { Name = file.FullPath, Tag = file }; fileNode.SelectedImageIndex = fileNode.ImageIndex = 1; parentNode.Nodes.Add(fileNode); } parentNode.Expand(); } finally { treeFileSystem.EndUpdate(); treeFileSystem.BeforeExpand += TreeFileSystem_BeforeExpand; } } protected override void OnFormClosing(FormClosingEventArgs e) { base.OnFormClosing(e); try { if (_picture != null) { _picture.Dispose(); _picture = null; } if (_image != null) { _image.Dispose(); _image = null; } if (_textDisplay != null) { _textDisplay.Dispose(); _textDisplay = null; } if (_textFont == null) { return; } _textFont.Dispose(); _textFont = null; } catch (Exception ex) { ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), Program.Log); } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); try { _picture = new PictureBox { Name = "pictureImage" }; _textDisplay = new TextBox { Name = "textDisplay" }; _textFont = new Font("Consolas", 10.0f, FontStyle.Regular, GraphicsUnit.Point); _textDisplay.Font = _textFont; _instructions = new Label { Name = "labelInstructions", Text = "Double click on a file node in the tree to display it.", AutoSize = false, TextAlign = ContentAlignment.MiddleCenter, Dock = DockStyle.Fill, Font = Font }; splitFileSystem.Panel2.Controls.Add(_instructions); LoadZipFileSystemProvider(); _fileSystem.Mount(Program.GetResourcePath(@"VFSRoot\")); _fileSystem.Mount(Program.GetResourcePath("VFSRoot.zip"), "/ZipFile"); FillTree(null); } catch (Exception ex) { ex.Catch(_ => GorgonDialogs.ErrorBox(this, _), Program.Log); GorgonApplication.Quit(); } } #endregion #region Constructor/Destructor. public FormMain() => InitializeComponent(); #endregion }
[ "public", "partial", "class", "FormMain", ":", "Form", "{", "region", " Variables.", "private", "GorgonFileSystem", "_fileSystem", ";", "private", "PictureBox", "_picture", ";", "private", "Image", "_image", ";", "private", "TextBox", "_textDisplay", ";", "private", "Font", "_textFont", ";", "private", "Label", "_instructions", ";", "endregion", "region", " Methods.", "private", "void", "TreeFileSystem_NodeMouseDoubleClick", "(", "object", "sender", ",", "TreeNodeMouseClickEventArgs", "e", ")", "{", "if", "(", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "Count", ">", "0", ")", "{", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "RemoveAt", "(", "0", ")", ";", "}", "try", "{", "if", "(", "!", "(", "e", ".", "Node", "?", ".", "Tag", "is", "IGorgonVirtualFile", ")", ")", "{", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "Add", "(", "_instructions", ")", ";", "return", ";", "}", "_picture", ".", "Image", "=", "null", ";", "_textDisplay", ".", "Text", "=", "string", ".", "Empty", ";", "var", "file", "=", "(", "IGorgonVirtualFile", ")", "e", ".", "Node", ".", "Tag", ";", "using", "(", "Stream", "fileStream", "=", "file", ".", "OpenStream", "(", ")", ")", "{", "switch", "(", "file", ".", "Extension", ".", "ToLower", "(", ")", ")", "{", "case", "\"", ".jpg", "\"", ":", "case", "\"", ".jpeg", "\"", ":", "case", "\"", ".bmp", "\"", ":", "case", "\"", ".png", "\"", ":", "if", "(", "_image", "!=", "null", ")", "{", "_image", ".", "Dispose", "(", ")", ";", "_image", "=", "null", ";", "}", "_image", "=", "Image", ".", "FromStream", "(", "fileStream", ")", ";", "_picture", ".", "Image", "=", "_image", ";", "_picture", ".", "SizeMode", "=", "PictureBoxSizeMode", ".", "Zoom", ";", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "Add", "(", "_picture", ")", ";", "_picture", ".", "Dock", "=", "DockStyle", ".", "Fill", ";", "break", ";", "default", ":", "byte", "[", "]", "textData", "=", "new", "byte", "[", "fileStream", ".", "Length", "]", ";", "fileStream", ".", "Read", "(", "textData", ",", "0", ",", "textData", ".", "Length", ")", ";", "_textDisplay", ".", "Text", "=", "Encoding", ".", "UTF8", ".", "GetString", "(", "textData", ")", ";", "_textDisplay", ".", "Multiline", "=", "true", ";", "_textDisplay", ".", "ReadOnly", "=", "true", ";", "_textDisplay", ".", "ScrollBars", "=", "ScrollBars", ".", "Both", ";", "_textDisplay", ".", "Dock", "=", "DockStyle", ".", "Fill", ";", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "Add", "(", "_textDisplay", ")", ";", "break", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "Catch", "(", "_", "=>", "GorgonDialogs", ".", "ErrorBox", "(", "this", ",", "_", ")", ",", "Program", ".", "Log", ")", ";", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "Add", "(", "_instructions", ")", ";", "}", "}", "private", "void", "TreeFileSystem_BeforeExpand", "(", "object", "sender", ",", "TreeViewCancelEventArgs", "e", ")", "{", "try", "{", "if", "(", "!", "(", "e", ".", "Node", ".", "Tag", "is", "IGorgonVirtualDirectory", "directory", ")", ")", "{", "e", ".", "Cancel", "=", "true", ";", "return", ";", "}", "FillTree", "(", "directory", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "Catch", "(", "_", "=>", "GorgonDialogs", ".", "ErrorBox", "(", "this", ",", "_", ")", ",", "Program", ".", "Log", ")", ";", "}", "}", "private", "void", "TreeFileSystem_BeforeCollapse", "(", "object", "sender", ",", "TreeViewCancelEventArgs", "e", ")", "{", "var", "directory", "=", "e", ".", "Node", ".", "Tag", "as", "IGorgonVirtualDirectory", ";", "try", "{", "if", "(", "directory", "==", "_fileSystem", ".", "RootDirectory", ")", "{", "e", ".", "Cancel", "=", "true", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "Catch", "(", "_", "=>", "GorgonDialogs", ".", "ErrorBox", "(", "this", ",", "_", ")", ",", "Program", ".", "Log", ")", ";", "}", "}", "private", "void", "LoadZipFileSystemProvider", "(", ")", "{", "const", "string", "zipProviderPlugInName", "=", "\"", "Gorgon.IO.Zip.ZipProvider", "\"", ";", "using", "(", "var", "pluginAssemblies", "=", "new", "GorgonMefPlugInCache", "(", "Program", ".", "Log", ")", ")", "{", "pluginAssemblies", ".", "LoadPlugInAssemblies", "(", "Program", ".", "PlugInPath", ",", "\"", "Gorgon.FileSystem.Zip.DLL", "\"", ")", ";", "var", "providerFactory", "=", "new", "GorgonFileSystemProviderFactory", "(", "new", "GorgonMefPlugInService", "(", "pluginAssemblies", ")", ",", "Program", ".", "Log", ")", ";", "_fileSystem", "=", "new", "GorgonFileSystem", "(", "providerFactory", ".", "CreateProvider", "(", "zipProviderPlugInName", ")", ",", "Program", ".", "Log", ")", ";", "}", "}", "private", "void", "FillTree", "(", "IGorgonVirtualDirectory", "directory", ")", "{", "TreeNodeCollection", "nodes", ";", "TreeNode", "parentNode", ";", "if", "(", "directory", "==", "null", ")", "{", "directory", "=", "_fileSystem", ".", "RootDirectory", ";", "nodes", "=", "treeFileSystem", ".", "Nodes", ";", "parentNode", "=", "new", "TreeNode", "(", "\"", "/", "\"", ")", "{", "Name", "=", "\"", "/", "\"", "}", ";", "parentNode", ".", "SelectedImageIndex", "=", "parentNode", ".", "ImageIndex", "=", "0", ";", "}", "else", "{", "TreeNode", "[", "]", "searchNodes", "=", "treeFileSystem", ".", "Nodes", ".", "Find", "(", "directory", ".", "FullPath", ",", "true", ")", ";", "if", "(", "searchNodes", ".", "Length", ">", "0", ")", "{", "parentNode", "=", "searchNodes", "[", "0", "]", ";", "nodes", "=", "parentNode", ".", "Nodes", ";", "}", "else", "{", "GorgonDialogs", ".", "ErrorBox", "(", "this", ",", "\"", "Could not find the virtual directory '", "\"", "+", "directory", ".", "FullPath", "+", "\"", "'", "\"", ")", ";", "return", ";", "}", "}", "parentNode", ".", "Tag", "=", "directory", ";", "treeFileSystem", ".", "BeforeExpand", "-=", "TreeFileSystem_BeforeExpand", ";", "try", "{", "treeFileSystem", ".", "BeginUpdate", "(", ")", ";", "nodes", ".", "Clear", "(", ")", ";", "if", "(", "parentNode", ".", "Tag", "==", "_fileSystem", ".", "RootDirectory", ")", "{", "nodes", ".", "Add", "(", "parentNode", ")", ";", "}", "IOrderedEnumerable", "<", "IGorgonVirtualDirectory", ">", "directories", "=", "directory", ".", "Directories", ".", "OrderBy", "(", "item", "=>", "item", ".", "Name", ")", ";", "IEnumerable", "<", "IGorgonVirtualFile", ">", "files", "=", "directory", ".", "Files", ".", "OrderBy", "(", "item", "=>", "item", ".", "Name", ")", ".", "Where", "(", "item", "=>", "item", ".", "Extension", "!=", "\"", ".gorSprite", "\"", "&&", "item", ".", "Extension", "!=", "\"", ".gal", "\"", ")", ";", "foreach", "(", "IGorgonVirtualDirectory", "subDirectory", "in", "directories", ")", "{", "var", "directoryNode", "=", "new", "TreeNode", "(", "subDirectory", ".", "Name", ")", "{", "Name", "=", "subDirectory", ".", "FullPath", ",", "Tag", "=", "subDirectory", "}", ";", "if", "(", "subDirectory", ".", "Name", "!=", "\"", "ZipFile", "\"", ")", "{", "directoryNode", ".", "SelectedImageIndex", "=", "directoryNode", ".", "ImageIndex", "=", "0", ";", "}", "else", "{", "directoryNode", ".", "SelectedImageIndex", "=", "directoryNode", ".", "ImageIndex", "=", "2", ";", "}", "if", "(", "(", "subDirectory", ".", "Directories", ".", "Count", ">", "0", ")", "||", "(", "subDirectory", ".", "Files", ".", "Count", "(", "item", "=>", "item", ".", "Extension", "!=", "\"", ".gorSprite", "\"", "&&", "item", ".", "Extension", "!=", "\"", ".gal", "\"", ")", ">", "0", ")", ")", "{", "directoryNode", ".", "Nodes", ".", "Add", "(", "new", "TreeNode", "(", "\"", "This is a dummy node.", "\"", ")", ")", ";", "}", "parentNode", ".", "Nodes", ".", "Add", "(", "directoryNode", ")", ";", "}", "foreach", "(", "IGorgonVirtualFile", "file", "in", "files", ")", "{", "if", "(", "file", ".", "Extension", "==", "\"", ".gorSprite", "\"", ")", "{", "continue", ";", "}", "var", "fileNode", "=", "new", "TreeNode", "(", "file", ".", "Name", ")", "{", "Name", "=", "file", ".", "FullPath", ",", "Tag", "=", "file", "}", ";", "fileNode", ".", "SelectedImageIndex", "=", "fileNode", ".", "ImageIndex", "=", "1", ";", "parentNode", ".", "Nodes", ".", "Add", "(", "fileNode", ")", ";", "}", "parentNode", ".", "Expand", "(", ")", ";", "}", "finally", "{", "treeFileSystem", ".", "EndUpdate", "(", ")", ";", "treeFileSystem", ".", "BeforeExpand", "+=", "TreeFileSystem_BeforeExpand", ";", "}", "}", "protected", "override", "void", "OnFormClosing", "(", "FormClosingEventArgs", "e", ")", "{", "base", ".", "OnFormClosing", "(", "e", ")", ";", "try", "{", "if", "(", "_picture", "!=", "null", ")", "{", "_picture", ".", "Dispose", "(", ")", ";", "_picture", "=", "null", ";", "}", "if", "(", "_image", "!=", "null", ")", "{", "_image", ".", "Dispose", "(", ")", ";", "_image", "=", "null", ";", "}", "if", "(", "_textDisplay", "!=", "null", ")", "{", "_textDisplay", ".", "Dispose", "(", ")", ";", "_textDisplay", "=", "null", ";", "}", "if", "(", "_textFont", "==", "null", ")", "{", "return", ";", "}", "_textFont", ".", "Dispose", "(", ")", ";", "_textFont", "=", "null", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "Catch", "(", "_", "=>", "GorgonDialogs", ".", "ErrorBox", "(", "this", ",", "_", ")", ",", "Program", ".", "Log", ")", ";", "}", "}", "protected", "override", "void", "OnLoad", "(", "EventArgs", "e", ")", "{", "base", ".", "OnLoad", "(", "e", ")", ";", "try", "{", "_picture", "=", "new", "PictureBox", "{", "Name", "=", "\"", "pictureImage", "\"", "}", ";", "_textDisplay", "=", "new", "TextBox", "{", "Name", "=", "\"", "textDisplay", "\"", "}", ";", "_textFont", "=", "new", "Font", "(", "\"", "Consolas", "\"", ",", "10.0f", ",", "FontStyle", ".", "Regular", ",", "GraphicsUnit", ".", "Point", ")", ";", "_textDisplay", ".", "Font", "=", "_textFont", ";", "_instructions", "=", "new", "Label", "{", "Name", "=", "\"", "labelInstructions", "\"", ",", "Text", "=", "\"", "Double click on a file node in the tree to display it.", "\"", ",", "AutoSize", "=", "false", ",", "TextAlign", "=", "ContentAlignment", ".", "MiddleCenter", ",", "Dock", "=", "DockStyle", ".", "Fill", ",", "Font", "=", "Font", "}", ";", "splitFileSystem", ".", "Panel2", ".", "Controls", ".", "Add", "(", "_instructions", ")", ";", "LoadZipFileSystemProvider", "(", ")", ";", "_fileSystem", ".", "Mount", "(", "Program", ".", "GetResourcePath", "(", "@\"VFSRoot\\\"", ")", ")", ";", "_fileSystem", ".", "Mount", "(", "Program", ".", "GetResourcePath", "(", "\"", "VFSRoot.zip", "\"", ")", ",", "\"", "/ZipFile", "\"", ")", ";", "FillTree", "(", "null", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "Catch", "(", "_", "=>", "GorgonDialogs", ".", "ErrorBox", "(", "this", ",", "_", ")", ",", "Program", ".", "Log", ")", ";", "GorgonApplication", ".", "Quit", "(", ")", ";", "}", "}", "endregion", "region", " Constructor/Destructor.", "public", "FormMain", "(", ")", "=>", "InitializeComponent", "(", ")", ";", "endregion", "}" ]
Main application interface.
[ "Main", "application", "interface", "." ]
[ "// Our file system.", "// Our picture box.", "// Loaded image.", "// Loaded text/binary info.", "// Textbox font.", "// Instructions label.", "/// <summary>", "/// Handles the NodeMouseDoubleClick event of the treeFileSystem control.", "/// </summary>", "/// <param name=\"sender\">The source of the event.</param>", "/// <param name=\"e\">The <see cref=\"TreeNodeMouseClickEventArgs\" /> instance containing the event data.</param>", "// Here we load the image from the file system.", "// Note that we don't care if it's from the zip file", "// or the folder. It's all the same to us.", "// If it's a picture, then load it.", "// Add to control.", "// Get data in the file stream.", "// Convert to a string.", "/// <summary>", "/// Handles the BeforeExpand event of the treeFileSystem control.", "/// </summary>", "/// <param name=\"sender\">The source of the event.</param>", "/// <param name=\"e\">The <see cref=\"TreeViewCancelEventArgs\" /> instance containing the event data.</param>", "/// <summary>", "/// Handles the BeforeCollapse event of the treeFileSystem control.", "/// </summary>", "/// <param name=\"sender\">The source of the event.</param>", "/// <param name=\"e\">The <see cref=\"TreeViewCancelEventArgs\" /> instance containing the event data.</param>", "// Do not expand or collapse", "/// <summary>", "/// Function to load the zip file system provider.", "/// </summary>", "// Name of our zip provider plugin.", "// We can load the objects we need and discard the plugin system after.", "// This works because we keep the references to the objects that our ", "// plugin creates, even after the plugin is gone.", "/// <summary>", "/// Function to fill the file system tree view.", "/// </summary>", "/// <param name=\"directory\">Parent directory to fill, or <b>null</b> to fill the root directory.</param>", "// Set root node.", "// Find the node with the directory.", "// Turn off the expand event.", "// Clean up the tree node.", "// Add the root node if necessary.", "// Enumerate the data. For the purposed of this example, we will filter out known binary files from our file system.\t\t\t\t", "// Get directories.", "// Put a special icon on the zip file so we have a visual representation", "// of where it is in our VFS.", "// The VFS does not care if the data is in a zip file or folder, and Gorgon", "// does very little to differentiate it. After all, the whole point of", "// have a unified file system is to abstract away the differences.", "// Add a dummy node if there are files or sub directories.", "// Get files.", "/// <summary>", "/// Raises the <see cref=\"E:System.Windows.Forms.Form.FormClosing\" /> event.", "/// </summary>", "/// <param name=\"e\">A <see cref=\"T:System.Windows.Forms.FormClosingEventArgs\" /> that contains the event data.</param>", "/// <summary>", "/// Raises the <see cref=\"E:System.Windows.Forms.Form.Load\" /> event.", "/// </summary>", "/// <param name=\"e\">An <see cref=\"T:System.EventArgs\" /> that contains the event data.</param>", "// Picture box.", "// Text display.", "// Add the instructions.", "// Get the zip file provider.", "// Mount the physical file system directory.", "// Mount the zip file into a sub directory.", "// Fill the root of the tree.", "/// <summary>", "/// Initializes a new instance of the <see cref=\"FormMain\" /> class.", "/// </summary>" ]
[ { "param": "Form", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Form", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "In this example we will mount two different data sources into a virtual file system.\n\nThe file system is able to mount different data sources into the same file system which will allow for access\nto multiple sets of files as a unified file system. Here we mount a physical file system folder as the root\nof the file system and a zip file as a virtual subdirectory in the virtual file system. Accessing these\nfiles is just a matter of getting the file entry and loading the data as a stream.\n\nYou may mount multiple data sources into the same virtual directory and the\nfiles from each data source will be merged. However, the caveat here is the order in which the file systems\nare mounted. If 2 or more data sources contain the same file names, then the data source that was mounted\nlast will take precedence over the previous file systems. For example, if D:\\directory\\filename.txt exists in\nthe virtual root as \"/filename.txt\" and we mount a zip file that has filename.txt in the root of the zip file,\nthen when we open filename.txt from the virtual file system we will be opening the file from the zip file.\n\nWe begin the example by loading the file system provider for zip files, and then mounting a physical folder\nand then the zip file into a virtual subdirectory. From there we enumerate the files and virtual sub directories\ninto the tree view. Opening a file can be done either from the file entry as shown in the example, or it can be\nopened via the file system interface (allowing the user to pass a full path to the file). Files can be returned\nas a stream (OpenStream) or an array of bytes (ReadFile). Please note that writing to these file systems is not\nsupported and can only be done when a write directory is set. This will be covered in another example.", "docstring_tokens": [ "In", "this", "example", "we", "will", "mount", "two", "different", "data", "sources", "into", "a", "virtual", "file", "system", ".", "The", "file", "system", "is", "able", "to", "mount", "different", "data", "sources", "into", "the", "same", "file", "system", "which", "will", "allow", "for", "access", "to", "multiple", "sets", "of", "files", "as", "a", "unified", "file", "system", ".", "Here", "we", "mount", "a", "physical", "file", "system", "folder", "as", "the", "root", "of", "the", "file", "system", "and", "a", "zip", "file", "as", "a", "virtual", "subdirectory", "in", "the", "virtual", "file", "system", ".", "Accessing", "these", "files", "is", "just", "a", "matter", "of", "getting", "the", "file", "entry", "and", "loading", "the", "data", "as", "a", "stream", ".", "You", "may", "mount", "multiple", "data", "sources", "into", "the", "same", "virtual", "directory", "and", "the", "files", "from", "each", "data", "source", "will", "be", "merged", ".", "However", "the", "caveat", "here", "is", "the", "order", "in", "which", "the", "file", "systems", "are", "mounted", ".", "If", "2", "or", "more", "data", "sources", "contain", "the", "same", "file", "names", "then", "the", "data", "source", "that", "was", "mounted", "last", "will", "take", "precedence", "over", "the", "previous", "file", "systems", ".", "For", "example", "if", "D", ":", "\\", "directory", "\\", "filename", ".", "txt", "exists", "in", "the", "virtual", "root", "as", "\"", "/", "filename", ".", "txt", "\"", "and", "we", "mount", "a", "zip", "file", "that", "has", "filename", ".", "txt", "in", "the", "root", "of", "the", "zip", "file", "then", "when", "we", "open", "filename", ".", "txt", "from", "the", "virtual", "file", "system", "we", "will", "be", "opening", "the", "file", "from", "the", "zip", "file", ".", "We", "begin", "the", "example", "by", "loading", "the", "file", "system", "provider", "for", "zip", "files", "and", "then", "mounting", "a", "physical", "folder", "and", "then", "the", "zip", "file", "into", "a", "virtual", "subdirectory", ".", "From", "there", "we", "enumerate", "the", "files", "and", "virtual", "sub", "directories", "into", "the", "tree", "view", ".", "Opening", "a", "file", "can", "be", "done", "either", "from", "the", "file", "entry", "as", "shown", "in", "the", "example", "or", "it", "can", "be", "opened", "via", "the", "file", "system", "interface", "(", "allowing", "the", "user", "to", "pass", "a", "full", "path", "to", "the", "file", ")", ".", "Files", "can", "be", "returned", "as", "a", "stream", "(", "OpenStream", ")", "or", "an", "array", "of", "bytes", "(", "ReadFile", ")", ".", "Please", "note", "that", "writing", "to", "these", "file", "systems", "is", "not", "supported", "and", "can", "only", "be", "done", "when", "a", "write", "directory", "is", "set", ".", "This", "will", "be", "covered", "in", "another", "example", "." ] } ] }
false
20
1,733
444
85f5aee8f695a0e014abfa3895d8dd0f701558eb
ww362034710/Gannt
gannt/lib/Grid/column/CheckColumn.js
[ "MIT" ]
JavaScript
CheckColumn
/** * A column that displays a checkbox in the cell. The value of the backing field is toggled by the checkbox. * * This column uses a {@link Core.widget.Checkbox checkbox} as its editor, and it is not intended to be changed. * * @extends Grid/column/WidgetColumn * * @example * new Grid({ * appendTo : document.body, * * columns : [ * { type: 'check', field: 'allow' } * ] * }); * * @classType check * @externalexample column/CheckColumn.js */
A column that displays a checkbox in the cell. The value of the backing field is toggled by the checkbox. This column uses a Core.widget.Checkbox checkbox as its editor, and it is not intended to be changed. @example new Grid({ appendTo : document.body.
[ "A", "column", "that", "displays", "a", "checkbox", "in", "the", "cell", ".", "The", "value", "of", "the", "backing", "field", "is", "toggled", "by", "the", "checkbox", ".", "This", "column", "uses", "a", "Core", ".", "widget", ".", "Checkbox", "checkbox", "as", "its", "editor", "and", "it", "is", "not", "intended", "to", "be", "changed", ".", "@example", "new", "Grid", "(", "{", "appendTo", ":", "document", ".", "body", "." ]
class CheckColumn extends WidgetColumn { //region Config static get type() { return 'check'; } static get fields() { return ['checkCls', 'showCheckAll']; } static get defaults() { return { align : 'center', /** * CSS class name to add to checkbox * @config {String} * @category Rendering */ checkCls : null, /** * True to show a checkbox in the column header to be able to select/deselect all rows * @config {Boolean} */ showCheckAll : false, widgets : [{ type : 'checkbox', valueProperty : 'checked' }] }; } constructor(config, store) { super(...arguments); this.internalCellCls = 'b-check-cell'; if (this.grid) { this.grid.on('destroy', () => this.headerCheckbox && this.headerCheckbox.destroy()); } } headerRenderer({ headerElement, column }) { const me = this; headerElement.classList.add('b-check-header'); if (column.showCheckAll) { headerElement.classList.add('b-check-header-with-checkbox'); if (column.headerCheckbox) { column.headerCheckbox.destroy(); } column.headerCheckbox = new Checkbox({ appendTo : headerElement, owner : me.grid, listeners : { change : ({ checked }) => { /** * Fired when the header checkbox is clicked to toggle its checked status. * @event toggleAll * @param {Grid.column.Column} source This Column * @param {Boolean} checked The checked status of the header checkbox. */ column.trigger('toggleAll', { checked }); } } }); } else { return column.text; } } //endregion renderer({ value, isExport }) { if (isExport) { return value == null ? '' : value; } else { super.renderer(...arguments); } } //region Widget rendering onBeforeWidgetCreate(widgetCfg, event) { widgetCfg.cls = this.checkCls; } onAfterWidgetCreate(widget, event) { event.cellElement.widget = widget; widget.on({ beforeChange : 'onBeforeCheckboxChange', change : 'onCheckboxChange', thisObj : this }); } onBeforeWidgetSetValue(widget) { widget.record = widget.cellInfo.record; this.isInitialSet = true; } onAfterWidgetSetValue(widget) { this.isInitialSet = false; } //endregion //region Events onBeforeCheckboxChange({ source, checked }) { if (!this.isInitialSet) { /** * Fired when a cell is clicked to toggle its checked status. Returning `false` will prevent status change. * @event beforeToggle * @param {Grid.column.Column} source This Column * @param {Core.data.Model} record The record for the row containing the cell. * @param {Boolean} checked The new checked status of the cell. */ return this.trigger('beforeToggle', { record : source.cellInfo.record, checked }); } } onCheckboxChange({ source, checked }) { if (!this.isInitialSet) { const record = source.cellInfo.record, field = this.field; if (field) { const setterName = `set${StringHelper.capitalize(field)}`; if (record[setterName]) { record[setterName](checked); } else { record.set(field, checked); } } /** * Fired when a cell is clicked to toggle its checked status. * @event toggle * @param {Grid.column.Column} source This Column * @param {Core.data.Model} record The record for the row containing the cell. * @param {Boolean} checked The new checked status of the cell. */ this.trigger('toggle', { record, checked }); } } //endregion }
[ "class", "CheckColumn", "extends", "WidgetColumn", "{", "static", "get", "type", "(", ")", "{", "return", "'check'", ";", "}", "static", "get", "fields", "(", ")", "{", "return", "[", "'checkCls'", ",", "'showCheckAll'", "]", ";", "}", "static", "get", "defaults", "(", ")", "{", "return", "{", "align", ":", "'center'", ",", "checkCls", ":", "null", ",", "showCheckAll", ":", "false", ",", "widgets", ":", "[", "{", "type", ":", "'checkbox'", ",", "valueProperty", ":", "'checked'", "}", "]", "}", ";", "}", "constructor", "(", "config", ",", "store", ")", "{", "super", "(", "...", "arguments", ")", ";", "this", ".", "internalCellCls", "=", "'b-check-cell'", ";", "if", "(", "this", ".", "grid", ")", "{", "this", ".", "grid", ".", "on", "(", "'destroy'", ",", "(", ")", "=>", "this", ".", "headerCheckbox", "&&", "this", ".", "headerCheckbox", ".", "destroy", "(", ")", ")", ";", "}", "}", "headerRenderer", "(", "{", "headerElement", ",", "column", "}", ")", "{", "const", "me", "=", "this", ";", "headerElement", ".", "classList", ".", "add", "(", "'b-check-header'", ")", ";", "if", "(", "column", ".", "showCheckAll", ")", "{", "headerElement", ".", "classList", ".", "add", "(", "'b-check-header-with-checkbox'", ")", ";", "if", "(", "column", ".", "headerCheckbox", ")", "{", "column", ".", "headerCheckbox", ".", "destroy", "(", ")", ";", "}", "column", ".", "headerCheckbox", "=", "new", "Checkbox", "(", "{", "appendTo", ":", "headerElement", ",", "owner", ":", "me", ".", "grid", ",", "listeners", ":", "{", "change", ":", "(", "{", "checked", "}", ")", "=>", "{", "column", ".", "trigger", "(", "'toggleAll'", ",", "{", "checked", "}", ")", ";", "}", "}", "}", ")", ";", "}", "else", "{", "return", "column", ".", "text", ";", "}", "}", "renderer", "(", "{", "value", ",", "isExport", "}", ")", "{", "if", "(", "isExport", ")", "{", "return", "value", "==", "null", "?", "''", ":", "value", ";", "}", "else", "{", "super", ".", "renderer", "(", "...", "arguments", ")", ";", "}", "}", "onBeforeWidgetCreate", "(", "widgetCfg", ",", "event", ")", "{", "widgetCfg", ".", "cls", "=", "this", ".", "checkCls", ";", "}", "onAfterWidgetCreate", "(", "widget", ",", "event", ")", "{", "event", ".", "cellElement", ".", "widget", "=", "widget", ";", "widget", ".", "on", "(", "{", "beforeChange", ":", "'onBeforeCheckboxChange'", ",", "change", ":", "'onCheckboxChange'", ",", "thisObj", ":", "this", "}", ")", ";", "}", "onBeforeWidgetSetValue", "(", "widget", ")", "{", "widget", ".", "record", "=", "widget", ".", "cellInfo", ".", "record", ";", "this", ".", "isInitialSet", "=", "true", ";", "}", "onAfterWidgetSetValue", "(", "widget", ")", "{", "this", ".", "isInitialSet", "=", "false", ";", "}", "onBeforeCheckboxChange", "(", "{", "source", ",", "checked", "}", ")", "{", "if", "(", "!", "this", ".", "isInitialSet", ")", "{", "return", "this", ".", "trigger", "(", "'beforeToggle'", ",", "{", "record", ":", "source", ".", "cellInfo", ".", "record", ",", "checked", "}", ")", ";", "}", "}", "onCheckboxChange", "(", "{", "source", ",", "checked", "}", ")", "{", "if", "(", "!", "this", ".", "isInitialSet", ")", "{", "const", "record", "=", "source", ".", "cellInfo", ".", "record", ",", "field", "=", "this", ".", "field", ";", "if", "(", "field", ")", "{", "const", "setterName", "=", "`", "${", "StringHelper", ".", "capitalize", "(", "field", ")", "}", "`", ";", "if", "(", "record", "[", "setterName", "]", ")", "{", "record", "[", "setterName", "]", "(", "checked", ")", ";", "}", "else", "{", "record", ".", "set", "(", "field", ",", "checked", ")", ";", "}", "}", "this", ".", "trigger", "(", "'toggle'", ",", "{", "record", ",", "checked", "}", ")", ";", "}", "}", "}" ]
A column that displays a checkbox in the cell.
[ "A", "column", "that", "displays", "a", "checkbox", "in", "the", "cell", "." ]
[ "//region Config", "/**\n * CSS class name to add to checkbox\n * @config {String}\n * @category Rendering\n */", "/**\n * True to show a checkbox in the column header to be able to select/deselect all rows\n * @config {Boolean}\n */", "/**\n * Fired when the header checkbox is clicked to toggle its checked status.\n * @event toggleAll\n * @param {Grid.column.Column} source This Column\n * @param {Boolean} checked The checked status of the header checkbox.\n */", "//endregion", "//region Widget rendering", "//endregion", "//region Events", "/**\n * Fired when a cell is clicked to toggle its checked status. Returning `false` will prevent status change.\n * @event beforeToggle\n * @param {Grid.column.Column} source This Column\n * @param {Core.data.Model} record The record for the row containing the cell.\n * @param {Boolean} checked The new checked status of the cell.\n */", "/**\n * Fired when a cell is clicked to toggle its checked status.\n * @event toggle\n * @param {Grid.column.Column} source This Column\n * @param {Core.data.Model} record The record for the row containing the cell.\n * @param {Boolean} checked The new checked status of the cell.\n */", "//endregion" ]
[ { "param": "WidgetColumn", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "WidgetColumn", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
21
877
123
d840e30e293d6d1d13bffcd1491950a6ab4b3d75
AnomalousMedical/Engine
Engine/Plugin/PluginManager.cs
[ "MIT" ]
C#
PluginManager
/// <summary> /// This class loads and unloads the various plugins for the system. /// It will also maintain the di scope using a builder you supply or one it creates. /// Any instance of this class will be added to the builder automatically, in addition /// they will maintain the main app container and globlal lifetime scope. To shut down /// these containers call the Dispose function on the PluginManager. This will initiate /// cleanup correctly. If you create a PluginManager you are responsible to call Dispose on it. /// </summary>
This class loads and unloads the various plugins for the system. It will also maintain the di scope using a builder you supply or one it creates. Any instance of this class will be added to the builder automatically, in addition they will maintain the main app container and globlal lifetime scope. To shut down these containers call the Dispose function on the PluginManager. This will initiate cleanup correctly. If you create a PluginManager you are responsible to call Dispose on it.
[ "This", "class", "loads", "and", "unloads", "the", "various", "plugins", "for", "the", "system", ".", "It", "will", "also", "maintain", "the", "di", "scope", "using", "a", "builder", "you", "supply", "or", "one", "it", "creates", ".", "Any", "instance", "of", "this", "class", "will", "be", "added", "to", "the", "builder", "automatically", "in", "addition", "they", "will", "maintain", "the", "main", "app", "container", "and", "globlal", "lifetime", "scope", ".", "To", "shut", "down", "these", "containers", "call", "the", "Dispose", "function", "on", "the", "PluginManager", ".", "This", "will", "initiate", "cleanup", "correctly", ".", "If", "you", "create", "a", "PluginManager", "you", "are", "responsible", "to", "call", "Dispose", "on", "it", "." ]
public class PluginManager : IDisposable { #region Static private static PluginManager instance; public static PluginManager Instance { get { return instance; } } #endregion #region Fields private List<PluginInterface> loadedPlugins = new List<PluginInterface>(); private List<AddSimElementCommand> addSimElementCommands = new List<AddSimElementCommand>(); private List<AddSimElementManagerCommand> addElementManagerCommands = new List<AddSimElementManagerCommand>(); private RendererPlugin rendererPlugin = null; private List<Assembly> pluginAssemblies = new List<Assembly>(); private ResourceManager prototypeResourceManager = new ResourceManager(); private List<DebugInterface> debugInterfaces; private ConfigFile configFile; private String pluginDirectory = null; private VirtualFileSystem virtualFileSystem; private Dictionary<String, Type> typeCache = new Dictionary<string, Type>(); private RenamedTypeMap renamedTypeMap = null; private IServiceCollection serviceCollection; private ServiceProvider serviceProvider; private IServiceScope globalScope; private bool shuttingDown = false; #endregion Fields #region Events public ConfigureDefaultWindow OnConfigureDefaultWindow; #endregion Events #region Constructors public PluginManager(ConfigFile configFile, IServiceCollection serviceCollection) { this.serviceCollection = serviceCollection; serviceCollection.TryAddSingleton<PluginManager>(this); if (instance == null) { this.configFile = configFile; instance = this; instance.addPlugin(new BehaviorPluginInterface()); virtualFileSystem = new VirtualFileSystem(); } else { throw new InvalidPluginException("Can only call the constructor for the PluginManager one time"); } } #endregion #region Functions public void Dispose() { if (shuttingDown) { } else { shuttingDown = true; globalScope.Dispose(); serviceProvider.Dispose(); virtualFileSystem.Dispose(); for (int i = loadedPlugins.Count - 1; i >= 0; --i) { loadedPlugins[i].Dispose(); } loadedPlugins.Clear(); ThreadManager.cancelAll(); } } public void initializePlugins() { foreach (Assembly assembly in pluginAssemblies) { PluginEntryPointAttribute[] attributes = (PluginEntryPointAttribute[])assembly.GetCustomAttributes(typeof(PluginEntryPointAttribute)); if (attributes.Length > 0) { foreach (PluginEntryPointAttribute entryPointAttribute in attributes) { entryPointAttribute.createPluginInterfaces(this); } } else { throw new InvalidPluginException(String.Format("Cannot find PluginEntryPointAttribute in assembly {0}. Please add this property to the assembly.", assembly.FullName)); } } serviceProvider = serviceCollection.BuildServiceProvider(); globalScope = serviceProvider.CreateScope(); foreach (var plugin in loadedPlugins) { plugin.link(this); } } public void addPlugin(PluginInterface plugin) { Log.Default.sendMessage("Plugin {0} added.", LogLevel.Info, "Engine", plugin.Name); loadedPlugins.Add(plugin); plugin.initialize(this, serviceCollection); if (renamedTypeMap != null) { plugin.setupRenamedSaveableTypes(renamedTypeMap); } } internal Type findType(String assemblyQualifiedName) { Type type; if (!typeCache.TryGetValue(assemblyQualifiedName, out type)) { type = Type.GetType(assemblyQualifiedName, false); if (type == null) { String typeName = DefaultTypeFinder.GetTypeNameWithoutAssembly(assemblyQualifiedName); if (renamedTypeMap == null) { renamedTypeMap = new RenamedTypeMap(); foreach (var plugin in loadedPlugins) { plugin.setupRenamedSaveableTypes(renamedTypeMap); } } if (!renamedTypeMap.tryGetType(typeName, out type)) { Log.Warning("TypeSearch: Had to do slow search looking for type \'{0}\'. You should fix the source file searching for this type or add an entry to the renamed type maps for '{1}'", assemblyQualifiedName, typeName); foreach (Assembly assembly in pluginAssemblies) { type = assembly.GetType(typeName); if (type != null) { break; } } if (type == null) { foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { type = assembly.GetType(typeName); if (type != null) { break; } } } } if (type != null) { Log.Warning("TypeSearch: Replacement found for type \'{0}\'. Replacement type is \'{1}\'", assemblyQualifiedName, type.AssemblyQualifiedName); } else { Log.Warning("TypeSearch: Unable to find replacement for type \'{0}\'.", assemblyQualifiedName); } } typeCache.Add(assemblyQualifiedName, type); } return type; } public void addPluginAssembly(Assembly assembly) { pluginAssemblies.Add(assembly); } public PluginInterface getPlugin(String name) { foreach (PluginInterface plugin in loadedPlugins) { if (plugin.Name == name) { return plugin; } } return null; } public void setRendererPlugin(RendererPlugin plugin, out WindowInfo defaultWindow) { if (rendererPlugin == null) { rendererPlugin = plugin; Log.Default.sendMessage("Renderer plugin set to {0}.", LogLevel.Info, "Engine", plugin.Name); if (OnConfigureDefaultWindow != null) { OnConfigureDefaultWindow.Invoke(out defaultWindow); if (defaultWindow == null) { throw new InvalidPluginException("A custom window configure function was invoked, but it did not set the default window up correctly. The renderer cannot be initalized."); } } else { defaultWindow = new WindowInfo("Anomalous Engine", 640, 480); } } else { throw new InvalidPluginException("A second renderer plugin was added. It is only valid to specify one renderer plugin please correct this issue."); } } public void reconfigureDefaultWindow(out WindowInfo defaultWindow) { if (OnConfigureDefaultWindow != null) { OnConfigureDefaultWindow.Invoke(out defaultWindow); } else { defaultWindow = new WindowInfo("Anomalous Engine", 640, 480); } } public void addSubsystemResources(String name, ResourceListener subsystemListener) { prototypeResourceManager.addSubsystemResource(new SubsystemResources(name, subsystemListener)); } public void setPlatformInfo(UpdateTimer mainTimer, EventManager eventManager) { GlobalContextEventHandler.setEventManager(eventManager); foreach (PluginInterface plugin in loadedPlugins) { plugin.setPlatformInfo(mainTimer, eventManager); } mainTimer.addUpdateListener(new ThreadManagerUpdate()); } public void addCreateSimElementManagerCommand(AddSimElementManagerCommand command) { addElementManagerCommands.Add(command); } public IEnumerable<AddSimElementManagerCommand> getCreateSimElementManagerCommands() { return addElementManagerCommands; } public void addCreateSimElementCommand(AddSimElementCommand command) { addSimElementCommands.Add(command); } public IEnumerable<AddSimElementCommand> getCreateSimElementCommands() { return addSimElementCommands; } public List<CommandManager> createDebugCommands() { List<CommandManager> commands = new List<CommandManager>(); foreach (PluginInterface plugin in loadedPlugins) { plugin.createDebugCommands(commands); } return commands; } public ResourceManager createLiveResourceManager(String resourceNamespace) { return new ResourceManager(prototypeResourceManager, true) { Namespace = resourceNamespace }; } public ResourceManager createScratchResourceManager() { return new ResourceManager(prototypeResourceManager, false); } public ResourceManager createResourceManagerForListener(String customSubsystemName, ResourceListener listener) { ResourceManager resourceManager = new ResourceManager(); resourceManager.addSubsystemResource(new SubsystemResources(customSubsystemName, listener)); return resourceManager; } public IEnumerable<DebugInterface> DebugInterfaces { get { if (debugInterfaces == null) { debugInterfaces = new List<DebugInterface>(); foreach (PluginInterface plugin in loadedPlugins) { DebugInterface debug = plugin.getDebugInterface(); if (debug != null) { debugInterfaces.Add(debug); } } } return debugInterfaces; } } #endregion Functions #region Properties public RendererPlugin RendererPlugin { get { return rendererPlugin; } } public ConfigFile ConfigFile { get { return configFile; } } public String PluginDirectory { get { if (pluginDirectory == null) { String[] args = Environment.GetCommandLineArgs(); if (args.Length > 0) { pluginDirectory = Path.GetDirectoryName(args[0]); } } return pluginDirectory; } } public IServiceScope GlobalScope { get { return globalScope; } } #endregion Properties }
[ "public", "class", "PluginManager", ":", "IDisposable", "{", "region", " Static", "private", "static", "PluginManager", "instance", ";", "public", "static", "PluginManager", "Instance", "{", "get", "{", "return", "instance", ";", "}", "}", "endregion", "region", " Fields", "private", "List", "<", "PluginInterface", ">", "loadedPlugins", "=", "new", "List", "<", "PluginInterface", ">", "(", ")", ";", "private", "List", "<", "AddSimElementCommand", ">", "addSimElementCommands", "=", "new", "List", "<", "AddSimElementCommand", ">", "(", ")", ";", "private", "List", "<", "AddSimElementManagerCommand", ">", "addElementManagerCommands", "=", "new", "List", "<", "AddSimElementManagerCommand", ">", "(", ")", ";", "private", "RendererPlugin", "rendererPlugin", "=", "null", ";", "private", "List", "<", "Assembly", ">", "pluginAssemblies", "=", "new", "List", "<", "Assembly", ">", "(", ")", ";", "private", "ResourceManager", "prototypeResourceManager", "=", "new", "ResourceManager", "(", ")", ";", "private", "List", "<", "DebugInterface", ">", "debugInterfaces", ";", "private", "ConfigFile", "configFile", ";", "private", "String", "pluginDirectory", "=", "null", ";", "private", "VirtualFileSystem", "virtualFileSystem", ";", "private", "Dictionary", "<", "String", ",", "Type", ">", "typeCache", "=", "new", "Dictionary", "<", "string", ",", "Type", ">", "(", ")", ";", "private", "RenamedTypeMap", "renamedTypeMap", "=", "null", ";", "private", "IServiceCollection", "serviceCollection", ";", "private", "ServiceProvider", "serviceProvider", ";", "private", "IServiceScope", "globalScope", ";", "private", "bool", "shuttingDown", "=", "false", ";", "endregion", " Fields", "region", " Events", "public", "ConfigureDefaultWindow", "OnConfigureDefaultWindow", ";", "endregion", " Events", "region", " Constructors", "public", "PluginManager", "(", "ConfigFile", "configFile", ",", "IServiceCollection", "serviceCollection", ")", "{", "this", ".", "serviceCollection", "=", "serviceCollection", ";", "serviceCollection", ".", "TryAddSingleton", "<", "PluginManager", ">", "(", "this", ")", ";", "if", "(", "instance", "==", "null", ")", "{", "this", ".", "configFile", "=", "configFile", ";", "instance", "=", "this", ";", "instance", ".", "addPlugin", "(", "new", "BehaviorPluginInterface", "(", ")", ")", ";", "virtualFileSystem", "=", "new", "VirtualFileSystem", "(", ")", ";", "}", "else", "{", "throw", "new", "InvalidPluginException", "(", "\"", "Can only call the constructor for the PluginManager one time", "\"", ")", ";", "}", "}", "endregion", "region", " Functions", "public", "void", "Dispose", "(", ")", "{", "if", "(", "shuttingDown", ")", "{", "}", "else", "{", "shuttingDown", "=", "true", ";", "globalScope", ".", "Dispose", "(", ")", ";", "serviceProvider", ".", "Dispose", "(", ")", ";", "virtualFileSystem", ".", "Dispose", "(", ")", ";", "for", "(", "int", "i", "=", "loadedPlugins", ".", "Count", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "loadedPlugins", "[", "i", "]", ".", "Dispose", "(", ")", ";", "}", "loadedPlugins", ".", "Clear", "(", ")", ";", "ThreadManager", ".", "cancelAll", "(", ")", ";", "}", "}", "public", "void", "initializePlugins", "(", ")", "{", "foreach", "(", "Assembly", "assembly", "in", "pluginAssemblies", ")", "{", "PluginEntryPointAttribute", "[", "]", "attributes", "=", "(", "PluginEntryPointAttribute", "[", "]", ")", "assembly", ".", "GetCustomAttributes", "(", "typeof", "(", "PluginEntryPointAttribute", ")", ")", ";", "if", "(", "attributes", ".", "Length", ">", "0", ")", "{", "foreach", "(", "PluginEntryPointAttribute", "entryPointAttribute", "in", "attributes", ")", "{", "entryPointAttribute", ".", "createPluginInterfaces", "(", "this", ")", ";", "}", "}", "else", "{", "throw", "new", "InvalidPluginException", "(", "String", ".", "Format", "(", "\"", "Cannot find PluginEntryPointAttribute in assembly {0}. Please add this property to the assembly.", "\"", ",", "assembly", ".", "FullName", ")", ")", ";", "}", "}", "serviceProvider", "=", "serviceCollection", ".", "BuildServiceProvider", "(", ")", ";", "globalScope", "=", "serviceProvider", ".", "CreateScope", "(", ")", ";", "foreach", "(", "var", "plugin", "in", "loadedPlugins", ")", "{", "plugin", ".", "link", "(", "this", ")", ";", "}", "}", "public", "void", "addPlugin", "(", "PluginInterface", "plugin", ")", "{", "Log", ".", "Default", ".", "sendMessage", "(", "\"", "Plugin {0} added.", "\"", ",", "LogLevel", ".", "Info", ",", "\"", "Engine", "\"", ",", "plugin", ".", "Name", ")", ";", "loadedPlugins", ".", "Add", "(", "plugin", ")", ";", "plugin", ".", "initialize", "(", "this", ",", "serviceCollection", ")", ";", "if", "(", "renamedTypeMap", "!=", "null", ")", "{", "plugin", ".", "setupRenamedSaveableTypes", "(", "renamedTypeMap", ")", ";", "}", "}", "internal", "Type", "findType", "(", "String", "assemblyQualifiedName", ")", "{", "Type", "type", ";", "if", "(", "!", "typeCache", ".", "TryGetValue", "(", "assemblyQualifiedName", ",", "out", "type", ")", ")", "{", "type", "=", "Type", ".", "GetType", "(", "assemblyQualifiedName", ",", "false", ")", ";", "if", "(", "type", "==", "null", ")", "{", "String", "typeName", "=", "DefaultTypeFinder", ".", "GetTypeNameWithoutAssembly", "(", "assemblyQualifiedName", ")", ";", "if", "(", "renamedTypeMap", "==", "null", ")", "{", "renamedTypeMap", "=", "new", "RenamedTypeMap", "(", ")", ";", "foreach", "(", "var", "plugin", "in", "loadedPlugins", ")", "{", "plugin", ".", "setupRenamedSaveableTypes", "(", "renamedTypeMap", ")", ";", "}", "}", "if", "(", "!", "renamedTypeMap", ".", "tryGetType", "(", "typeName", ",", "out", "type", ")", ")", "{", "Log", ".", "Warning", "(", "\"", "TypeSearch: Had to do slow search looking for type ", "\\'", "{0}", "\\'", ". You should fix the source file searching for this type or add an entry to the renamed type maps for '{1}'", "\"", ",", "assemblyQualifiedName", ",", "typeName", ")", ";", "foreach", "(", "Assembly", "assembly", "in", "pluginAssemblies", ")", "{", "type", "=", "assembly", ".", "GetType", "(", "typeName", ")", ";", "if", "(", "type", "!=", "null", ")", "{", "break", ";", "}", "}", "if", "(", "type", "==", "null", ")", "{", "foreach", "(", "Assembly", "assembly", "in", "AppDomain", ".", "CurrentDomain", ".", "GetAssemblies", "(", ")", ")", "{", "type", "=", "assembly", ".", "GetType", "(", "typeName", ")", ";", "if", "(", "type", "!=", "null", ")", "{", "break", ";", "}", "}", "}", "}", "if", "(", "type", "!=", "null", ")", "{", "Log", ".", "Warning", "(", "\"", "TypeSearch: Replacement found for type ", "\\'", "{0}", "\\'", ". Replacement type is ", "\\'", "{1}", "\\'", "\"", ",", "assemblyQualifiedName", ",", "type", ".", "AssemblyQualifiedName", ")", ";", "}", "else", "{", "Log", ".", "Warning", "(", "\"", "TypeSearch: Unable to find replacement for type ", "\\'", "{0}", "\\'", ".", "\"", ",", "assemblyQualifiedName", ")", ";", "}", "}", "typeCache", ".", "Add", "(", "assemblyQualifiedName", ",", "type", ")", ";", "}", "return", "type", ";", "}", "public", "void", "addPluginAssembly", "(", "Assembly", "assembly", ")", "{", "pluginAssemblies", ".", "Add", "(", "assembly", ")", ";", "}", "public", "PluginInterface", "getPlugin", "(", "String", "name", ")", "{", "foreach", "(", "PluginInterface", "plugin", "in", "loadedPlugins", ")", "{", "if", "(", "plugin", ".", "Name", "==", "name", ")", "{", "return", "plugin", ";", "}", "}", "return", "null", ";", "}", "public", "void", "setRendererPlugin", "(", "RendererPlugin", "plugin", ",", "out", "WindowInfo", "defaultWindow", ")", "{", "if", "(", "rendererPlugin", "==", "null", ")", "{", "rendererPlugin", "=", "plugin", ";", "Log", ".", "Default", ".", "sendMessage", "(", "\"", "Renderer plugin set to {0}.", "\"", ",", "LogLevel", ".", "Info", ",", "\"", "Engine", "\"", ",", "plugin", ".", "Name", ")", ";", "if", "(", "OnConfigureDefaultWindow", "!=", "null", ")", "{", "OnConfigureDefaultWindow", ".", "Invoke", "(", "out", "defaultWindow", ")", ";", "if", "(", "defaultWindow", "==", "null", ")", "{", "throw", "new", "InvalidPluginException", "(", "\"", "A custom window configure function was invoked, but it did not set the default window up correctly. The renderer cannot be initalized.", "\"", ")", ";", "}", "}", "else", "{", "defaultWindow", "=", "new", "WindowInfo", "(", "\"", "Anomalous Engine", "\"", ",", "640", ",", "480", ")", ";", "}", "}", "else", "{", "throw", "new", "InvalidPluginException", "(", "\"", "A second renderer plugin was added. It is only valid to specify one renderer plugin please correct this issue.", "\"", ")", ";", "}", "}", "public", "void", "reconfigureDefaultWindow", "(", "out", "WindowInfo", "defaultWindow", ")", "{", "if", "(", "OnConfigureDefaultWindow", "!=", "null", ")", "{", "OnConfigureDefaultWindow", ".", "Invoke", "(", "out", "defaultWindow", ")", ";", "}", "else", "{", "defaultWindow", "=", "new", "WindowInfo", "(", "\"", "Anomalous Engine", "\"", ",", "640", ",", "480", ")", ";", "}", "}", "public", "void", "addSubsystemResources", "(", "String", "name", ",", "ResourceListener", "subsystemListener", ")", "{", "prototypeResourceManager", ".", "addSubsystemResource", "(", "new", "SubsystemResources", "(", "name", ",", "subsystemListener", ")", ")", ";", "}", "public", "void", "setPlatformInfo", "(", "UpdateTimer", "mainTimer", ",", "EventManager", "eventManager", ")", "{", "GlobalContextEventHandler", ".", "setEventManager", "(", "eventManager", ")", ";", "foreach", "(", "PluginInterface", "plugin", "in", "loadedPlugins", ")", "{", "plugin", ".", "setPlatformInfo", "(", "mainTimer", ",", "eventManager", ")", ";", "}", "mainTimer", ".", "addUpdateListener", "(", "new", "ThreadManagerUpdate", "(", ")", ")", ";", "}", "public", "void", "addCreateSimElementManagerCommand", "(", "AddSimElementManagerCommand", "command", ")", "{", "addElementManagerCommands", ".", "Add", "(", "command", ")", ";", "}", "public", "IEnumerable", "<", "AddSimElementManagerCommand", ">", "getCreateSimElementManagerCommands", "(", ")", "{", "return", "addElementManagerCommands", ";", "}", "public", "void", "addCreateSimElementCommand", "(", "AddSimElementCommand", "command", ")", "{", "addSimElementCommands", ".", "Add", "(", "command", ")", ";", "}", "public", "IEnumerable", "<", "AddSimElementCommand", ">", "getCreateSimElementCommands", "(", ")", "{", "return", "addSimElementCommands", ";", "}", "public", "List", "<", "CommandManager", ">", "createDebugCommands", "(", ")", "{", "List", "<", "CommandManager", ">", "commands", "=", "new", "List", "<", "CommandManager", ">", "(", ")", ";", "foreach", "(", "PluginInterface", "plugin", "in", "loadedPlugins", ")", "{", "plugin", ".", "createDebugCommands", "(", "commands", ")", ";", "}", "return", "commands", ";", "}", "public", "ResourceManager", "createLiveResourceManager", "(", "String", "resourceNamespace", ")", "{", "return", "new", "ResourceManager", "(", "prototypeResourceManager", ",", "true", ")", "{", "Namespace", "=", "resourceNamespace", "}", ";", "}", "public", "ResourceManager", "createScratchResourceManager", "(", ")", "{", "return", "new", "ResourceManager", "(", "prototypeResourceManager", ",", "false", ")", ";", "}", "public", "ResourceManager", "createResourceManagerForListener", "(", "String", "customSubsystemName", ",", "ResourceListener", "listener", ")", "{", "ResourceManager", "resourceManager", "=", "new", "ResourceManager", "(", ")", ";", "resourceManager", ".", "addSubsystemResource", "(", "new", "SubsystemResources", "(", "customSubsystemName", ",", "listener", ")", ")", ";", "return", "resourceManager", ";", "}", "public", "IEnumerable", "<", "DebugInterface", ">", "DebugInterfaces", "{", "get", "{", "if", "(", "debugInterfaces", "==", "null", ")", "{", "debugInterfaces", "=", "new", "List", "<", "DebugInterface", ">", "(", ")", ";", "foreach", "(", "PluginInterface", "plugin", "in", "loadedPlugins", ")", "{", "DebugInterface", "debug", "=", "plugin", ".", "getDebugInterface", "(", ")", ";", "if", "(", "debug", "!=", "null", ")", "{", "debugInterfaces", ".", "Add", "(", "debug", ")", ";", "}", "}", "}", "return", "debugInterfaces", ";", "}", "}", "endregion", " Functions", "region", " Properties", "public", "RendererPlugin", "RendererPlugin", "{", "get", "{", "return", "rendererPlugin", ";", "}", "}", "public", "ConfigFile", "ConfigFile", "{", "get", "{", "return", "configFile", ";", "}", "}", "public", "String", "PluginDirectory", "{", "get", "{", "if", "(", "pluginDirectory", "==", "null", ")", "{", "String", "[", "]", "args", "=", "Environment", ".", "GetCommandLineArgs", "(", ")", ";", "if", "(", "args", ".", "Length", ">", "0", ")", "{", "pluginDirectory", "=", "Path", ".", "GetDirectoryName", "(", "args", "[", "0", "]", ")", ";", "}", "}", "return", "pluginDirectory", ";", "}", "}", "public", "IServiceScope", "GlobalScope", "{", "get", "{", "return", "globalScope", ";", "}", "}", "endregion", " Properties", "}" ]
This class loads and unloads the various plugins for the system.
[ "This", "class", "loads", "and", "unloads", "the", "various", "plugins", "for", "the", "system", "." ]
[ "/// <summary>", "/// Get the singleton for the PluginManager. It must first be created in", "/// a using statement with the constructor so it will be disposed.", "/// </summary>", "//After a type is found for an AssemblyQualifiedName it will be stored here.", "//This makes sure Shutdown is always called", "/// <summary>", "/// This event is called when the RendererPlugin is found, but before", "/// the Renderer is initialized. This gives the application a chance to", "/// modify the window auto-creation settings.", "/// </summary>", "/// <summary>", "/// Constructor. Must be called once before plugins are used.", "/// </summary>", "//This is externally owned", "/// <summary>", "/// Dispose function. Calling this will dispose the global scope, which will cause the", "/// entire engine to dispose itself. After calling this the program needs to end or finish", "/// any additional cleanup it may need.", "/// </summary>", "/// <remarks>", "/// Internally this will end up being called twice. Once when the user disposes the PluginManager", "/// and once when the di system disposes the actual instance.", "/// </remarks>", "//TODO: Refactor this to be less dumb logic wise.", "//For ms di it seems like we can do this all at once, still investigating lifecycles.", "//If we are not in dispose from a shutdown set this to true and dispose", "//the di containers, that will eventually call the real dispose at the correct", "//time for the shutdown order. This keeps the di system in charge of dispose", "//order and keeps us from having to do other weird stuff.", "//Then virtual file system", "//Unload plugins in reverse order", "/// <summary>", "/// Load all plugins for the assemblies that have been registered. This", "/// should be called before any plugins are used at the start of the", "/// program. The plugin assemblies need to be registered using", "/// addPluginAssembly or by using a PluginLoader.", "/// </summary>", "/// <summary>", "/// Add a plugin instance to this manager. This should be called inside", "/// PluginEntryPoint subclasses. Doing it this way allows a dll to load", "/// multiple plugins.", "/// </summary>", "/// <param name=\"plugin\">The plugin to add.</param>", "/// <summary>", "/// Search for a given type using an assemblyQualifiedName. First this", "/// will use the standard Type.GetType function. If that fails it will", "/// search all the plugin loaded assemblies for the type directly. If", "/// that fails the function will return null. If sucessful the matching", "/// type will be returned.", "/// </summary>", "/// <remarks>", "/// This function could be optimized. For now it will search all loaded", "/// assemblies in a loop when the Type.GetType function call fails.", "/// </remarks>", "/// <param name=\"assemblyQualifiedName\">The AssemblyQualifiedName to search for.</param>", "/// <returns>The matching type or null if the type cannot be found.</returns>", "//If that fails do the slow search.", "//If there is not yet a renamed type map, create it.", "//Check the rename cache", "//If that fails search all loaded assemblies.", "//If we found something put it in the slow search cache so it can be found quicker later", "/// <summary>", "/// Add an assembly that will be searched for a plugin.", "/// </summary>", "/// <param name=\"assembly\">The assembly to search.</param>", "/// <summary>", "/// Get the plugin specified by path.", "/// </summary>", "/// <param name=\"name\">The name of the plugin to get.</param>", "/// <returns>The ElementPlugin if it is found or null if it is not.</returns>", "/// <summary>", "/// Set the RendererPlugin for the run of this engine. It is only valid", "/// to set this one time. Any attempts to set this after the first time", "/// will throw an InvalidPluginException. This will also fire the", "/// OnRendererPluginFound where the default window creation settings can", "/// be overwritten.", "/// </summary>", "/// <param name=\"plugin\">The RendererPlugin to use.</param>", "/// <param name=\"defaultWindow\">Out variable that will contain the setup for the default window.</param>", "/// <summary>", "/// Call this to recall the default window function and setup the window again.", "/// </summary>", "/// <param name=\"defaultWindow\">The parameters for the default window.</param>", "/// <summary>", "/// Add a set of SubsystemResources to the primary ResourceManager. This", "/// will allow a plugin to get updates about the resources that are", "/// requested for a scene. The SubsystemResources passed to this", "/// function should be configured with a ResourceListener so it can get", "/// the appropriate callbacks.", "/// </summary>", "/// <param name=\"subsystem\">A callback configured SubsystemResources instance.</param>", "/// <summary>", "/// Set the classes from the platform that the plugins may be interested", "/// in. The timer can be subscribed to for updates and the EventManager", "/// will be updated with events every frame. This should be called as", "/// soon as possible and before any plugins are used besides the", "/// PlatformPlugin.", "/// </summary>", "/// <param name=\"mainTimer\">The main update timer.</param>", "/// <param name=\"eventManager\">The main event manager.</param>", "/// <summary>", "/// Add a command to create a SimElementManagerDescription.", "/// </summary>", "/// <param name=\"command\">A command that creates SimElementManagerDescriptions.</param>", "/// <summary>", "/// Get the list of commands from plugins that create SimElementManagers.", "/// </summary>", "/// <returns>The list of commands from plugins that create SimElementManagers.</returns>", "/// <summary>", "/// Add a command to create a SimElementDescription.", "/// </summary>", "/// <param name=\"command\">A command that creates SimElementDescriptions.</param>", "/// <summary>", "/// Get the commands that create SimElements.", "/// </summary>", "/// <returns>A list of commands that create SimElements.</returns>", "/// <summary>", "/// Create the debugging commands for the various plugins.", "/// </summary>", "/// <returns>A list of command managers for each plugin.</returns>", "/// <summary>", "/// Create a live ResourceManager that contains the SubsystemResources for each plugin, but not any groups or locations. ", "/// Live means that changes to this resource manager will be applied to subsystems. If you add resources to this resource manager", "/// the subsystems will attempt to load them. It is not very likely that you will create a lot of live resource managers, because even", "/// though you may create multiple of them they likely map back to a singleton in the subsystems they are hooked up to. Also be careful", "/// of name collisions between the ResourceManagers you create. The most likely usage is to create one of these for scene resources and", "/// one for persistant resources, being careful not to have collisions between them.", "/// You provide a namespace for this ResourceManager that helps to avoid these collisions. You should take care that each live ResourceManager", "/// you create has a unique name.", "/// This is the official way to create ResourceManagers because it is unknown until the engine is configured what subsystems need resources.", "/// </summary>", "/// <returns>A new empty ResourceManager that is hooked up to the subsystems.</returns>", "/// <summary>", "/// Create a scratch ResourceManager that contains the SubsystemResources for each plugin, but not any groups or locations. ", "/// Scratch means that resources added to this resource manager will not alert the subsystems of changes. You could then apply this resource manager", "/// to a live resource manager or save it or do something else. These will not alter loaded resources.", "/// This is the official way to create ResourceManagers because it is unknown until the engine is configured what subsystems need resources.", "/// </summary>", "/// <returns>A new empty ResourceManager that is not hooked up to the subsystems.</returns>", "/// <summary>", "/// Create a resource manager with one subsystem specified by customSubsystemName using the passed listener. This", "/// does not have any relation to the live and scratch resource managers.", "/// </summary>", "/// <param name=\"customSubsystemName\"></param>", "/// <param name=\"listener\"></param>", "/// <returns></returns>", "/// <summary>", "/// The RendererPlugin that has been loaded.", "/// </summary>", "/// <summary>", "/// The ConfigFile used by the system.", "/// </summary>" ]
[ { "param": "IDisposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDisposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
20
2,005
111
312356afafdd5740706b1b830928492ff876f429
gnusmas12/MyTested.AspNet.TV
src/Huge Code Base/Open Judge System/Web/OJS.Web/App_GlobalResources/Areas/Administration/Users/ViewModels/UserProfileAdministration.Designer.cs
[ "MIT" ]
C#
UserProfileAdministration
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class UserProfileAdministration { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal UserProfileAdministration() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("OJS.Web.App_GlobalResources.Areas.Administration.Users.ViewModels.UserProfileAdmi" + "nistration", typeof(UserProfileAdministration).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string Age { get { return ResourceManager.GetString("Age", resourceCulture); } } public static string City { get { return ResourceManager.GetString("City", resourceCulture); } } public static string City_length { get { return ResourceManager.GetString("City_length", resourceCulture); } } public static string Company { get { return ResourceManager.GetString("Company", resourceCulture); } } public static string Company_length { get { return ResourceManager.GetString("Company_length", resourceCulture); } } public static string Date_of_birth { get { return ResourceManager.GetString("Date_of_birth", resourceCulture); } } public static string Educational_institution { get { return ResourceManager.GetString("Educational_institution", resourceCulture); } } public static string Educational_institution_length { get { return ResourceManager.GetString("Educational_institution_length", resourceCulture); } } public static string Faculty_number { get { return ResourceManager.GetString("Faculty_number", resourceCulture); } } public static string Faculty_number_length { get { return ResourceManager.GetString("Faculty_number_length", resourceCulture); } } public static string First_name { get { return ResourceManager.GetString("First_name", resourceCulture); } } public static string First_name_length { get { return ResourceManager.GetString("First_name_length", resourceCulture); } } public static string Job_title { get { return ResourceManager.GetString("Job_title", resourceCulture); } } public static string Job_title_length { get { return ResourceManager.GetString("Job_title_length", resourceCulture); } } public static string Last_name { get { return ResourceManager.GetString("Last_name", resourceCulture); } } public static string Last_name_length { get { return ResourceManager.GetString("Last_name_length", resourceCulture); } } public static string Mail_invalid { get { return ResourceManager.GetString("Mail_invalid", resourceCulture); } } public static string Mail_length { get { return ResourceManager.GetString("Mail_length", resourceCulture); } } public static string Mail_required { get { return ResourceManager.GetString("Mail_required", resourceCulture); } } public static string Missing { get { return ResourceManager.GetString("Missing", resourceCulture); } } public static string Null_display_text { get { return ResourceManager.GetString("Null_display_text", resourceCulture); } } public static string UserName { get { return ResourceManager.GetString("UserName", resourceCulture); } } public static string Username_required { get { return ResourceManager.GetString("Username_required", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "16.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "UserProfileAdministration", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "UserProfileAdministration", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "OJS.Web.App_GlobalResources.Areas.Administration.Users.ViewModels.UserProfileAdmi", "\"", "+", "\"", "nistration", "\"", ",", "typeof", "(", "UserProfileAdministration", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "Age", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Age", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "City", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "City", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "City_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "City_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Company", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Company", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Company_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Company_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Date_of_birth", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Date_of_birth", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Educational_institution", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Educational_institution", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Educational_institution_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Educational_institution_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Faculty_number", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Faculty_number", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Faculty_number_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Faculty_number_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "First_name", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "First_name", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "First_name_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "First_name_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Job_title", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Job_title", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Job_title_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Job_title_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Last_name", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Last_name", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Last_name_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Last_name_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Mail_invalid", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Mail_invalid", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Mail_length", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Mail_length", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Mail_required", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Mail_required", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Missing", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Missing", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Null_display_text", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Null_display_text", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "UserName", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "UserName", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Username_required", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Username_required", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Age.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to City.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The entered city is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Company.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The entered company name is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Date of birth.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Educational institution.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The educational institution name is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Faculty number.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The entered faculty number is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to First name.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The entered name is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Job title.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The entered job title name is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Last name.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The entered last name is too long.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invalid email address.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The email is too long!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Email is required!.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Missing.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No information.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Username.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Username is required!.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
867
84
0acf1dda7bebce379b9e0760bb368e669b3955d9
Anshul1507/Leetcode
src/main/java/com/fishercoder/solutions/_161.java
[ "Apache-2.0" ]
Java
_161
/** * 161. One Edit Distance * * Given two strings s and t, determine if they are both one edit distance apart. * * Note: * There are 3 possiblities to satisify one edit distance apart: * Insert a character into s to get t * Delete a character from s to get t * Replace a character of s to get t * * Example 1: * Input: s = "ab", t = "acb" * Output: true * Explanation: We can insert 'c' into s to get t. * * Example 2: * Input: s = "cab", t = "ad" * Output: false * Explanation: We cannot get t from s by only one step. * * Example 3: * Input: s = "1203", t = "1213" * Output: true * Explanation: We can replace '0' with '1' to get t. */
161. One Edit Distance Given two strings s and t, determine if they are both one edit distance apart. There are 3 possiblities to satisify one edit distance apart: Insert a character into s to get t Delete a character from s to get t Replace a character of s to get t Example 1: Input: s = "ab", t = "acb" Output: true Explanation: We can insert 'c' into s to get t. Example 2: Input: s = "cab", t = "ad" Output: false Explanation: We cannot get t from s by only one step. Example 3: Input: s = "1203", t = "1213" Output: true Explanation: We can replace '0' with '1' to get t.
[ "161", ".", "One", "Edit", "Distance", "Given", "two", "strings", "s", "and", "t", "determine", "if", "they", "are", "both", "one", "edit", "distance", "apart", ".", "There", "are", "3", "possiblities", "to", "satisify", "one", "edit", "distance", "apart", ":", "Insert", "a", "character", "into", "s", "to", "get", "t", "Delete", "a", "character", "from", "s", "to", "get", "t", "Replace", "a", "character", "of", "s", "to", "get", "t", "Example", "1", ":", "Input", ":", "s", "=", "\"", "ab", "\"", "t", "=", "\"", "acb", "\"", "Output", ":", "true", "Explanation", ":", "We", "can", "insert", "'", "c", "'", "into", "s", "to", "get", "t", ".", "Example", "2", ":", "Input", ":", "s", "=", "\"", "cab", "\"", "t", "=", "\"", "ad", "\"", "Output", ":", "false", "Explanation", ":", "We", "cannot", "get", "t", "from", "s", "by", "only", "one", "step", ".", "Example", "3", ":", "Input", ":", "s", "=", "\"", "1203", "\"", "t", "=", "\"", "1213", "\"", "Output", ":", "true", "Explanation", ":", "We", "can", "replace", "'", "0", "'", "with", "'", "1", "'", "to", "get", "t", "." ]
public class _161 { public static class Solution1 { public boolean isOneEditDistance(String s, String t) { char[] schar = s.toCharArray(); char[] tchar = t.toCharArray(); if (Math.abs(s.length() - t.length()) == 1) { char[] longer = (s.length() > t.length()) ? schar : tchar; char[] shorter = (longer == schar) ? tchar : schar; int diffCnt = 0; int i = 0; int j = 0; for (; i < shorter.length && j < longer.length; ) { if (longer[j] != shorter[i]) { diffCnt++; j++; } else { i++; j++; } } return diffCnt == 1 || diffCnt == 0;//it could be the last char of the longer is the different one, in that case, diffCnt remains to be zero } else if (s.length() == t.length()) { int diffCnt = 0; for (int i = 0; i < s.length(); i++) { if (schar[i] != tchar[i]) { diffCnt++; } if (diffCnt > 1) { return false; } } return diffCnt == 1; } return false; } } }
[ "public", "class", "_161", "{", "public", "static", "class", "Solution1", "{", "public", "boolean", "isOneEditDistance", "(", "String", "s", ",", "String", "t", ")", "{", "char", "[", "]", "schar", "=", "s", ".", "toCharArray", "(", ")", ";", "char", "[", "]", "tchar", "=", "t", ".", "toCharArray", "(", ")", ";", "if", "(", "Math", ".", "abs", "(", "s", ".", "length", "(", ")", "-", "t", ".", "length", "(", ")", ")", "==", "1", ")", "{", "char", "[", "]", "longer", "=", "(", "s", ".", "length", "(", ")", ">", "t", ".", "length", "(", ")", ")", "?", "schar", ":", "tchar", ";", "char", "[", "]", "shorter", "=", "(", "longer", "==", "schar", ")", "?", "tchar", ":", "schar", ";", "int", "diffCnt", "=", "0", ";", "int", "i", "=", "0", ";", "int", "j", "=", "0", ";", "for", "(", ";", "i", "<", "shorter", ".", "length", "&&", "j", "<", "longer", ".", "length", ";", ")", "{", "if", "(", "longer", "[", "j", "]", "!=", "shorter", "[", "i", "]", ")", "{", "diffCnt", "++", ";", "j", "++", ";", "}", "else", "{", "i", "++", ";", "j", "++", ";", "}", "}", "return", "diffCnt", "==", "1", "||", "diffCnt", "==", "0", ";", "}", "else", "if", "(", "s", ".", "length", "(", ")", "==", "t", ".", "length", "(", ")", ")", "{", "int", "diffCnt", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "s", ".", "length", "(", ")", ";", "i", "++", ")", "{", "if", "(", "schar", "[", "i", "]", "!=", "tchar", "[", "i", "]", ")", "{", "diffCnt", "++", ";", "}", "if", "(", "diffCnt", ">", "1", ")", "{", "return", "false", ";", "}", "}", "return", "diffCnt", "==", "1", ";", "}", "return", "false", ";", "}", "}", "}" ]
161.
[ "161", "." ]
[ "//it could be the last char of the longer is the different one, in that case, diffCnt remains to be zero" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
309
207
14c72f631bf9644581b3925676031697c437990d
eventfuel/lowdown
vendor/gems/selenium-client-1.2.16/lib/selenium/rspec/rspec_extensions.rb
[ "MIT" ]
Ruby
Spec
# # Monkey-patch RSpec Example Group so that we can track whether an # example already failed or not in an after(:each) block # # Useful to only capture Selenium screenshots when a test fails # # * Changed execution_error to be an instance variable (in lieu of # a local variable). # # * Introduced an unique id (example_uid) that is the same for # a real Example (passed in after(:each) when screenshot is # taken) as well as the corresponding ExampleProxy # (passed to the HTML formatter). This unique id gives us # a way to correlate file names between generation and # reporting time. #
Monkey-patch RSpec Example Group so that we can track whether an example already failed or not in an after(:each) block Useful to only capture Selenium screenshots when a test fails Changed execution_error to be an instance variable (in lieu of a local variable). Introduced an unique id (example_uid) that is the same for a real Example (passed in after(:each) when screenshot is taken) as well as the corresponding ExampleProxy (passed to the HTML formatter). This unique id gives us a way to correlate file names between generation and reporting time.
[ "Monkey", "-", "patch", "RSpec", "Example", "Group", "so", "that", "we", "can", "track", "whether", "an", "example", "already", "failed", "or", "not", "in", "an", "after", "(", ":", "each", ")", "block", "Useful", "to", "only", "capture", "Selenium", "screenshots", "when", "a", "test", "fails", "Changed", "execution_error", "to", "be", "an", "instance", "variable", "(", "in", "lieu", "of", "a", "local", "variable", ")", ".", "Introduced", "an", "unique", "id", "(", "example_uid", ")", "that", "is", "the", "same", "for", "a", "real", "Example", "(", "passed", "in", "after", "(", ":", "each", ")", "when", "screenshot", "is", "taken", ")", "as", "well", "as", "the", "corresponding", "ExampleProxy", "(", "passed", "to", "the", "HTML", "formatter", ")", ".", "This", "unique", "id", "gives", "us", "a", "way", "to", "correlate", "file", "names", "between", "generation", "and", "reporting", "time", "." ]
module Spec module Example module ExampleMethods attr_reader :execution_error remove_method :execute def execute(run_options, instance_variables) # :nodoc: @_proxy.options[:actual_example] = self run_options.reporter.example_started(@_proxy) set_instance_variables_from_hash(instance_variables) @execution_error = nil Timeout.timeout(run_options.timeout) do begin before_each_example instance_eval(&@_implementation) rescue Exception => e @execution_error ||= e end begin after_each_example rescue Exception => e @execution_error ||= e end end run_options.reporter.example_finished(@_proxy.update(description), @execution_error) success = @execution_error.nil? || ExamplePendingError === @execution_error end def actual_failure? case execution_error when nil false when Spec::Example::ExamplePendingError, Spec::Example::PendingExampleFixedError, Spec::Example::NoDescriptionError false else true end end def reporting_uid # backtrace is not reliable anymore using the implementation proc Digest::MD5.hexdigest @_implementation.inspect end def pending_for_browsers(*browser_regexps, &block) actual_browser = selenium_driver.browser_string match_browser_regexps = browser_regexps.inject(false) do |match, regexp| match ||= actual_browser =~ Regexp.new(regexp.source, Regexp::IGNORECASE) end if match_browser_regexps pending "#{actual_browser.gsub(/\*/, '').capitalize} does not support this feature yet" else yield end end end class ExampleProxy def reporting_uid options[:actual_example].reporting_uid end end end end
[ "module", "Spec", "module", "Example", "module", "ExampleMethods", "attr_reader", ":execution_error", "remove_method", ":execute", "def", "execute", "(", "run_options", ",", "instance_variables", ")", "@_proxy", ".", "options", "[", ":actual_example", "]", "=", "self", "run_options", ".", "reporter", ".", "example_started", "(", "@_proxy", ")", "set_instance_variables_from_hash", "(", "instance_variables", ")", "@execution_error", "=", "nil", "Timeout", ".", "timeout", "(", "run_options", ".", "timeout", ")", "do", "begin", "before_each_example", "instance_eval", "(", "&", "@_implementation", ")", "rescue", "Exception", "=>", "e", "@execution_error", "||=", "e", "end", "begin", "after_each_example", "rescue", "Exception", "=>", "e", "@execution_error", "||=", "e", "end", "end", "run_options", ".", "reporter", ".", "example_finished", "(", "@_proxy", ".", "update", "(", "description", ")", ",", "@execution_error", ")", "success", "=", "@execution_error", ".", "nil?", "||", "ExamplePendingError", "===", "@execution_error", "end", "def", "actual_failure?", "case", "execution_error", "when", "nil", "false", "when", "Spec", "::", "Example", "::", "ExamplePendingError", ",", "Spec", "::", "Example", "::", "PendingExampleFixedError", ",", "Spec", "::", "Example", "::", "NoDescriptionError", "false", "else", "true", "end", "end", "def", "reporting_uid", "Digest", "::", "MD5", ".", "hexdigest", "@_implementation", ".", "inspect", "end", "def", "pending_for_browsers", "(", "*", "browser_regexps", ",", "&", "block", ")", "actual_browser", "=", "selenium_driver", ".", "browser_string", "match_browser_regexps", "=", "browser_regexps", ".", "inject", "(", "false", ")", "do", "|", "match", ",", "regexp", "|", "match", "||=", "actual_browser", "=~", "Regexp", ".", "new", "(", "regexp", ".", "source", ",", "Regexp", "::", "IGNORECASE", ")", "end", "if", "match_browser_regexps", "pending", "\"#{actual_browser.gsub(/\\*/, '').capitalize} does not support this feature yet\"", "else", "yield", "end", "end", "end", "class", "ExampleProxy", "def", "reporting_uid", "options", "[", ":actual_example", "]", ".", "reporting_uid", "end", "end", "end", "end" ]
Monkey-patch RSpec Example Group so that we can track whether an example already failed or not in an after(:each) block
[ "Monkey", "-", "patch", "RSpec", "Example", "Group", "so", "that", "we", "can", "track", "whether", "an", "example", "already", "failed", "or", "not", "in", "an", "after", "(", ":", "each", ")", "block" ]
[ "# :nodoc:", "# backtrace is not reliable anymore using the implementation proc " ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
410
144
e0178008a2d191fc69e3dbf7237733897f492df4
m-tapper/Eto
src/Eto/Drawing/Icon.cs
[ "BSD-3-Clause" ]
C#
Icon
/// <summary> /// Represents an icon which allows for multiple sizes and resolutions of an image /// </summary> /// <remarks> /// The formats supported vary by platform, however all platforms do support loading windows .ico format. /// /// Using an icon for things like menus, toolbars, etc are preferred so that each platform can use the appropriate /// sized image. /// /// For High DPI/Retina displays (e.g. on OS X), this will allow using a higher resolution image automatically. /// </remarks> /// <copyright>(c) 2016 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license>
Represents an icon which allows for multiple sizes and resolutions of an image
[ "Represents", "an", "icon", "which", "allows", "for", "multiple", "sizes", "and", "resolutions", "of", "an", "image" ]
[Handler(typeof(Icon.IHandler))] [TypeConverter(typeof(IconConverter))] public class Icon : Image { new IHandler Handler { get { return (IHandler)base.Handler; } } public Icon(IHandler handler) : base(handler) { } public Icon(Stream stream) { Handler.Create(stream); Initialize(); } public Icon(string fileName) { Handler.Create(fileName); Initialize(); } public Icon(IEnumerable<IconFrame> frames) { Handler.Create(frames); Initialize(); } public Icon(params IconFrame[] frames) { Handler.Create(frames); Initialize(); } public Icon(float scale, Bitmap bitmap) : this(new IconFrame(scale, bitmap)) { } public static Icon FromResource(string resourceName, Assembly assembly = null) { if (assembly == null) { #if PCL assembly = (Assembly)TypeHelper.GetCallingAssembly.Invoke(null, null); #else assembly = Assembly.GetCallingAssembly(); #endif } if (resourceName.EndsWith(".ico", StringComparison.OrdinalIgnoreCase)) { using (var stream = assembly.GetManifestResourceStream(resourceName)) { if (stream == null) throw new ArgumentException($"Resource '{resourceName}' not found in assembly '{assembly.FullName}'", nameof(resourceName)); return new Icon(stream); } } var frames = new List<IconFrame>(); GetResources(resourceName, assembly, frames); if (frames.Count == 0) throw new ArgumentException($"Resource '{resourceName}' not found in assembly '{assembly.FullName}'", nameof(resourceName)); return new Icon(frames); } static void GetResources(string resourceName, Assembly assembly, List<IconFrame> frames) { var info = assembly.GetManifestResourceInfo(resourceName); if (info != null) frames.Add(IconFrame.FromResource(1f, resourceName, assembly)); var extensionIndex = resourceName.LastIndexOf('.'); if (extensionIndex < 0) return; var extension = resourceName.Substring(extensionIndex); if (extension.Equals(".ico", StringComparison.OrdinalIgnoreCase)) return; var resourceWithoutExtension = resourceName.Substring(0, extensionIndex); var nameWithAt = resourceWithoutExtension + "@"; foreach (var entryName in assembly.GetManifestResourceNames() .Where(r => r.StartsWith(nameWithAt, StringComparison.Ordinal)) .OrderByDescending(r => r)) { if (extension != null && !entryName.EndsWith(extension, StringComparison.Ordinal)) continue; extensionIndex = entryName.LastIndexOf('.'); if (extensionIndex < 0) extensionIndex = entryName.Length; var scaleString = entryName.Substring(nameWithAt.Length, extensionIndex - nameWithAt.Length); float scale; if (!scaleString.EndsWith("x", StringComparison.Ordinal) || !float.TryParse(scaleString.TrimEnd('x'), NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out scale)) continue; frames.Add(IconFrame.FromResource(scale, entryName, assembly)); } } public static Icon FromResource(string resourceName, Type type) { if (type == null) throw new ArgumentNullException("type"); return FromResource(resourceName, type.GetAssembly()); } IconFrame FindBySize(float scale, Size fittingSize) { fittingSize = Size.Ceiling((SizeF)fittingSize * scale); var fs = fittingSize.Width * fittingSize.Height; var frame = Frames .Select(r => Tuple.Create(r.PixelSize.Width * r.PixelSize.Height, r)) .OrderBy(r => r.Item1) .FirstOrDefault(r => r.Item1 >= fs)?.Item2; return frame ?? Frames.OrderBy(r => r.PixelSize.Width * r.PixelSize.Height).Last(); } IconFrame FindByScale(float scale) { IconFrame selected = null; float scaleDiff = 0; float lastScale = 0; foreach (var frame in Frames.OrderBy(r => r.Scale).ThenByDescending(r => r.Size.Width * r.Size.Height)) { var ps = Size.Ceiling((SizeF)Size * scale); var pixelSizeNeeded = ps.Width * ps.Height; var diff = scale - frame.Scale; if (selected == null || (diff < scaleDiff && (diff >= 0 || scaleDiff > 0))) { scaleDiff = diff; lastScale = frame.Scale; selected = frame; } else if (lastScale == frame.Scale) { ps = frame.PixelSize; if (ps.Width * ps.Height >= pixelSizeNeeded) { selected = frame; scaleDiff = diff; lastScale = frame.Scale; } else break; } else break; } if (selected == null) { selected = Frames.OrderBy(r => r.PixelSize.Width * r.PixelSize.Height).Last(); } return selected; } public IconFrame GetFrame(float scale, Size? fittingSize = null) { if (fittingSize != null) { return FindBySize(scale, fittingSize.Value); } else { return FindByScale(scale); } } public Icon WithSize(Size fittingSize) { var frames = Frames.Select(frame => { var scale = Math.Max((float)frame.PixelSize.Width / (float)fittingSize.Width, (float)frame.PixelSize.Height / (float)fittingSize.Height); return new IconFrame(scale, frame.Bitmap); }); return new Icon(frames); } public Icon WithSize(int width, int height) { return WithSize(new Size(width, height)); } public IEnumerable<IconFrame> Frames { get { return Handler.Frames; } } [AutoInitialize(false)] public new interface IHandler : Image.IHandler { void Create(Stream stream); void Create(string fileName); void Create(IEnumerable<IconFrame> frames); IEnumerable<IconFrame> Frames { get; } } }
[ "[", "Handler", "(", "typeof", "(", "Icon", ".", "IHandler", ")", ")", "]", "[", "TypeConverter", "(", "typeof", "(", "IconConverter", ")", ")", "]", "public", "class", "Icon", ":", "Image", "{", "new", "IHandler", "Handler", "{", "get", "{", "return", "(", "IHandler", ")", "base", ".", "Handler", ";", "}", "}", "public", "Icon", "(", "IHandler", "handler", ")", ":", "base", "(", "handler", ")", "{", "}", "public", "Icon", "(", "Stream", "stream", ")", "{", "Handler", ".", "Create", "(", "stream", ")", ";", "Initialize", "(", ")", ";", "}", "public", "Icon", "(", "string", "fileName", ")", "{", "Handler", ".", "Create", "(", "fileName", ")", ";", "Initialize", "(", ")", ";", "}", "public", "Icon", "(", "IEnumerable", "<", "IconFrame", ">", "frames", ")", "{", "Handler", ".", "Create", "(", "frames", ")", ";", "Initialize", "(", ")", ";", "}", "public", "Icon", "(", "params", "IconFrame", "[", "]", "frames", ")", "{", "Handler", ".", "Create", "(", "frames", ")", ";", "Initialize", "(", ")", ";", "}", "public", "Icon", "(", "float", "scale", ",", "Bitmap", "bitmap", ")", ":", "this", "(", "new", "IconFrame", "(", "scale", ",", "bitmap", ")", ")", "{", "}", "public", "static", "Icon", "FromResource", "(", "string", "resourceName", ",", "Assembly", "assembly", "=", "null", ")", "{", "if", "(", "assembly", "==", "null", ")", "{", "if", "PCL", "assembly", "=", "(", "Assembly", ")", "TypeHelper", ".", "GetCallingAssembly", ".", "Invoke", "(", "null", ",", "null", ")", ";", "else", "assembly", "=", "Assembly", ".", "GetCallingAssembly", "(", ")", ";", "endif", "}", "if", "(", "resourceName", ".", "EndsWith", "(", "\"", ".ico", "\"", ",", "StringComparison", ".", "OrdinalIgnoreCase", ")", ")", "{", "using", "(", "var", "stream", "=", "assembly", ".", "GetManifestResourceStream", "(", "resourceName", ")", ")", "{", "if", "(", "stream", "==", "null", ")", "throw", "new", "ArgumentException", "(", "$\"", "Resource '", "{", "resourceName", "}", "' not found in assembly '", "{", "assembly", ".", "FullName", "}", "'", "\"", ",", "nameof", "(", "resourceName", ")", ")", ";", "return", "new", "Icon", "(", "stream", ")", ";", "}", "}", "var", "frames", "=", "new", "List", "<", "IconFrame", ">", "(", ")", ";", "GetResources", "(", "resourceName", ",", "assembly", ",", "frames", ")", ";", "if", "(", "frames", ".", "Count", "==", "0", ")", "throw", "new", "ArgumentException", "(", "$\"", "Resource '", "{", "resourceName", "}", "' not found in assembly '", "{", "assembly", ".", "FullName", "}", "'", "\"", ",", "nameof", "(", "resourceName", ")", ")", ";", "return", "new", "Icon", "(", "frames", ")", ";", "}", "static", "void", "GetResources", "(", "string", "resourceName", ",", "Assembly", "assembly", ",", "List", "<", "IconFrame", ">", "frames", ")", "{", "var", "info", "=", "assembly", ".", "GetManifestResourceInfo", "(", "resourceName", ")", ";", "if", "(", "info", "!=", "null", ")", "frames", ".", "Add", "(", "IconFrame", ".", "FromResource", "(", "1f", ",", "resourceName", ",", "assembly", ")", ")", ";", "var", "extensionIndex", "=", "resourceName", ".", "LastIndexOf", "(", "'", ".", "'", ")", ";", "if", "(", "extensionIndex", "<", "0", ")", "return", ";", "var", "extension", "=", "resourceName", ".", "Substring", "(", "extensionIndex", ")", ";", "if", "(", "extension", ".", "Equals", "(", "\"", ".ico", "\"", ",", "StringComparison", ".", "OrdinalIgnoreCase", ")", ")", "return", ";", "var", "resourceWithoutExtension", "=", "resourceName", ".", "Substring", "(", "0", ",", "extensionIndex", ")", ";", "var", "nameWithAt", "=", "resourceWithoutExtension", "+", "\"", "@", "\"", ";", "foreach", "(", "var", "entryName", "in", "assembly", ".", "GetManifestResourceNames", "(", ")", ".", "Where", "(", "r", "=>", "r", ".", "StartsWith", "(", "nameWithAt", ",", "StringComparison", ".", "Ordinal", ")", ")", ".", "OrderByDescending", "(", "r", "=>", "r", ")", ")", "{", "if", "(", "extension", "!=", "null", "&&", "!", "entryName", ".", "EndsWith", "(", "extension", ",", "StringComparison", ".", "Ordinal", ")", ")", "continue", ";", "extensionIndex", "=", "entryName", ".", "LastIndexOf", "(", "'", ".", "'", ")", ";", "if", "(", "extensionIndex", "<", "0", ")", "extensionIndex", "=", "entryName", ".", "Length", ";", "var", "scaleString", "=", "entryName", ".", "Substring", "(", "nameWithAt", ".", "Length", ",", "extensionIndex", "-", "nameWithAt", ".", "Length", ")", ";", "float", "scale", ";", "if", "(", "!", "scaleString", ".", "EndsWith", "(", "\"", "x", "\"", ",", "StringComparison", ".", "Ordinal", ")", "||", "!", "float", ".", "TryParse", "(", "scaleString", ".", "TrimEnd", "(", "'", "x", "'", ")", ",", "NumberStyles", ".", "AllowDecimalPoint", ",", "CultureInfo", ".", "InvariantCulture", ",", "out", "scale", ")", ")", "continue", ";", "frames", ".", "Add", "(", "IconFrame", ".", "FromResource", "(", "scale", ",", "entryName", ",", "assembly", ")", ")", ";", "}", "}", "public", "static", "Icon", "FromResource", "(", "string", "resourceName", ",", "Type", "type", ")", "{", "if", "(", "type", "==", "null", ")", "throw", "new", "ArgumentNullException", "(", "\"", "type", "\"", ")", ";", "return", "FromResource", "(", "resourceName", ",", "type", ".", "GetAssembly", "(", ")", ")", ";", "}", "IconFrame", "FindBySize", "(", "float", "scale", ",", "Size", "fittingSize", ")", "{", "fittingSize", "=", "Size", ".", "Ceiling", "(", "(", "SizeF", ")", "fittingSize", "*", "scale", ")", ";", "var", "fs", "=", "fittingSize", ".", "Width", "*", "fittingSize", ".", "Height", ";", "var", "frame", "=", "Frames", ".", "Select", "(", "r", "=>", "Tuple", ".", "Create", "(", "r", ".", "PixelSize", ".", "Width", "*", "r", ".", "PixelSize", ".", "Height", ",", "r", ")", ")", ".", "OrderBy", "(", "r", "=>", "r", ".", "Item1", ")", ".", "FirstOrDefault", "(", "r", "=>", "r", ".", "Item1", ">=", "fs", ")", "?", ".", "Item2", ";", "return", "frame", "??", "Frames", ".", "OrderBy", "(", "r", "=>", "r", ".", "PixelSize", ".", "Width", "*", "r", ".", "PixelSize", ".", "Height", ")", ".", "Last", "(", ")", ";", "}", "IconFrame", "FindByScale", "(", "float", "scale", ")", "{", "IconFrame", "selected", "=", "null", ";", "float", "scaleDiff", "=", "0", ";", "float", "lastScale", "=", "0", ";", "foreach", "(", "var", "frame", "in", "Frames", ".", "OrderBy", "(", "r", "=>", "r", ".", "Scale", ")", ".", "ThenByDescending", "(", "r", "=>", "r", ".", "Size", ".", "Width", "*", "r", ".", "Size", ".", "Height", ")", ")", "{", "var", "ps", "=", "Size", ".", "Ceiling", "(", "(", "SizeF", ")", "Size", "*", "scale", ")", ";", "var", "pixelSizeNeeded", "=", "ps", ".", "Width", "*", "ps", ".", "Height", ";", "var", "diff", "=", "scale", "-", "frame", ".", "Scale", ";", "if", "(", "selected", "==", "null", "||", "(", "diff", "<", "scaleDiff", "&&", "(", "diff", ">=", "0", "||", "scaleDiff", ">", "0", ")", ")", ")", "{", "scaleDiff", "=", "diff", ";", "lastScale", "=", "frame", ".", "Scale", ";", "selected", "=", "frame", ";", "}", "else", "if", "(", "lastScale", "==", "frame", ".", "Scale", ")", "{", "ps", "=", "frame", ".", "PixelSize", ";", "if", "(", "ps", ".", "Width", "*", "ps", ".", "Height", ">=", "pixelSizeNeeded", ")", "{", "selected", "=", "frame", ";", "scaleDiff", "=", "diff", ";", "lastScale", "=", "frame", ".", "Scale", ";", "}", "else", "break", ";", "}", "else", "break", ";", "}", "if", "(", "selected", "==", "null", ")", "{", "selected", "=", "Frames", ".", "OrderBy", "(", "r", "=>", "r", ".", "PixelSize", ".", "Width", "*", "r", ".", "PixelSize", ".", "Height", ")", ".", "Last", "(", ")", ";", "}", "return", "selected", ";", "}", "public", "IconFrame", "GetFrame", "(", "float", "scale", ",", "Size", "?", "fittingSize", "=", "null", ")", "{", "if", "(", "fittingSize", "!=", "null", ")", "{", "return", "FindBySize", "(", "scale", ",", "fittingSize", ".", "Value", ")", ";", "}", "else", "{", "return", "FindByScale", "(", "scale", ")", ";", "}", "}", "public", "Icon", "WithSize", "(", "Size", "fittingSize", ")", "{", "var", "frames", "=", "Frames", ".", "Select", "(", "frame", "=>", "{", "var", "scale", "=", "Math", ".", "Max", "(", "(", "float", ")", "frame", ".", "PixelSize", ".", "Width", "/", "(", "float", ")", "fittingSize", ".", "Width", ",", "(", "float", ")", "frame", ".", "PixelSize", ".", "Height", "/", "(", "float", ")", "fittingSize", ".", "Height", ")", ";", "return", "new", "IconFrame", "(", "scale", ",", "frame", ".", "Bitmap", ")", ";", "}", ")", ";", "return", "new", "Icon", "(", "frames", ")", ";", "}", "public", "Icon", "WithSize", "(", "int", "width", ",", "int", "height", ")", "{", "return", "WithSize", "(", "new", "Size", "(", "width", ",", "height", ")", ")", ";", "}", "public", "IEnumerable", "<", "IconFrame", ">", "Frames", "{", "get", "{", "return", "Handler", ".", "Frames", ";", "}", "}", "[", "AutoInitialize", "(", "false", ")", "]", "public", "new", "interface", "IHandler", ":", "Image", ".", "IHandler", "{", "void", "Create", "(", "Stream", "stream", ")", ";", "void", "Create", "(", "string", "fileName", ")", ";", "void", "Create", "(", "IEnumerable", "<", "IconFrame", ">", "frames", ")", ";", "IEnumerable", "<", "IconFrame", ">", "Frames", "{", "get", ";", "}", "}", "}" ]
Represents an icon which allows for multiple sizes and resolutions of an image
[ "Represents", "an", "icon", "which", "allows", "for", "multiple", "sizes", "and", "resolutions", "of", "an", "image" ]
[ "/// <summary>", "/// Initializes a new instance of the Icon class with the specified handler", "/// </summary>", "/// <param name=\"handler\">Handler for the icon backend</param>", "/// <summary>", "/// Initializes a new instance of the Icon class with the contents of the specified <paramref name=\"stream\"/>", "/// </summary>", "/// <param name=\"stream\">Stream to load the content from</param>", "/// <summary>", "/// Intitializes a new instanc of the Icon class with the contents of the specified <paramref name=\"fileName\"/>", "/// </summary>", "/// <param name=\"fileName\">Name of the file to loat the content from</param>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"Eto.Drawing.Icon\"/> class with the specified frames.", "/// </summary>", "/// <remarks>", "/// This is used when you want to create an icon with specific bitmap frames at different scales or sizes.", "/// </remarks>", "/// <param name=\"frames\">Frames for the icon.</param>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"Eto.Drawing.Icon\"/> class with the specified frames.", "/// </summary>", "/// <remarks>", "/// This is used when you want to create an icon with specific bitmap frames at different scales or sizes.", "/// </remarks>", "/// <param name=\"frames\">Frames for the icon.</param>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"Eto.Drawing.Icon\"/> class with the specified bitmap.", "/// </summary>", "/// <remarks>", "/// This is used when you want to create an icon with a single bitmap frame with the specified logical scale.", "/// </remarks>", "/// <param name=\"scale\">Logical pixel scale of the specified bitmap.</param>", "/// <param name=\"bitmap\">Bitmap for the frame.</param>", "/// <summary>", "/// Loads an icon from an embedded resource of the specified assembly", "/// </summary>", "/// <param name=\"assembly\">Assembly to load the resource from</param>", "/// <param name=\"resourceName\">Fully qualified name of the resource to load. E.g. \"MyProject.SomeFolder.YourFile.extension\"</param>", "/// <returns>A new instance of an Icon loaded with the contents of the specified resource</returns>", "// no extension? don't look for others", "// .ico files already have multiple resolutions", "// must be same extension, if one is supplied with the resourceName", "// get the scale, if supplied", "// parse out scale, e.g. @2x, @0.5x", "/// <summary>", "/// Loads an icon from a resource in the same assembly as the specified <paramref name=\"type\"/>", "/// </summary>", "/// <returns>The icon instance.</returns>", "/// <param name=\"resourceName\">Full name of the resource in the type's assembly E.g. \"MyProject.SomeFolder.YourFile.extension\"</param>", "/// <param name=\"type\">Type of the assembly to get the resource.</param>", "/// <summary>", "/// Find based on the fitting pixel size", "/// </summary>", "// adjust fitting size to scale to get pixel size desired", "/// <summary>", "/// find based on scale alone, we don't know the final render size", "/// </summary>", "// found where scale is the next greater or equal to desired scale", "// multiple resolutions with the same scale, use the one with the best pixel size", "// (e.g. ico file with multiple resolutions)", "// get largest", "/// <summary>", "/// Gets the frame with the specified scale that can fit into the <paramref name=\"fittingSize\"/> if specified.", "/// </summary>", "/// <remarks>", "/// This can be used to determine which frame should be used to draw to the screen, based on the desired logical pixel", "/// scale and final drawn size of the icon.", "/// </remarks>", "/// <returns>The frame that is the closest match for the specified scale and fitting size.</returns>", "/// <param name=\"scale\">Logical scale to find for, 1 for normal size, 2 for retina, etc.</param>", "/// <param name=\"fittingSize\">Fitting size that the icon will be drawn to, if known.</param>", "// we know the final render size, find the best match based on pixel size vs scale", "// We always prefer size that matches best with the input scale", "// e.g. when we need scale 2 at 64x64, it will prefer the frame that is greater in pixel size to 128x128.", "/// <summary>", "/// Gets a copy of this Icon with frames scaled to draw within the specified fitting size.", "/// </summary>", "/// <remarks>", "/// This is useful when you want to draw an Icon at a different size than the default size. ", "/// Note that the <paramref name=\"fittingSize\"/> specifies the maxiumum drawing size of the Icon, but will not", "/// change the aspect of each frame's bitmap. For example, if an existing frame is 128x128, and you specify 16x32,", "/// then the resulting frame will draw at 16x16.", "/// </remarks>", "/// <returns>A new icon that will draw within the fitting size.</returns>", "/// <param name=\"fittingSize\">The maximum size to draw the Icon.</param>", "/// <summary>", "/// Gets a copy of this Icon with frames scaled to draw within the specified fitting size.", "/// </summary>", "/// <remarks>", "/// This is useful when you want to draw an Icon at a different size than the default size. ", "/// Note that the <paramref name=\"width\"/> and <paramref name=\"height\"/> specifies the maxiumum drawing size of the Icon, but will not", "/// change the aspect of each frame's bitmap. For example, if an existing frame is 128x128, and you specify 16x32,", "/// then the resulting frame will draw at 16x16.", "/// </remarks>", "/// <returns>A new icon that will draw within the fitting size.</returns>", "/// <param name=\"width\">Maxiumum drawing width for the new icon.</param>", "/// <param name=\"height\">Maxiumum drawing height for the new icon.</param>", "/// <summary>", "/// Gets the definition for each frame in this icon.", "/// </summary>", "/// <value>The frames of the icon.</value>", "/// <summary>", "/// Platform handler for the <see cref=\"Icon\"/> class", "/// </summary>", "/// <summary>", "/// Called when creating an instance from a stream", "/// </summary>", "/// <param name=\"stream\">Stream to load the icon from</param>", "/// <summary>", "/// Called when creating an instance from a file name", "/// </summary>", "/// <param name=\"fileName\">File name to load the icon from</param>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"Eto.Drawing.Icon\"/> class with the specified frames.", "/// </summary>", "/// <remarks>", "/// This is used when you want to create an icon with specific bitmap frames at different scales or sizes.", "/// </remarks>", "/// <param name=\"frames\">Frames for the icon.</param>", "/// <summary>", "/// Gets the definition for each frame in this icon.", "/// </summary>", "/// <value>The frames of the icon.</value>" ]
[ { "param": "Image", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Image", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remarks", "docstring": "The formats supported vary by platform, however all platforms do support loading windows .ico format.\n\nUsing an icon for things like menus, toolbars, etc are preferred so that each platform can use the appropriate\nsized image.\n\nFor High DPI/Retina displays , this will allow using a higher resolution image automatically.", "docstring_tokens": [ "The", "formats", "supported", "vary", "by", "platform", "however", "all", "platforms", "do", "support", "loading", "windows", ".", "ico", "format", ".", "Using", "an", "icon", "for", "things", "like", "menus", "toolbars", "etc", "are", "preferred", "so", "that", "each", "platform", "can", "use", "the", "appropriate", "sized", "image", ".", "For", "High", "DPI", "/", "Retina", "displays", "this", "will", "allow", "using", "a", "higher", "resolution", "image", "automatically", "." ] }, { "identifier": "copyright", "docstring": "(c) 2016 by Curtis Wensley", "docstring_tokens": [ "(", "c", ")", "2016", "by", "Curtis", "Wensley" ] }, { "identifier": "license", "docstring": "See LICENSE for full terms", "docstring_tokens": [ "See", "LICENSE", "for", "full", "terms" ] } ] }
false
23
1,352
144
107b708a108de77c40b9ff7153f3ef9d51d865f4
abhishekks831998/umple
Umplificator/UmplifiedProjects/weka-umplified-0/src/main/java/weka/core/neighboursearch/balltrees/MiddleOutConstructor.java
[ "MIT" ]
Java
TempNode
/** * Temp class to represent either a leaf node or an internal node. Should only * have two children (could be the case one child is an instance and the other * another node). Primarily used for anchor nodes. It stores the points * contained in a node together with their distances to the node's * centre/anchor point. * * @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz) * @version $Revision: 10203 $ */
Temp class to represent either a leaf node or an internal node. Should only have two children (could be the case one child is an instance and the other another node). Primarily used for anchor nodes. It stores the points contained in a node together with their distances to the node's centre/anchor point. @author Ashraf M. Kibriya (amk14[at-the-rate]cs[dot]waikato[dot]ac[dot]nz) @version $Revision: 10203 $
[ "Temp", "class", "to", "represent", "either", "a", "leaf", "node", "or", "an", "internal", "node", ".", "Should", "only", "have", "two", "children", "(", "could", "be", "the", "case", "one", "child", "is", "an", "instance", "and", "the", "other", "another", "node", ")", ".", "Primarily", "used", "for", "anchor", "nodes", ".", "It", "stores", "the", "points", "contained", "in", "a", "node", "together", "with", "their", "distances", "to", "the", "node", "'", "s", "centre", "/", "anchor", "point", ".", "@author", "Ashraf", "M", ".", "Kibriya", "(", "amk14", "[", "at", "-", "the", "-", "rate", "]", "cs", "[", "dot", "]", "waikato", "[", "dot", "]", "ac", "[", "dot", "]", "nz", ")", "@version", "$Revision", ":", "10203", "$" ]
protected class TempNode implements RevisionHandler { /** The anchor point of the node. */ Instance anchor; /** The index of the anchor point. */ int idx; /** The radius of the node. */ double radius; /** The list of points inside the node. */ MyIdxList points; /** Node's left child. */ TempNode left; /** Node's right child. */ TempNode right; /** * Returns a string represention of the node. * * @return The string representation of the node. */ @Override public String toString() { if (points == null || points.length() == 0) { return idx + ""; } StringBuffer bf = new StringBuffer(); try { bf.append(idx + " p: "); ListNode temp; for (int i = 0; i < points.size(); i++) { temp = points.get(i); if (i == 0) { bf.append("" + temp.idx); } else { bf.append(", " + temp.idx); } } } catch (Exception ex) { ex.printStackTrace(); } return bf.toString(); } /** * Returns the revision string. * * @return the revision */ @Override public String getRevision() { return RevisionUtils.extract("$Revision: 10203 $"); } }
[ "protected", "class", "TempNode", "implements", "RevisionHandler", "{", "/** The anchor point of the node. */", "Instance", "anchor", ";", "/** The index of the anchor point. */", "int", "idx", ";", "/** The radius of the node. */", "double", "radius", ";", "/** The list of points inside the node. */", "MyIdxList", "points", ";", "/** Node's left child. */", "TempNode", "left", ";", "/** Node's right child. */", "TempNode", "right", ";", "/**\n * Returns a string represention of the node.\n * \n * @return The string representation of the node.\n */", "@", "Override", "public", "String", "toString", "(", ")", "{", "if", "(", "points", "==", "null", "||", "points", ".", "length", "(", ")", "==", "0", ")", "{", "return", "idx", "+", "\"", "\"", ";", "}", "StringBuffer", "bf", "=", "new", "StringBuffer", "(", ")", ";", "try", "{", "bf", ".", "append", "(", "idx", "+", "\"", " p: ", "\"", ")", ";", "ListNode", "temp", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "points", ".", "size", "(", ")", ";", "i", "++", ")", "{", "temp", "=", "points", ".", "get", "(", "i", ")", ";", "if", "(", "i", "==", "0", ")", "{", "bf", ".", "append", "(", "\"", "\"", "+", "temp", ".", "idx", ")", ";", "}", "else", "{", "bf", ".", "append", "(", "\"", ", ", "\"", "+", "temp", ".", "idx", ")", ";", "}", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "}", "return", "bf", ".", "toString", "(", ")", ";", "}", "/**\n * Returns the revision string.\n * \n * @return the revision\n */", "@", "Override", "public", "String", "getRevision", "(", ")", "{", "return", "RevisionUtils", ".", "extract", "(", "\"", "$Revision: 10203 $", "\"", ")", ";", "}", "}" ]
Temp class to represent either a leaf node or an internal node.
[ "Temp", "class", "to", "represent", "either", "a", "leaf", "node", "or", "an", "internal", "node", "." ]
[]
[ { "param": "RevisionHandler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "RevisionHandler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
307
132
7f60cdcc4cb2ec1c626f2c83036cfd58fdea98af
TU-Berlin-SNET/tresor-pdp-caching
modules/benchmarks/src/main/java/ilhn/xacml/benchmark/balana/CacheFinderBenchmark.java
[ "Apache-2.0" ]
Java
CacheFinderBenchmark
/** * Benchmark solely for finding matching policies and policy sets for a particular request * under different conditions and configurations. * Includes the whole policy finding process, e.g. target matching and loading the policy. * Tests only PolicyFinderModule Type 2, ProxyFilebasedPolicyFinderModule from ExtendedPDP, * which provides functionalities such as caching of policies, policy finder results * and loading policies on-demand. */
Benchmark solely for finding matching policies and policy sets for a particular request under different conditions and configurations. Includes the whole policy finding process, e.g. target matching and loading the policy. Tests only PolicyFinderModule Type 2, ProxyFilebasedPolicyFinderModule from ExtendedPDP, which provides functionalities such as caching of policies, policy finder results and loading policies on-demand.
[ "Benchmark", "solely", "for", "finding", "matching", "policies", "and", "policy", "sets", "for", "a", "particular", "request", "under", "different", "conditions", "and", "configurations", ".", "Includes", "the", "whole", "policy", "finding", "process", "e", ".", "g", ".", "target", "matching", "and", "loading", "the", "policy", ".", "Tests", "only", "PolicyFinderModule", "Type", "2", "ProxyFilebasedPolicyFinderModule", "from", "ExtendedPDP", "which", "provides", "functionalities", "such", "as", "caching", "of", "policies", "policy", "finder", "results", "and", "loading", "policies", "on", "-", "demand", "." ]
@State(Scope.Benchmark) public class CacheFinderBenchmark { private static Logger log = LoggerFactory.getLogger(CacheFinderBenchmark.class); @Param({ "2" }) int policyFinderType; @Param({ "10000" }) int requestCount; @Param({ "100", "1000", "1010", "10000" }) int policyCount; @Param({ "0", "0.25", "0.5" }) float finderResultCacheFraction; @Param({ "0.5", "1" }) float finderPolicyCacheFraction; List<EvaluationCtx> requests; PolicyFinder finder; Random random; @Setup public void setup() throws FileNotFoundException { log.info("Setting up FinderBenchmark"); String policyLocation; switch (policyCount) { case 100: policyLocation = BenchmarkUtil.POLICIES_100; break; case 1000: policyLocation = BenchmarkUtil.POLICIES_1k; break; case 1010: policyLocation = BenchmarkUtil.POLICIES_1k10; break; case 10000: policyLocation = BenchmarkUtil.POLICIES_10k; break; default: throw new IllegalArgumentException("Illegal Policycount " + policyCount); } log.info("{} policies at path {}", policyCount, policyLocation); int resultCacheSize = Math.round(finderResultCacheFraction * requestCount); int policyCacheSize = Math.round(finderPolicyCacheFraction * policyCount); log.info("ResultCache size is {} | PolicyCache size is {}", resultCacheSize, policyCacheSize); PolicyFinderModule pfm = new ProxyFilebasedPolicyFinderModule(policyLocation, resultCacheSize, policyCacheSize); log.info("PolicyFinderModule is {}", pfm.getClass().getSimpleName()); log.info("Loading {} requests", requestCount); requests = BenchmarkUtil.loadStrings(BenchmarkUtil.REQUESTS, requestCount).stream() .collect(Collectors.mapping(s -> { try { return EvaluationCtxFactory.getFactory().getEvaluationCtx(XACML3StreamParser.readRequest(s), null); } catch (Exception e) { throw new RuntimeException(e); } }, Collectors.toList())); log.info("Loaded {} requests", requests.size()); random = new Random(); Set<PolicyFinderModule> finderModules = new HashSet<>(); finderModules.add(pfm); finder = new PolicyFinder(); finder.setModules(finderModules); finder.init(); log.info("Ready to go..."); } @Benchmark public PolicyFinderResult findPolicyRandomRequest() { return finder.findPolicy(requests.get(random.nextInt(requests.size()))); } }
[ "@", "State", "(", "Scope", ".", "Benchmark", ")", "public", "class", "CacheFinderBenchmark", "{", "private", "static", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "CacheFinderBenchmark", ".", "class", ")", ";", "@", "Param", "(", "{", "\"", "2", "\"", "}", ")", "int", "policyFinderType", ";", "@", "Param", "(", "{", "\"", "10000", "\"", "}", ")", "int", "requestCount", ";", "@", "Param", "(", "{", "\"", "100", "\"", ",", "\"", "1000", "\"", ",", "\"", "1010", "\"", ",", "\"", "10000", "\"", "}", ")", "int", "policyCount", ";", "@", "Param", "(", "{", "\"", "0", "\"", ",", "\"", "0.25", "\"", ",", "\"", "0.5", "\"", "}", ")", "float", "finderResultCacheFraction", ";", "@", "Param", "(", "{", "\"", "0.5", "\"", ",", "\"", "1", "\"", "}", ")", "float", "finderPolicyCacheFraction", ";", "List", "<", "EvaluationCtx", ">", "requests", ";", "PolicyFinder", "finder", ";", "Random", "random", ";", "@", "Setup", "public", "void", "setup", "(", ")", "throws", "FileNotFoundException", "{", "log", ".", "info", "(", "\"", "Setting up FinderBenchmark", "\"", ")", ";", "String", "policyLocation", ";", "switch", "(", "policyCount", ")", "{", "case", "100", ":", "policyLocation", "=", "BenchmarkUtil", ".", "POLICIES_100", ";", "break", ";", "case", "1000", ":", "policyLocation", "=", "BenchmarkUtil", ".", "POLICIES_1k", ";", "break", ";", "case", "1010", ":", "policyLocation", "=", "BenchmarkUtil", ".", "POLICIES_1k10", ";", "break", ";", "case", "10000", ":", "policyLocation", "=", "BenchmarkUtil", ".", "POLICIES_10k", ";", "break", ";", "default", ":", "throw", "new", "IllegalArgumentException", "(", "\"", "Illegal Policycount ", "\"", "+", "policyCount", ")", ";", "}", "log", ".", "info", "(", "\"", "{} policies at path {}", "\"", ",", "policyCount", ",", "policyLocation", ")", ";", "int", "resultCacheSize", "=", "Math", ".", "round", "(", "finderResultCacheFraction", "*", "requestCount", ")", ";", "int", "policyCacheSize", "=", "Math", ".", "round", "(", "finderPolicyCacheFraction", "*", "policyCount", ")", ";", "log", ".", "info", "(", "\"", "ResultCache size is {} | PolicyCache size is {}", "\"", ",", "resultCacheSize", ",", "policyCacheSize", ")", ";", "PolicyFinderModule", "pfm", "=", "new", "ProxyFilebasedPolicyFinderModule", "(", "policyLocation", ",", "resultCacheSize", ",", "policyCacheSize", ")", ";", "log", ".", "info", "(", "\"", "PolicyFinderModule is {}", "\"", ",", "pfm", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "log", ".", "info", "(", "\"", "Loading {} requests", "\"", ",", "requestCount", ")", ";", "requests", "=", "BenchmarkUtil", ".", "loadStrings", "(", "BenchmarkUtil", ".", "REQUESTS", ",", "requestCount", ")", ".", "stream", "(", ")", ".", "collect", "(", "Collectors", ".", "mapping", "(", "s", "->", "{", "try", "{", "return", "EvaluationCtxFactory", ".", "getFactory", "(", ")", ".", "getEvaluationCtx", "(", "XACML3StreamParser", ".", "readRequest", "(", "s", ")", ",", "null", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}", ",", "Collectors", ".", "toList", "(", ")", ")", ")", ";", "log", ".", "info", "(", "\"", "Loaded {} requests", "\"", ",", "requests", ".", "size", "(", ")", ")", ";", "random", "=", "new", "Random", "(", ")", ";", "Set", "<", "PolicyFinderModule", ">", "finderModules", "=", "new", "HashSet", "<", ">", "(", ")", ";", "finderModules", ".", "add", "(", "pfm", ")", ";", "finder", "=", "new", "PolicyFinder", "(", ")", ";", "finder", ".", "setModules", "(", "finderModules", ")", ";", "finder", ".", "init", "(", ")", ";", "log", ".", "info", "(", "\"", "Ready to go...", "\"", ")", ";", "}", "@", "Benchmark", "public", "PolicyFinderResult", "findPolicyRandomRequest", "(", ")", "{", "return", "finder", ".", "findPolicy", "(", "requests", ".", "get", "(", "random", ".", "nextInt", "(", "requests", ".", "size", "(", ")", ")", ")", ")", ";", "}", "}" ]
Benchmark solely for finding matching policies and policy sets for a particular request under different conditions and configurations.
[ "Benchmark", "solely", "for", "finding", "matching", "policies", "and", "policy", "sets", "for", "a", "particular", "request", "under", "different", "conditions", "and", "configurations", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
20
592
84
d43d9eaf44a59f762f6a50fa98177628c1c3eb52
UniversityofHelsinki/OC-webgui
app/services/agent_status_updater.rb
[ "MIT" ]
Ruby
AgentStatusUpdater
# Provides functionality for tracking the statuses of Agents over time and storing the current status of logged in Agents in the DB. # This is done by comparing the latest agent status data from OC to AgentStatus data stored in the DB. Any changes are updated. # # Current_time parameter should always be current time (Time.zone.now), except for tests # Last_success should contain timestamp of the last time the update job was run successfully
Provides functionality for tracking the statuses of Agents over time and storing the current status of logged in Agents in the DB. This is done by comparing the latest agent status data from OC to AgentStatus data stored in the DB. Any changes are updated. Current_time parameter should always be current time (Time.zone.now), except for tests Last_success should contain timestamp of the last time the update job was run successfully
[ "Provides", "functionality", "for", "tracking", "the", "statuses", "of", "Agents", "over", "time", "and", "storing", "the", "current", "status", "of", "logged", "in", "Agents", "in", "the", "DB", ".", "This", "is", "done", "by", "comparing", "the", "latest", "agent", "status", "data", "from", "OC", "to", "AgentStatus", "data", "stored", "in", "the", "DB", ".", "Any", "changes", "are", "updated", ".", "Current_time", "parameter", "should", "always", "be", "current", "time", "(", "Time", ".", "zone", ".", "now", ")", "except", "for", "tests", "Last_success", "should", "contain", "timestamp", "of", "the", "last", "time", "the", "update", "job", "was", "run", "successfully" ]
class AgentStatusUpdater include Now def initialize(current_time, last_success) @current_time = current_time @last_success = last_success end # Updates the statuses of each logged in agent. Any statuses that are no longer active will be marked as closed, # and their closed time updated to current time. Any new statuses (belonging either to agents who logged in, or whose # status has changed) will be stored as new AgentStatus objects in the DB such that their open status is set to true. # # new_statuses should be an Array of AgentStatus objects representing the current state of each logged in agent def update_statuses(new_statuses) new_statuses ||= [] # Map statuses into a hash where the key is the agent ID and the result is the AgentStatus object for that agent @previous_statuses = Hash[AgentStatus.where(open: true).map { |status| [status.agent_id, status] }] @new_statuses = Hash[new_statuses.map { |status| [status.agent_id, status] }] @statuses_to_create = [] check_when_new_statuses_opened check_signed_out_agents update_new_and_changed_statuses save_updates end private # Assign created_at time for each new status to help determine whether the statuses are the same as those already stored in DB def check_when_new_statuses_opened @new_statuses.each { |_agent_id, status| status.created_at = Time.zone.at(@current_time.to_i - status.time_in_status.to_i) } end def check_signed_out_agents @previous_statuses.each do |agent_id, status| status.open = false unless @new_statuses[agent_id] end end # Create a new AgentStatus for each agent who either logged in since the last check, or whose status has changed def update_new_and_changed_statuses @new_statuses.each do |agent_id, status| # If agent didn't appear in the previous query, it means they must have signed in, so create a new status for them if !@previous_statuses[agent_id] save_new_status(status) else check_if_status_has_changed(agent_id, status) end end end def check_if_status_has_changed(agent_id, status) previous = @previous_statuses[agent_id] # The agent's status has changed if either the status name is different, or the time spent in it is less than before # Since AgentStatus data from OC is only updated every 5 seconds and there may be random delays, there is a 10 second buffer # to ensure that an existing status is not registered as a changed one. if previous.status != status.status || status.created_at > previous.created_at + 10.seconds previous.open = false save_new_status(status) end end def save_updates items_to_close = @previous_statuses.map { |_agent_id, status| status.id unless status.open } AgentStatus.where(id: items_to_close) .update_all(open: false, closed: @current_time, last_reliable_status: @last_success) unless items_to_close.empty? AgentStatus.create(@statuses_to_create) end # Adds status to list of statuses to be saved later def save_new_status(status) @statuses_to_create.push(agent_id: status.agent_id, status: status.status, open: true, created_at: @current_time) end end
[ "class", "AgentStatusUpdater", "include", "Now", "def", "initialize", "(", "current_time", ",", "last_success", ")", "@current_time", "=", "current_time", "@last_success", "=", "last_success", "end", "def", "update_statuses", "(", "new_statuses", ")", "new_statuses", "||=", "[", "]", "@previous_statuses", "=", "Hash", "[", "AgentStatus", ".", "where", "(", "open", ":", "true", ")", ".", "map", "{", "|", "status", "|", "[", "status", ".", "agent_id", ",", "status", "]", "}", "]", "@new_statuses", "=", "Hash", "[", "new_statuses", ".", "map", "{", "|", "status", "|", "[", "status", ".", "agent_id", ",", "status", "]", "}", "]", "@statuses_to_create", "=", "[", "]", "check_when_new_statuses_opened", "check_signed_out_agents", "update_new_and_changed_statuses", "save_updates", "end", "private", "def", "check_when_new_statuses_opened", "@new_statuses", ".", "each", "{", "|", "_agent_id", ",", "status", "|", "status", ".", "created_at", "=", "Time", ".", "zone", ".", "at", "(", "@current_time", ".", "to_i", "-", "status", ".", "time_in_status", ".", "to_i", ")", "}", "end", "def", "check_signed_out_agents", "@previous_statuses", ".", "each", "do", "|", "agent_id", ",", "status", "|", "status", ".", "open", "=", "false", "unless", "@new_statuses", "[", "agent_id", "]", "end", "end", "def", "update_new_and_changed_statuses", "@new_statuses", ".", "each", "do", "|", "agent_id", ",", "status", "|", "if", "!", "@previous_statuses", "[", "agent_id", "]", "save_new_status", "(", "status", ")", "else", "check_if_status_has_changed", "(", "agent_id", ",", "status", ")", "end", "end", "end", "def", "check_if_status_has_changed", "(", "agent_id", ",", "status", ")", "previous", "=", "@previous_statuses", "[", "agent_id", "]", "if", "previous", ".", "status", "!=", "status", ".", "status", "||", "status", ".", "created_at", ">", "previous", ".", "created_at", "+", "10", ".", "seconds", "previous", ".", "open", "=", "false", "save_new_status", "(", "status", ")", "end", "end", "def", "save_updates", "items_to_close", "=", "@previous_statuses", ".", "map", "{", "|", "_agent_id", ",", "status", "|", "status", ".", "id", "unless", "status", ".", "open", "}", "AgentStatus", ".", "where", "(", "id", ":", "items_to_close", ")", ".", "update_all", "(", "open", ":", "false", ",", "closed", ":", "@current_time", ",", "last_reliable_status", ":", "@last_success", ")", "unless", "items_to_close", ".", "empty?", "AgentStatus", ".", "create", "(", "@statuses_to_create", ")", "end", "def", "save_new_status", "(", "status", ")", "@statuses_to_create", ".", "push", "(", "agent_id", ":", "status", ".", "agent_id", ",", "status", ":", "status", ".", "status", ",", "open", ":", "true", ",", "created_at", ":", "@current_time", ")", "end", "end" ]
Provides functionality for tracking the statuses of Agents over time and storing the current status of logged in Agents in the DB.
[ "Provides", "functionality", "for", "tracking", "the", "statuses", "of", "Agents", "over", "time", "and", "storing", "the", "current", "status", "of", "logged", "in", "Agents", "in", "the", "DB", "." ]
[ "# Updates the statuses of each logged in agent. Any statuses that are no longer active will be marked as closed,", "# and their closed time updated to current time. Any new statuses (belonging either to agents who logged in, or whose", "# status has changed) will be stored as new AgentStatus objects in the DB such that their open status is set to true.", "#", "# new_statuses should be an Array of AgentStatus objects representing the current state of each logged in agent", "# Map statuses into a hash where the key is the agent ID and the result is the AgentStatus object for that agent", "# Assign created_at time for each new status to help determine whether the statuses are the same as those already stored in DB", "# Create a new AgentStatus for each agent who either logged in since the last check, or whose status has changed", "# If agent didn't appear in the previous query, it means they must have signed in, so create a new status for them", "# The agent's status has changed if either the status name is different, or the time spent in it is less than before", "# Since AgentStatus data from OC is only updated every 5 seconds and there may be random delays, there is a 10 second buffer", "# to ensure that an existing status is not registered as a changed one.", "# Adds status to list of statuses to be saved later" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
755
86
0a4a1cc0b249ce738940f0a113b864f784324880
davearonson/rubocop
lib/rubocop/cop/performance/inefficient_hash_search.rb
[ "MIT" ]
Ruby
InefficientHashSearch
# This cop checks for inefficient searching of keys and values within # hashes. # # `Hash#keys.include?` is less efficient than `Hash#key?` because # the former allocates a new array and then performs an O(n) search # through that array, while `Hash#key?` does not allocate any array and # performs a faster O(1) search for the key. # # `Hash#values.include?` is less efficient than `Hash#value?`. While they # both perform an O(n) search through all of the values, calling `values` # allocates a new array while using `value?` does not. # # @example # # bad # { a: 1, b: 2 }.keys.include?(:a) # { a: 1, b: 2 }.keys.include?(:z) # h = { a: 1, b: 2 }; h.keys.include?(100) # # # good # { a: 1, b: 2 }.key?(:a) # { a: 1, b: 2 }.has_key?(:z) # h = { a: 1, b: 2 }; h.key?(100) # # # bad # { a: 1, b: 2 }.values.include?(2) # { a: 1, b: 2 }.values.include?('garbage') # h = { a: 1, b: 2 }; h.values.include?(nil) # # # good # { a: 1, b: 2 }.value?(2) # { a: 1, b: 2 }.has_value?('garbage') # h = { a: 1, b: 2 }; h.value?(nil) #
This cop checks for inefficient searching of keys and values within hashes. `Hash#values.include?` is less efficient than `Hash#value?`. While they both perform an O(n) search through all of the values, calling `values` allocates a new array while using `value?` does not.
[ "This", "cop", "checks", "for", "inefficient", "searching", "of", "keys", "and", "values", "within", "hashes", ".", "`", "Hash#values", ".", "include?", "`", "is", "less", "efficient", "than", "`", "Hash#value?", "`", ".", "While", "they", "both", "perform", "an", "O", "(", "n", ")", "search", "through", "all", "of", "the", "values", "calling", "`", "values", "`", "allocates", "a", "new", "array", "while", "using", "`", "value?", "`", "does", "not", "." ]
class InefficientHashSearch < Cop def_node_matcher :inefficient_include?, <<-PATTERN (send (send $_ {:keys :values}) :include? _) PATTERN def on_send(node) inefficient_include?(node) do |receiver| return if receiver.nil? add_offense(node) end end def autocorrect(node) lambda do |corrector| # Replace `keys.include?` or `values.include?` with the appropriate # `key?`/`value?` method. corrector.replace( node.loc.expression, "#{autocorrect_hash_expression(node)}."\ "#{autocorrect_method(node)}(#{autocorrect_argument(node)})" ) end end private def message(node) "Use `##{autocorrect_method(node)}` instead of "\ "`##{current_method(node)}.include?`." end def autocorrect_method(node) case current_method(node) when :keys then use_long_method ? 'has_key?' : 'key?' when :values then use_long_method ? 'has_value?' : 'value?' end end def current_method(node) node.receiver.method_name end def use_long_method preferred_config = config.for_all_cops['Style/PreferredHashMethods'] preferred_config && preferred_config['EnforcedStyle'] == 'long' && preferred_config['Enabled'] end def autocorrect_argument(node) node.arguments.first.source end def autocorrect_hash_expression(node) node.receiver.receiver.source end end
[ "class", "InefficientHashSearch", "<", "Cop", "def_node_matcher", ":inefficient_include?", ",", "<<-PATTERN", "\n (send (send $_ {:keys :values}) :include? _)\n ", "PATTERN", "def", "on_send", "(", "node", ")", "inefficient_include?", "(", "node", ")", "do", "|", "receiver", "|", "return", "if", "receiver", ".", "nil?", "add_offense", "(", "node", ")", "end", "end", "def", "autocorrect", "(", "node", ")", "lambda", "do", "|", "corrector", "|", "corrector", ".", "replace", "(", "node", ".", "loc", ".", "expression", ",", "\"#{autocorrect_hash_expression(node)}.\"", "\"#{autocorrect_method(node)}(#{autocorrect_argument(node)})\"", ")", "end", "end", "private", "def", "message", "(", "node", ")", "\"Use `##{autocorrect_method(node)}` instead of \"", "\"`##{current_method(node)}.include?`.\"", "end", "def", "autocorrect_method", "(", "node", ")", "case", "current_method", "(", "node", ")", "when", ":keys", "then", "use_long_method", "?", "'has_key?'", ":", "'key?'", "when", ":values", "then", "use_long_method", "?", "'has_value?'", ":", "'value?'", "end", "end", "def", "current_method", "(", "node", ")", "node", ".", "receiver", ".", "method_name", "end", "def", "use_long_method", "preferred_config", "=", "config", ".", "for_all_cops", "[", "'Style/PreferredHashMethods'", "]", "preferred_config", "&&", "preferred_config", "[", "'EnforcedStyle'", "]", "==", "'long'", "&&", "preferred_config", "[", "'Enabled'", "]", "end", "def", "autocorrect_argument", "(", "node", ")", "node", ".", "arguments", ".", "first", ".", "source", "end", "def", "autocorrect_hash_expression", "(", "node", ")", "node", ".", "receiver", ".", "receiver", ".", "source", "end", "end" ]
This cop checks for inefficient searching of keys and values within hashes.
[ "This", "cop", "checks", "for", "inefficient", "searching", "of", "keys", "and", "values", "within", "hashes", "." ]
[ "# Replace `keys.include?` or `values.include?` with the appropriate", "# `key?`/`value?` method." ]
[ { "param": "Cop", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Cop", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "example", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
15
359
400
08166eec863799f1d3fddc90aa7b2502603e2930
apppackio/deploy-action
node_modules/@aws-sdk/client-ecr/dist/cjs/commands/PutReplicationConfigurationCommand.js
[ "MIT" ]
JavaScript
PutReplicationConfigurationCommand
/** * <p>Creates or updates the replication configuration for a registry. The existing * replication configuration for a repository can be retrieved with the <a>DescribeRegistry</a> API action. The first time the * PutReplicationConfiguration API is called, a service-linked IAM role is created in * your account for the replication process. For more information, see <a href="https://docs.aws.amazon.com/AmazonECR/latest/userguide/using-service-linked-roles.html">Using * Service-Linked Roles for Amazon ECR</a> in the * <i>Amazon Elastic Container Registry User Guide</i>.</p> * <note> * <p>When configuring cross-account replication, the destination account must grant the * source account permission to replicate. This permission is controlled using a * registry permissions policy. For more information, see <a>PutRegistryPolicy</a>.</p> * </note> */
Creates or updates the replication configuration for a registry. The existing replication configuration for a repository can be retrieved with the DescribeRegistry API action. The first time the PutReplicationConfiguration API is called, a service-linked IAM role is created in your account for the replication process. For more information, see Using Service-Linked Roles for Amazon ECR in the Amazon Elastic Container Registry User Guide. When configuring cross-account replication, the destination account must grant the source account permission to replicate. This permission is controlled using a registry permissions policy. For more information, see PutRegistryPolicy.
[ "Creates", "or", "updates", "the", "replication", "configuration", "for", "a", "registry", ".", "The", "existing", "replication", "configuration", "for", "a", "repository", "can", "be", "retrieved", "with", "the", "DescribeRegistry", "API", "action", ".", "The", "first", "time", "the", "PutReplicationConfiguration", "API", "is", "called", "a", "service", "-", "linked", "IAM", "role", "is", "created", "in", "your", "account", "for", "the", "replication", "process", ".", "For", "more", "information", "see", "Using", "Service", "-", "Linked", "Roles", "for", "Amazon", "ECR", "in", "the", "Amazon", "Elastic", "Container", "Registry", "User", "Guide", ".", "When", "configuring", "cross", "-", "account", "replication", "the", "destination", "account", "must", "grant", "the", "source", "account", "permission", "to", "replicate", ".", "This", "permission", "is", "controlled", "using", "a", "registry", "permissions", "policy", ".", "For", "more", "information", "see", "PutRegistryPolicy", "." ]
class PutReplicationConfigurationCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "ECRClient"; const commandName = "PutReplicationConfigurationCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.PutReplicationConfigurationRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.PutReplicationConfigurationResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_json1_1_1.serializeAws_json1_1PutReplicationConfigurationCommand(input, context); } deserialize(output, context) { return Aws_json1_1_1.deserializeAws_json1_1PutReplicationConfigurationCommand(output, context); } }
[ "class", "PutReplicationConfigurationCommand", "extends", "smithy_client_1", ".", "Command", "{", "constructor", "(", "input", ")", "{", "super", "(", ")", ";", "this", ".", "input", "=", "input", ";", "}", "resolveMiddleware", "(", "clientStack", ",", "configuration", ",", "options", ")", "{", "this", ".", "middlewareStack", ".", "use", "(", "middleware_serde_1", ".", "getSerdePlugin", "(", "configuration", ",", "this", ".", "serialize", ",", "this", ".", "deserialize", ")", ")", ";", "const", "stack", "=", "clientStack", ".", "concat", "(", "this", ".", "middlewareStack", ")", ";", "const", "{", "logger", "}", "=", "configuration", ";", "const", "clientName", "=", "\"ECRClient\"", ";", "const", "commandName", "=", "\"PutReplicationConfigurationCommand\"", ";", "const", "handlerExecutionContext", "=", "{", "logger", ",", "clientName", ",", "commandName", ",", "inputFilterSensitiveLog", ":", "models_0_1", ".", "PutReplicationConfigurationRequest", ".", "filterSensitiveLog", ",", "outputFilterSensitiveLog", ":", "models_0_1", ".", "PutReplicationConfigurationResponse", ".", "filterSensitiveLog", ",", "}", ";", "const", "{", "requestHandler", "}", "=", "configuration", ";", "return", "stack", ".", "resolve", "(", "(", "request", ")", "=>", "requestHandler", ".", "handle", "(", "request", ".", "request", ",", "options", "||", "{", "}", ")", ",", "handlerExecutionContext", ")", ";", "}", "serialize", "(", "input", ",", "context", ")", "{", "return", "Aws_json1_1_1", ".", "serializeAws_json1_1PutReplicationConfigurationCommand", "(", "input", ",", "context", ")", ";", "}", "deserialize", "(", "output", ",", "context", ")", "{", "return", "Aws_json1_1_1", ".", "deserializeAws_json1_1PutReplicationConfigurationCommand", "(", "output", ",", "context", ")", ";", "}", "}" ]
<p>Creates or updates the replication configuration for a registry.
[ "<p", ">", "Creates", "or", "updates", "the", "replication", "configuration", "for", "a", "registry", "." ]
[ "// Start section: command_properties", "// End section: command_properties", "// Start section: command_constructor", "// End section: command_constructor", "/**\n * @internal\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
304
204
3ec3a13e799bb480eba4155a38973410ff51deb7
seiggy/TrashBash
TrashBash/ScreenSystem/GameScreen.cs
[ "WTFPL" ]
C#
GameScreen
/// <summary> /// A screen is a single layer that has update and draw logic, and which /// can be combined with other layers to build up a complex menu system. /// For instance the main menu, the options menu, the "are you sure you /// want to quit" message box, and the main game itself are all implemented /// as screens. /// </summary>
A screen is a single layer that has update and draw logic, and which can be combined with other layers to build up a complex menu system. For instance the main menu, the options menu, the "are you sure you want to quit" message box, and the main game itself are all implemented as screens.
[ "A", "screen", "is", "a", "single", "layer", "that", "has", "update", "and", "draw", "logic", "and", "which", "can", "be", "combined", "with", "other", "layers", "to", "build", "up", "a", "complex", "menu", "system", ".", "For", "instance", "the", "main", "menu", "the", "options", "menu", "the", "\"", "are", "you", "sure", "you", "want", "to", "quit", "\"", "message", "box", "and", "the", "main", "game", "itself", "are", "all", "implemented", "as", "screens", "." ]
public abstract class GameScreen : IDisposable { private bool _debugViewEnabled; private bool _isExiting; private bool _otherScreenHasFocus; private PhysicsSimulator _physicsSimulator; private PhysicsSimulatorView _physicsSimulatorView; private ScreenState _screenState = ScreenState.TransitionOn; private TimeSpan _transitionOffTime = TimeSpan.Zero; private TimeSpan _transitionOnTime = TimeSpan.Zero; private float _transitionPosition = 1; protected bool FirstRun = true; protected GameScreen() { _physicsSimulator = new PhysicsSimulator(new Vector2(0, 0)); _physicsSimulatorView = new PhysicsSimulatorView(_physicsSimulator); } public PhysicsSimulator PhysicsSimulator { get { return _physicsSimulator; } set { _physicsSimulator = value; } } public PhysicsSimulatorView PhysicsSimulatorView { get { return _physicsSimulatorView; } set { _physicsSimulatorView = value; } } public bool DebugViewEnabled { get { return _debugViewEnabled; } } public bool IsPopup { get; protected set; } public TimeSpan TransitionOnTime { get { return _transitionOnTime; } protected set { _transitionOnTime = value; } } public TimeSpan TransitionOffTime { get { return _transitionOffTime; } protected set { _transitionOffTime = value; } } public float TransitionPosition { get { return _transitionPosition; } protected set { _transitionPosition = value; } } public byte TransitionAlpha { get { return (byte) (255 - TransitionPosition*255); } } public ScreenState ScreenState { get { return _screenState; } protected set { _screenState = value; } } public bool IsExiting { get { return _isExiting; } protected set { _isExiting = value; } } public bool IsActive { get { return !_otherScreenHasFocus && (_screenState == ScreenState.TransitionOn || _screenState == ScreenState.Active); } } public ScreenManager ScreenManager { get; internal set; } #region IDisposable Members public virtual void Dispose() { } #endregion public virtual void Initialize() { } public virtual void LoadContent() { _physicsSimulatorView.LoadContent(ScreenManager.GraphicsDevice, ScreenManager.ContentManager); } public virtual void UnloadContent() { _physicsSimulator.Clear(); } public virtual void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { _otherScreenHasFocus = otherScreenHasFocus; if (_isExiting) { _screenState = ScreenState.TransitionOff; if (!UpdateTransition(gameTime, _transitionOffTime, 1)) { ScreenManager.RemoveScreen(this); _isExiting = false; } } else if (coveredByOtherScreen) { if (UpdateTransition(gameTime, _transitionOffTime, 1)) { _screenState = ScreenState.TransitionOff; } else { _screenState = ScreenState.Hidden; } } else { if (UpdateTransition(gameTime, _transitionOnTime, -1)) { _screenState = ScreenState.TransitionOn; } else { _screenState = ScreenState.Active; } } } public virtual void UpdatePhysics(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { if (!coveredByOtherScreen && !otherScreenHasFocus) PhysicsSimulator.Update(gameTime.ElapsedGameTime.Milliseconds*.001f); } private bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction) { float transitionDelta; if (time == TimeSpan.Zero) transitionDelta = 1; else transitionDelta = (float) (gameTime.ElapsedGameTime.TotalMilliseconds/ time.TotalMilliseconds); _transitionPosition += transitionDelta*direction; if ((_transitionPosition <= 0) || (_transitionPosition >= 1)) { _transitionPosition = MathHelper.Clamp(_transitionPosition, 0, 1); return false; } return true; } public virtual void HandleInput(InputState input) { if (input.P1LastGamePadState.Buttons.RightStick != ButtonState.Pressed && input.P1CurrentGamePadState.Buttons.RightStick == ButtonState.Pressed) { _debugViewEnabled = !_debugViewEnabled; _physicsSimulator.EnableDiagnostics = _debugViewEnabled; } if (!input.LastKeyboardState.IsKeyDown(Keys.F1) && input.CurrentKeyboardState.IsKeyDown(Keys.F1)) { _debugViewEnabled = !_debugViewEnabled; _physicsSimulator.EnableDiagnostics = _debugViewEnabled; } } public virtual void Draw(GameTime gameTime) { if (_debugViewEnabled) { ScreenManager.SpriteBatch.Begin(SpriteBlendMode.AlphaBlend); _physicsSimulatorView.Draw(ScreenManager.SpriteBatch); ScreenManager.SpriteBatch.End(); } } public void ExitScreen() { if (TransitionOffTime == TimeSpan.Zero) { ScreenManager.RemoveScreen(this); } else { _isExiting = true; } } }
[ "public", "abstract", "class", "GameScreen", ":", "IDisposable", "{", "private", "bool", "_debugViewEnabled", ";", "private", "bool", "_isExiting", ";", "private", "bool", "_otherScreenHasFocus", ";", "private", "PhysicsSimulator", "_physicsSimulator", ";", "private", "PhysicsSimulatorView", "_physicsSimulatorView", ";", "private", "ScreenState", "_screenState", "=", "ScreenState", ".", "TransitionOn", ";", "private", "TimeSpan", "_transitionOffTime", "=", "TimeSpan", ".", "Zero", ";", "private", "TimeSpan", "_transitionOnTime", "=", "TimeSpan", ".", "Zero", ";", "private", "float", "_transitionPosition", "=", "1", ";", "protected", "bool", "FirstRun", "=", "true", ";", "protected", "GameScreen", "(", ")", "{", "_physicsSimulator", "=", "new", "PhysicsSimulator", "(", "new", "Vector2", "(", "0", ",", "0", ")", ")", ";", "_physicsSimulatorView", "=", "new", "PhysicsSimulatorView", "(", "_physicsSimulator", ")", ";", "}", "public", "PhysicsSimulator", "PhysicsSimulator", "{", "get", "{", "return", "_physicsSimulator", ";", "}", "set", "{", "_physicsSimulator", "=", "value", ";", "}", "}", "public", "PhysicsSimulatorView", "PhysicsSimulatorView", "{", "get", "{", "return", "_physicsSimulatorView", ";", "}", "set", "{", "_physicsSimulatorView", "=", "value", ";", "}", "}", "public", "bool", "DebugViewEnabled", "{", "get", "{", "return", "_debugViewEnabled", ";", "}", "}", "public", "bool", "IsPopup", "{", "get", ";", "protected", "set", ";", "}", "public", "TimeSpan", "TransitionOnTime", "{", "get", "{", "return", "_transitionOnTime", ";", "}", "protected", "set", "{", "_transitionOnTime", "=", "value", ";", "}", "}", "public", "TimeSpan", "TransitionOffTime", "{", "get", "{", "return", "_transitionOffTime", ";", "}", "protected", "set", "{", "_transitionOffTime", "=", "value", ";", "}", "}", "public", "float", "TransitionPosition", "{", "get", "{", "return", "_transitionPosition", ";", "}", "protected", "set", "{", "_transitionPosition", "=", "value", ";", "}", "}", "public", "byte", "TransitionAlpha", "{", "get", "{", "return", "(", "byte", ")", "(", "255", "-", "TransitionPosition", "*", "255", ")", ";", "}", "}", "public", "ScreenState", "ScreenState", "{", "get", "{", "return", "_screenState", ";", "}", "protected", "set", "{", "_screenState", "=", "value", ";", "}", "}", "public", "bool", "IsExiting", "{", "get", "{", "return", "_isExiting", ";", "}", "protected", "set", "{", "_isExiting", "=", "value", ";", "}", "}", "public", "bool", "IsActive", "{", "get", "{", "return", "!", "_otherScreenHasFocus", "&&", "(", "_screenState", "==", "ScreenState", ".", "TransitionOn", "||", "_screenState", "==", "ScreenState", ".", "Active", ")", ";", "}", "}", "public", "ScreenManager", "ScreenManager", "{", "get", ";", "internal", "set", ";", "}", "region", " IDisposable Members", "public", "virtual", "void", "Dispose", "(", ")", "{", "}", "endregion", "public", "virtual", "void", "Initialize", "(", ")", "{", "}", "public", "virtual", "void", "LoadContent", "(", ")", "{", "_physicsSimulatorView", ".", "LoadContent", "(", "ScreenManager", ".", "GraphicsDevice", ",", "ScreenManager", ".", "ContentManager", ")", ";", "}", "public", "virtual", "void", "UnloadContent", "(", ")", "{", "_physicsSimulator", ".", "Clear", "(", ")", ";", "}", "public", "virtual", "void", "Update", "(", "GameTime", "gameTime", ",", "bool", "otherScreenHasFocus", ",", "bool", "coveredByOtherScreen", ")", "{", "_otherScreenHasFocus", "=", "otherScreenHasFocus", ";", "if", "(", "_isExiting", ")", "{", "_screenState", "=", "ScreenState", ".", "TransitionOff", ";", "if", "(", "!", "UpdateTransition", "(", "gameTime", ",", "_transitionOffTime", ",", "1", ")", ")", "{", "ScreenManager", ".", "RemoveScreen", "(", "this", ")", ";", "_isExiting", "=", "false", ";", "}", "}", "else", "if", "(", "coveredByOtherScreen", ")", "{", "if", "(", "UpdateTransition", "(", "gameTime", ",", "_transitionOffTime", ",", "1", ")", ")", "{", "_screenState", "=", "ScreenState", ".", "TransitionOff", ";", "}", "else", "{", "_screenState", "=", "ScreenState", ".", "Hidden", ";", "}", "}", "else", "{", "if", "(", "UpdateTransition", "(", "gameTime", ",", "_transitionOnTime", ",", "-", "1", ")", ")", "{", "_screenState", "=", "ScreenState", ".", "TransitionOn", ";", "}", "else", "{", "_screenState", "=", "ScreenState", ".", "Active", ";", "}", "}", "}", "public", "virtual", "void", "UpdatePhysics", "(", "GameTime", "gameTime", ",", "bool", "otherScreenHasFocus", ",", "bool", "coveredByOtherScreen", ")", "{", "if", "(", "!", "coveredByOtherScreen", "&&", "!", "otherScreenHasFocus", ")", "PhysicsSimulator", ".", "Update", "(", "gameTime", ".", "ElapsedGameTime", ".", "Milliseconds", "*", ".001f", ")", ";", "}", "private", "bool", "UpdateTransition", "(", "GameTime", "gameTime", ",", "TimeSpan", "time", ",", "int", "direction", ")", "{", "float", "transitionDelta", ";", "if", "(", "time", "==", "TimeSpan", ".", "Zero", ")", "transitionDelta", "=", "1", ";", "else", "transitionDelta", "=", "(", "float", ")", "(", "gameTime", ".", "ElapsedGameTime", ".", "TotalMilliseconds", "/", "time", ".", "TotalMilliseconds", ")", ";", "_transitionPosition", "+=", "transitionDelta", "*", "direction", ";", "if", "(", "(", "_transitionPosition", "<=", "0", ")", "||", "(", "_transitionPosition", ">=", "1", ")", ")", "{", "_transitionPosition", "=", "MathHelper", ".", "Clamp", "(", "_transitionPosition", ",", "0", ",", "1", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "public", "virtual", "void", "HandleInput", "(", "InputState", "input", ")", "{", "if", "(", "input", ".", "P1LastGamePadState", ".", "Buttons", ".", "RightStick", "!=", "ButtonState", ".", "Pressed", "&&", "input", ".", "P1CurrentGamePadState", ".", "Buttons", ".", "RightStick", "==", "ButtonState", ".", "Pressed", ")", "{", "_debugViewEnabled", "=", "!", "_debugViewEnabled", ";", "_physicsSimulator", ".", "EnableDiagnostics", "=", "_debugViewEnabled", ";", "}", "if", "(", "!", "input", ".", "LastKeyboardState", ".", "IsKeyDown", "(", "Keys", ".", "F1", ")", "&&", "input", ".", "CurrentKeyboardState", ".", "IsKeyDown", "(", "Keys", ".", "F1", ")", ")", "{", "_debugViewEnabled", "=", "!", "_debugViewEnabled", ";", "_physicsSimulator", ".", "EnableDiagnostics", "=", "_debugViewEnabled", ";", "}", "}", "public", "virtual", "void", "Draw", "(", "GameTime", "gameTime", ")", "{", "if", "(", "_debugViewEnabled", ")", "{", "ScreenManager", ".", "SpriteBatch", ".", "Begin", "(", "SpriteBlendMode", ".", "AlphaBlend", ")", ";", "_physicsSimulatorView", ".", "Draw", "(", "ScreenManager", ".", "SpriteBatch", ")", ";", "ScreenManager", ".", "SpriteBatch", ".", "End", "(", ")", ";", "}", "}", "public", "void", "ExitScreen", "(", ")", "{", "if", "(", "TransitionOffTime", "==", "TimeSpan", ".", "Zero", ")", "{", "ScreenManager", ".", "RemoveScreen", "(", "this", ")", ";", "}", "else", "{", "_isExiting", "=", "true", ";", "}", "}", "}" ]
A screen is a single layer that has update and draw logic, and which can be combined with other layers to build up a complex menu system.
[ "A", "screen", "is", "a", "single", "layer", "that", "has", "update", "and", "draw", "logic", "and", "which", "can", "be", "combined", "with", "other", "layers", "to", "build", "up", "a", "complex", "menu", "system", "." ]
[ "//Note: This should not really be here. It should be in an engine instead that takes care of physics", "/// <summary>", "/// Normally when one screen is brought up over the top of another,", "/// the first screen will transition off to make room for the new", "/// one. This property indicates whether the screen is only a small", "/// popup, in which case screens underneath it do not need to bother", "/// transitioning off.", "/// </summary>", "/// <summary>", "/// Indicates how long the screen takes to", "/// transition on when it is activated.", "/// </summary>", "/// <summary>", "/// Indicates how long the screen takes to", "/// transition off when it is deactivated.", "/// </summary>", "/// <summary>", "/// Gets the current position of the screen transition, ranging", "/// from zero (fully active, no transition) to one (transitioned", "/// fully off to nothing).", "/// </summary>", "/// <summary>", "/// Gets the current alpha of the screen transition, ranging", "/// from 255 (fully active, no transition) to 0 (transitioned", "/// fully off to nothing).", "/// </summary>", "/// <summary>", "/// Gets the current screen transition state.", "/// </summary>", "/// <summary>", "/// There are two possible reasons why a screen might be transitioning", "/// off. It could be temporarily going away to make room for another", "/// screen that is on top of it, or it could be going away for good.", "/// This property indicates whether the screen is exiting for real:", "/// if set, the screen will automatically remove itself as soon as the", "/// transition finishes.", "/// </summary>", "/// <summary>", "/// Checks whether this screen is active and can respond to user input.", "/// </summary>", "/// <summary>", "/// Gets the manager that this screen belongs to.", "/// </summary>", "/// <summary>", "/// Load graphics content for the screen.", "/// </summary>", "/// <summary>", "/// Unload content for the screen.", "/// </summary>", "/// <summary>", "/// Allows the screen to run logic, such as updating the transition position.", "/// Unlike <see cref=\"HandleInput\"/>, this method is called regardless of whether the screen", "/// is active, hidden, or in the middle of a transition.", "/// </summary>", "// If the screen is going away to die, it should transition off.", "// When the transition finishes, remove the screen.", "// If the screen is covered by another, it should transition off.", "// Still busy transitioning.", "// Transition finished!", "// Otherwise the screen should transition on and become active.", "// Still busy transitioning.", "// Transition finished!", "/// <summary>", "/// Helper for updating the screen transition position.", "/// </summary>", "// How much should we move by?", "// Update the transition position.", "// Did we reach the end of the transition?", "// Otherwise we are still busy transitioning.", "/// <summary>", "/// Allows the screen to handle user input. Unlike Update, this method", "/// is only called when the screen is active, and not when some other", "/// screen has taken the focus.", "/// </summary>", "//Xbox", "//Windows", "/// <summary>", "/// This is called when the screen should draw itself.", "/// </summary>", "/// <summary>", "/// Tells the screen to go away. Unlike <see cref=\"ScreenManager\"/>.RemoveScreen, which", "/// instantly kills the screen, this method respects the transition timings", "/// and will give the screen a chance to gradually transition off.", "/// </summary>", "// If the screen has a zero transition time, remove it immediately.", "// Otherwise flag that it should transition off and then exit." ]
[ { "param": "IDisposable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IDisposable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
1,200
79
d423dd97669bcf5d7fb93745ce5f34b5752d8ff7
cyrilleberger/mxnet.rb
lib/mxnet/gluon/data/sampler.rb
[ "MIT" ]
Ruby
BatchSampler
# Wraps another Sampler and return mini-batches of samples. # # sampler = MXNet::Gluon::Data.SequentialSampler(10) # batch_sampler = MXNet::Gluon::Data.BatchSampler(sampler, 3, :keep) # batch_sampler.to_a # => [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] #
Wraps another Sampler and return mini-batches of samples.
[ "Wraps", "another", "Sampler", "and", "return", "mini", "-", "batches", "of", "samples", "." ]
class BatchSampler < Sampler # Creates a new instance. # # ====Parameters # # +sampler+:: (Sampler) # The source Sampler. # +batch_size+:: (integer) # Size of mini-batch. # +last_batch+:: (+:keep+, +:discard+, +:rollover+) # Specifies how the last batch is handled if # +batch_size+ does not evenly divide sequence # length. If +:keep+, the last batch will be # returned directly, but will contain fewer # elements than +batch_size+ requires. If # +:discard+, the last batch will be discarded. # If +:rollover+, the remaining elements will # be rolled over to the next iteration. # def initialize(sampler, batch_size, last_batch: :keep) unless [:keep, :discard, :rollover].include?(last_batch) raise ArgumentError, 'last_batch must be either :keep, :discard, or :rollover' end @sampler = sampler @batch_size = batch_size @last_batch = last_batch @prev = [] end def length case @last_batch when :discard @sampler.length.div(@batch_size) when :keep (@sampler.length + @batch_size - 1).div(@batch_size) when :rollover (@sampler.length + @prev.length).div(@batch_size) end end def each return enum_for unless block_given? batch, @prev = @prev, [] @sampler.each do |i| batch << i if batch.length == @batch_size yield batch batch = [] end end unless batch.empty? case @last_batch when :discard when :keep yield batch when :rollover @prev = batch end end end end
[ "class", "BatchSampler", "<", "Sampler", "def", "initialize", "(", "sampler", ",", "batch_size", ",", "last_batch", ":", ":keep", ")", "unless", "[", ":keep", ",", ":discard", ",", ":rollover", "]", ".", "include?", "(", "last_batch", ")", "raise", "ArgumentError", ",", "'last_batch must be either :keep, :discard, or :rollover'", "end", "@sampler", "=", "sampler", "@batch_size", "=", "batch_size", "@last_batch", "=", "last_batch", "@prev", "=", "[", "]", "end", "def", "length", "case", "@last_batch", "when", ":discard", "@sampler", ".", "length", ".", "div", "(", "@batch_size", ")", "when", ":keep", "(", "@sampler", ".", "length", "+", "@batch_size", "-", "1", ")", ".", "div", "(", "@batch_size", ")", "when", ":rollover", "(", "@sampler", ".", "length", "+", "@prev", ".", "length", ")", ".", "div", "(", "@batch_size", ")", "end", "end", "def", "each", "return", "enum_for", "unless", "block_given?", "batch", ",", "@prev", "=", "@prev", ",", "[", "]", "@sampler", ".", "each", "do", "|", "i", "|", "batch", "<<", "i", "if", "batch", ".", "length", "==", "@batch_size", "yield", "batch", "batch", "=", "[", "]", "end", "end", "unless", "batch", ".", "empty?", "case", "@last_batch", "when", ":discard", "when", ":keep", "yield", "batch", "when", ":rollover", "@prev", "=", "batch", "end", "end", "end", "end" ]
Wraps another Sampler and return mini-batches of samples.
[ "Wraps", "another", "Sampler", "and", "return", "mini", "-", "batches", "of", "samples", "." ]
[ "# Creates a new instance.", "#", "# ====Parameters", "#", "# +sampler+:: (Sampler)", "# The source Sampler.", "# +batch_size+:: (integer)", "# Size of mini-batch.", "# +last_batch+:: (+:keep+, +:discard+, +:rollover+)", "# Specifies how the last batch is handled if", "# +batch_size+ does not evenly divide sequence", "# length. If +:keep+, the last batch will be", "# returned directly, but will contain fewer", "# elements than +batch_size+ requires. If", "# +:discard+, the last batch will be discarded.", "# If +:rollover+, the remaining elements will", "# be rolled over to the next iteration.", "#" ]
[ { "param": "Sampler", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Sampler", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
455
95
c2ffb2ba9a7225e7a8c65e6292335e0e1ba54eb4
stoddabr/chairbot_ui_rework
server/scripts/BrettControllers/robot_controller.py
[ "Apache-2.0" ]
Python
RobotController
A class used to track multi-robot information This is the main class used by the outside world Attributes ---------- robots : dictionary < RobotEntity > dictionary of robots indexed by fiducial/robot id originId : int fiducial id of the origin reference used originLocation : tuple < int, int > x,y coordinates of the origin fiducial socket : ??? socket used to send commands Public Methods ------- updateRobotLocation( id: int , coords: tuple ) updates a specific robot's location command #TODO
A class used to track multi-robot information This is the main class used by the outside world Attributes Public Methods updateRobotLocation( id: int , coords: tuple ) updates a specific robot's location command #TODO
[ "A", "class", "used", "to", "track", "multi", "-", "robot", "information", "This", "is", "the", "main", "class", "used", "by", "the", "outside", "world", "Attributes", "Public", "Methods", "updateRobotLocation", "(", "id", ":", "int", "coords", ":", "tuple", ")", "updates", "a", "specific", "robot", "'", "s", "location", "command", "#TODO" ]
class RobotController: """ A class used to track multi-robot information This is the main class used by the outside world Attributes ---------- robots : dictionary < RobotEntity > dictionary of robots indexed by fiducial/robot id originId : int fiducial id of the origin reference used originLocation : tuple < int, int > x,y coordinates of the origin fiducial socket : ??? socket used to send commands Public Methods ------- updateRobotLocation( id: int , coords: tuple ) updates a specific robot's location command #TODO """ def __init__(self, fiducialIds, originId, originCoords=None): """ Parameters ---------- robotIds : array < int > array of fiducial/robot ids that may be active in the scene originId : int fiducial id of the origin point originCoords : tuple <int, int>, optional x, y location """ self.originId = originId self.originCoords = originCoords self.robots = {x: RobotEntity(x) for x in fiducialIds} def updateRobotLocation(self, robotId, coords): """ Updates a robots saved location which can then be used to calculate robot movements Parameters ---------- robotId : int robot fiducial id coords : tuple < int, int, float > (x,y,angle degrees) representing the location of the robot """ # if robot doesn't exist, initialize one if not self.robots.has_key(robotId): self.robots[robotId] = RobotEntity(robotId) # update coords self.robots[robotId].updateCoords(coords) def updateRobotGoal(self, robotId, coords): """ Updates a robots saved goal which can then be used to calculate robot movements Parameters ---------- robotId : int robot fiducial id coords : tuple < int, int > (x,y) representing the location of the goal """ # if robot doesn't exist, initialize one if not self.robots.has_key(robotId): self.robots[robotId] = RobotEntity(robotId) self.robots[robotId].updateGoal(coords) def command(self, robotId, newRobotCoords=None): # TODO finish writing """Calculates a robots best move in order to move toward it's goal based on it's last saved coordinates this method can be called right after setting the robots location and that command can be sent in a loop until the next time a location is passed Parameters ---------- robotId : int The sound the animal makes (default is None) newRobotCoords : tuple <int,int,int>, optional x,y,angle coordinates for this robot's new location. If not provided, then last saved location of the robot will be used Raises ------ SystemError If robotId not found """ if not self.robots.has_key(robotId): raise SystemError( 'Command sent to a robotId not initialized: {}' .format(robotId) ) # update robot coord if defined if newRobotCoords != None: self.updateRobotGoal(robotId, newRobotCoords) # prepare and send move command to robot self.robots[robotId].move()
[ "class", "RobotController", ":", "def", "__init__", "(", "self", ",", "fiducialIds", ",", "originId", ",", "originCoords", "=", "None", ")", ":", "\"\"\"\n Parameters\n ----------\n robotIds : array < int >\n array of fiducial/robot ids that may be active in the scene\n originId : int\n fiducial id of the origin point\n originCoords : tuple <int, int>, optional\n x, y location\n \"\"\"", "self", ".", "originId", "=", "originId", "self", ".", "originCoords", "=", "originCoords", "self", ".", "robots", "=", "{", "x", ":", "RobotEntity", "(", "x", ")", "for", "x", "in", "fiducialIds", "}", "def", "updateRobotLocation", "(", "self", ",", "robotId", ",", "coords", ")", ":", "\"\"\" Updates a robots saved location which can then be used to calculate\n robot movements\n\n Parameters\n ----------\n robotId : int\n robot fiducial id\n coords : tuple < int, int, float >\n (x,y,angle degrees) representing the location of the robot\n \"\"\"", "if", "not", "self", ".", "robots", ".", "has_key", "(", "robotId", ")", ":", "self", ".", "robots", "[", "robotId", "]", "=", "RobotEntity", "(", "robotId", ")", "self", ".", "robots", "[", "robotId", "]", ".", "updateCoords", "(", "coords", ")", "def", "updateRobotGoal", "(", "self", ",", "robotId", ",", "coords", ")", ":", "\"\"\" Updates a robots saved goal which can then be used to calculate\n robot movements\n\n Parameters\n ----------\n robotId : int\n robot fiducial id\n coords : tuple < int, int >\n (x,y) representing the location of the goal\n \"\"\"", "if", "not", "self", ".", "robots", ".", "has_key", "(", "robotId", ")", ":", "self", ".", "robots", "[", "robotId", "]", "=", "RobotEntity", "(", "robotId", ")", "self", ".", "robots", "[", "robotId", "]", ".", "updateGoal", "(", "coords", ")", "def", "command", "(", "self", ",", "robotId", ",", "newRobotCoords", "=", "None", ")", ":", "\"\"\"Calculates a robots best move in order to move toward it's goal\n based on it's last saved coordinates\n\n this method can be called right after setting the robots location\n and that command can be sent in a loop until the next time a location is\n passed\n\n Parameters\n ----------\n robotId : int\n The sound the animal makes (default is None)\n newRobotCoords : tuple <int,int,int>, optional\n x,y,angle coordinates for this robot's new location. \n If not provided, then last saved location of the robot will be used\n\n Raises\n ------\n SystemError\n If robotId not found\n \"\"\"", "if", "not", "self", ".", "robots", ".", "has_key", "(", "robotId", ")", ":", "raise", "SystemError", "(", "'Command sent to a robotId not initialized: {}'", ".", "format", "(", "robotId", ")", ")", "if", "newRobotCoords", "!=", "None", ":", "self", ".", "updateRobotGoal", "(", "robotId", ",", "newRobotCoords", ")", "self", ".", "robots", "[", "robotId", "]", ".", "move", "(", ")" ]
A class used to track multi-robot information This is the main class used by the outside world
[ "A", "class", "used", "to", "track", "multi", "-", "robot", "information", "This", "is", "the", "main", "class", "used", "by", "the", "outside", "world" ]
[ "\"\"\"\n A class used to track multi-robot information\n\n This is the main class used by the outside world\n\n Attributes\n ----------\n robots : dictionary < RobotEntity >\n dictionary of robots indexed by fiducial/robot id\n originId : int\n fiducial id of the origin reference used\n originLocation : tuple < int, int >\n x,y coordinates of the origin fiducial\n socket : ???\n socket used to send commands\n\n Public Methods\n -------\n updateRobotLocation( id: int , coords: tuple )\n updates a specific robot's location\n command #TODO \n \"\"\"", "\"\"\"\n Parameters\n ----------\n robotIds : array < int >\n array of fiducial/robot ids that may be active in the scene\n originId : int\n fiducial id of the origin point\n originCoords : tuple <int, int>, optional\n x, y location\n \"\"\"", "\"\"\" Updates a robots saved location which can then be used to calculate\n robot movements\n\n Parameters\n ----------\n robotId : int\n robot fiducial id\n coords : tuple < int, int, float >\n (x,y,angle degrees) representing the location of the robot\n \"\"\"", "# if robot doesn't exist, initialize one", "# update coords", "\"\"\" Updates a robots saved goal which can then be used to calculate\n robot movements\n\n Parameters\n ----------\n robotId : int\n robot fiducial id\n coords : tuple < int, int >\n (x,y) representing the location of the goal\n \"\"\"", "# if robot doesn't exist, initialize one", "# TODO finish writing", "\"\"\"Calculates a robots best move in order to move toward it's goal\n based on it's last saved coordinates\n\n this method can be called right after setting the robots location\n and that command can be sent in a loop until the next time a location is\n passed\n\n Parameters\n ----------\n robotId : int\n The sound the animal makes (default is None)\n newRobotCoords : tuple <int,int,int>, optional\n x,y,angle coordinates for this robot's new location. \n If not provided, then last saved location of the robot will be used\n\n Raises\n ------\n SystemError\n If robotId not found\n \"\"\"", "# update robot coord if defined", "# prepare and send move command to robot" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
760
133
bb4e1609f2b928bc671a5b8693f9f2f3fa828ce0
jekakm/captainfailure
app/controllers/manageusers_controller.rb
[ "Apache-2.0" ]
Ruby
ManageusersController
# Copyright 2015 Evgeniy Gurinovich # # 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.
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.
[ "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", "." ]
class ManageusersController < ApplicationController before_action :check_permission before_action :find_user, only: [:show, :edit, :update, :destroy] before_action :set_active #get /users/manage def index @users = User.all render 'manageusers/index' end def show end def new @user = User.new end #post /users/manage def create if params[:user][:generate_password] == '1' @user = User.new @user.name = params[:user][:name] @user.email = params[:user][:email] @user.is_admin = params[:user][:is_admin] generated_password = SecureRandom.urlsafe_base64(8) @user.password = generated_password @user.password_confirmation = generated_password @user.save RegistrationMailer.send_info(@user.email, request.domain, generated_password).deliver_later else @user = User.create(params.require(:user).permit(:name, :email, :password, :password_confirmation, :is_admin)) end if @user.errors.empty? redirect_to '/users/manage' else @save_errors = '' @user.errors.messages.each_key { |key| @save_errors << "#{key} #{@user.errors.messages[key][0]}" } render 'new' end end #get /users/manage/:id def edit end #put /users/manage/:id def update if params[:user][:generate_password] == '1' @user.name = params[:user][:name] @user.email = params[:user][:email] @user.is_admin = params[:user][:is_admin] generated_password = SecureRandom.urlsafe_base64(8) @user.password = generated_password @user.password_confirmation = generated_password @user.save RegistrationMailer.send_info(@user.email, Rails.configuration.domain_in_mail, generated_password).deliver_later else if params[:user][:password] == '' and params[:user][:password_confirmation] == '' update_params = :name, :email, :is_admin else update_params = :name, :email, :password, :password_confirmation, :is_admin end @user.update_attributes(params.require(:user).permit(update_params)) end if @user.errors.empty? redirect_to '/users/manage' else @save_errors = '' @user.errors.messages.each_key { |key| @save_errors << "#{key} #{@user.errors.messages[key][0]}" } render 'edit' end end #delete /users/manage/:id def destroy @user.destroy redirect_to action: 'index' end private def find_user @user = User.where('id = ?', params[:id]).first end def check_permission unless current_user.is_admin render 'permission_error', status: 403 end end def set_active @active = 'users' end end
[ "class", "ManageusersController", "<", "ApplicationController", "before_action", ":check_permission", "before_action", ":find_user", ",", "only", ":", "[", ":show", ",", ":edit", ",", ":update", ",", ":destroy", "]", "before_action", ":set_active", "def", "index", "@users", "=", "User", ".", "all", "render", "'manageusers/index'", "end", "def", "show", "end", "def", "new", "@user", "=", "User", ".", "new", "end", "def", "create", "if", "params", "[", ":user", "]", "[", ":generate_password", "]", "==", "'1'", "@user", "=", "User", ".", "new", "@user", ".", "name", "=", "params", "[", ":user", "]", "[", ":name", "]", "@user", ".", "email", "=", "params", "[", ":user", "]", "[", ":email", "]", "@user", ".", "is_admin", "=", "params", "[", ":user", "]", "[", ":is_admin", "]", "generated_password", "=", "SecureRandom", ".", "urlsafe_base64", "(", "8", ")", "@user", ".", "password", "=", "generated_password", "@user", ".", "password_confirmation", "=", "generated_password", "@user", ".", "save", "RegistrationMailer", ".", "send_info", "(", "@user", ".", "email", ",", "request", ".", "domain", ",", "generated_password", ")", ".", "deliver_later", "else", "@user", "=", "User", ".", "create", "(", "params", ".", "require", "(", ":user", ")", ".", "permit", "(", ":name", ",", ":email", ",", ":password", ",", ":password_confirmation", ",", ":is_admin", ")", ")", "end", "if", "@user", ".", "errors", ".", "empty?", "redirect_to", "'/users/manage'", "else", "@save_errors", "=", "''", "@user", ".", "errors", ".", "messages", ".", "each_key", "{", "|", "key", "|", "@save_errors", "<<", "\"#{key} #{@user.errors.messages[key][0]}\"", "}", "render", "'new'", "end", "end", "def", "edit", "end", "def", "update", "if", "params", "[", ":user", "]", "[", ":generate_password", "]", "==", "'1'", "@user", ".", "name", "=", "params", "[", ":user", "]", "[", ":name", "]", "@user", ".", "email", "=", "params", "[", ":user", "]", "[", ":email", "]", "@user", ".", "is_admin", "=", "params", "[", ":user", "]", "[", ":is_admin", "]", "generated_password", "=", "SecureRandom", ".", "urlsafe_base64", "(", "8", ")", "@user", ".", "password", "=", "generated_password", "@user", ".", "password_confirmation", "=", "generated_password", "@user", ".", "save", "RegistrationMailer", ".", "send_info", "(", "@user", ".", "email", ",", "Rails", ".", "configuration", ".", "domain_in_mail", ",", "generated_password", ")", ".", "deliver_later", "else", "if", "params", "[", ":user", "]", "[", ":password", "]", "==", "''", "and", "params", "[", ":user", "]", "[", ":password_confirmation", "]", "==", "''", "update_params", "=", ":name", ",", ":email", ",", ":is_admin", "else", "update_params", "=", ":name", ",", ":email", ",", ":password", ",", ":password_confirmation", ",", ":is_admin", "end", "@user", ".", "update_attributes", "(", "params", ".", "require", "(", ":user", ")", ".", "permit", "(", "update_params", ")", ")", "end", "if", "@user", ".", "errors", ".", "empty?", "redirect_to", "'/users/manage'", "else", "@save_errors", "=", "''", "@user", ".", "errors", ".", "messages", ".", "each_key", "{", "|", "key", "|", "@save_errors", "<<", "\"#{key} #{@user.errors.messages[key][0]}\"", "}", "render", "'edit'", "end", "end", "def", "destroy", "@user", ".", "destroy", "redirect_to", "action", ":", "'index'", "end", "private", "def", "find_user", "@user", "=", "User", ".", "where", "(", "'id = ?'", ",", "params", "[", ":id", "]", ")", ".", "first", "end", "def", "check_permission", "unless", "current_user", ".", "is_admin", "render", "'permission_error'", ",", "status", ":", "403", "end", "end", "def", "set_active", "@active", "=", "'users'", "end", "end" ]
Copyright 2015 Evgeniy Gurinovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
[ "Copyright", "2015", "Evgeniy", "Gurinovich", "Licensed", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", "." ]
[ "#get /users/manage", "#post /users/manage", "#get /users/manage/:id", "#put /users/manage/:id", "#delete /users/manage/:id" ]
[ { "param": "ApplicationController", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ApplicationController", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
692
133
437357fd30183b92f47e3ac86fd470c271064db6
yangzhinong/Open-XML-SDK
src/DocumentFormat.OpenXml/GeneratedCode/schemas_openxmlformats_org_presentationml_2006_main.g.cs
[ "MIT" ]
C#
AnimateScale
/// <summary> /// <para>Animate Scale.</para> /// <para>This class is available in Office 2007 or above.</para> /// <para>When the object is serialized out as xml, it's qualified name is p:animScale.</para> /// </summary> /// <remark> /// <para>The following table lists the possible child types:</para> /// <list type="bullet"> /// <item><description>CommonBehavior &lt;p:cBhvr></description></item> /// <item><description>ByPosition &lt;p:by></description></item> /// <item><description>FromPosition &lt;p:from></description></item> /// <item><description>ToPosition &lt;p:to></description></item> /// </list> /// </remark>
Animate Scale.This class is available in Office 2007 or above.When the object is serialized out as xml, it's qualified name is p:animScale.
[ "Animate", "Scale", ".", "This", "class", "is", "available", "in", "Office", "2007", "or", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "it", "'", "s", "qualified", "name", "is", "p", ":", "animScale", "." ]
[ChildElementInfo(typeof(CommonBehavior))] [ChildElementInfo(typeof(ByPosition))] [ChildElementInfo(typeof(FromPosition))] [ChildElementInfo(typeof(ToPosition))] [SchemaAttr(24, "animScale")] [OfficeAvailability(FileFormatVersions.Office2007)] public partial class AnimateScale : OpenXmlCompositeElement { public AnimateScale() : base() { } public AnimateScale(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } public AnimateScale(params OpenXmlElement[] childElements) : base(childElements) { } public AnimateScale(string outerXml) : base(outerXml) { } [SchemaAttr(0, "zoomContents")] [Index(0)] public BooleanValue ZoomContents { get; set; } [OfficeAvailability(FileFormatVersions.Office2010)] [NumberValidator(MinInclusive = 0L, MaxInclusive = 100000L)] [SchemaAttr(49, "bounceEnd")] [Index(1)] public Int32Value BounceEnd { get; set; } public CommonBehavior CommonBehavior { get => GetElement<CommonBehavior>(); set => SetElement(value); } public ByPosition ByPosition { get => GetElement<ByPosition>(); set => SetElement(value); } public FromPosition FromPosition { get => GetElement<FromPosition>(); set => SetElement(value); } public ToPosition ToPosition { get => GetElement<ToPosition>(); set => SetElement(value); } private static readonly CompiledParticle _constraint = new CompositeParticle(ParticleType.Sequence, 1, 1) { new ElementParticle(typeof(DocumentFormat.OpenXml.Presentation.CommonBehavior), 1, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Presentation.ByPosition), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Presentation.FromPosition), 0, 1), new ElementParticle(typeof(DocumentFormat.OpenXml.Presentation.ToPosition), 0, 1) }.Compile(); internal override CompiledParticle CompiledParticle => _constraint; public override OpenXmlElement CloneNode(bool deep) => CloneImp<AnimateScale>(deep); }
[ "[", "ChildElementInfo", "(", "typeof", "(", "CommonBehavior", ")", ")", "]", "[", "ChildElementInfo", "(", "typeof", "(", "ByPosition", ")", ")", "]", "[", "ChildElementInfo", "(", "typeof", "(", "FromPosition", ")", ")", "]", "[", "ChildElementInfo", "(", "typeof", "(", "ToPosition", ")", ")", "]", "[", "SchemaAttr", "(", "24", ",", "\"", "animScale", "\"", ")", "]", "[", "OfficeAvailability", "(", "FileFormatVersions", ".", "Office2007", ")", "]", "public", "partial", "class", "AnimateScale", ":", "OpenXmlCompositeElement", "{", "public", "AnimateScale", "(", ")", ":", "base", "(", ")", "{", "}", "public", "AnimateScale", "(", "IEnumerable", "<", "OpenXmlElement", ">", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "AnimateScale", "(", "params", "OpenXmlElement", "[", "]", "childElements", ")", ":", "base", "(", "childElements", ")", "{", "}", "public", "AnimateScale", "(", "string", "outerXml", ")", ":", "base", "(", "outerXml", ")", "{", "}", "[", "SchemaAttr", "(", "0", ",", "\"", "zoomContents", "\"", ")", "]", "[", "Index", "(", "0", ")", "]", "public", "BooleanValue", "ZoomContents", "{", "get", ";", "set", ";", "}", "[", "OfficeAvailability", "(", "FileFormatVersions", ".", "Office2010", ")", "]", "[", "NumberValidator", "(", "MinInclusive", "=", "0L", ",", "MaxInclusive", "=", "100000L", ")", "]", "[", "SchemaAttr", "(", "49", ",", "\"", "bounceEnd", "\"", ")", "]", "[", "Index", "(", "1", ")", "]", "public", "Int32Value", "BounceEnd", "{", "get", ";", "set", ";", "}", "public", "CommonBehavior", "CommonBehavior", "{", "get", "=>", "GetElement", "<", "CommonBehavior", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "public", "ByPosition", "ByPosition", "{", "get", "=>", "GetElement", "<", "ByPosition", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "public", "FromPosition", "FromPosition", "{", "get", "=>", "GetElement", "<", "FromPosition", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "public", "ToPosition", "ToPosition", "{", "get", "=>", "GetElement", "<", "ToPosition", ">", "(", ")", ";", "set", "=>", "SetElement", "(", "value", ")", ";", "}", "private", "static", "readonly", "CompiledParticle", "_constraint", "=", "new", "CompositeParticle", "(", "ParticleType", ".", "Sequence", ",", "1", ",", "1", ")", "{", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Presentation", ".", "CommonBehavior", ")", ",", "1", ",", "1", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Presentation", ".", "ByPosition", ")", ",", "0", ",", "1", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Presentation", ".", "FromPosition", ")", ",", "0", ",", "1", ")", ",", "new", "ElementParticle", "(", "typeof", "(", "DocumentFormat", ".", "OpenXml", ".", "Presentation", ".", "ToPosition", ")", ",", "0", ",", "1", ")", "}", ".", "Compile", "(", ")", ";", "internal", "override", "CompiledParticle", "CompiledParticle", "=>", "_constraint", ";", "public", "override", "OpenXmlElement", "CloneNode", "(", "bool", "deep", ")", "=>", "CloneImp", "<", "AnimateScale", ">", "(", "deep", ")", ";", "}" ]
Animate Scale.This class is available in Office 2007 or above.When the object is serialized out as xml, it's qualified name is p:animScale.
[ "Animate", "Scale", ".", "This", "class", "is", "available", "in", "Office", "2007", "or", "above", ".", "When", "the", "object", "is", "serialized", "out", "as", "xml", "it", "'", "s", "qualified", "name", "is", "p", ":", "animScale", "." ]
[ "/// <summary>", "/// Initializes a new instance of the AnimateScale class.", "/// </summary>", "/// <summary>", "/// Initializes a new instance of the AnimateScale class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the AnimateScale class with the specified child elements.", "/// </summary>", "/// <param name=\"childElements\">Specifies the child elements.</param>", "/// <summary>", "/// Initializes a new instance of the AnimateScale class from outer XML.", "/// </summary>", "/// <param name=\"outerXml\">Specifies the outer XML of the element.</param>", "/// <summary>", "/// <para>zoomContents</para>", "/// <para>Represents the following attribute in the schema: zoomContents</para>", "/// </summary>", "/// <summary>", "/// <para>bounceEnd, this property is only available in Office2010, Office2013, Office2016</para>", "/// <para>Represents the following attribute in the schema: p14:bounceEnd</para>", "/// </summary>", "/// <remark>", "/// xmlns:p14=http://schemas.microsoft.com/office/powerpoint/2010/main", "/// </remark>", "/// <summary>", "/// <para>CommonBehavior.</para>", "/// <para>Represents the following element tag in the schema: p:cBhvr.</para>", "/// </summary>", "/// <remark>", "/// xmlns:p = http://schemas.openxmlformats.org/presentationml/2006/main", "/// </remark>", "/// <summary>", "/// <para>ByPosition.</para>", "/// <para>Represents the following element tag in the schema: p:by.</para>", "/// </summary>", "/// <remark>", "/// xmlns:p = http://schemas.openxmlformats.org/presentationml/2006/main", "/// </remark>", "/// <summary>", "/// <para>FromPosition.</para>", "/// <para>Represents the following element tag in the schema: p:from.</para>", "/// </summary>", "/// <remark>", "/// xmlns:p = http://schemas.openxmlformats.org/presentationml/2006/main", "/// </remark>", "/// <summary>", "/// <para>ToPosition.</para>", "/// <para>Represents the following element tag in the schema: p:to.</para>", "/// </summary>", "/// <remark>", "/// xmlns:p = http://schemas.openxmlformats.org/presentationml/2006/main", "/// </remark>", "/// <inheritdoc/>" ]
[ { "param": "OpenXmlCompositeElement", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "OpenXmlCompositeElement", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "remark", "docstring": "The following table lists the possible child types.\n\nCommonBehavior \nByPosition \nFromPosition ToPosition ", "docstring_tokens": [ "The", "following", "table", "lists", "the", "possible", "child", "types", ".", "CommonBehavior", "ByPosition", "FromPosition", "ToPosition" ] } ] }
false
17
502
171
179d81e99e4fdb21328341e1bf0c4073e33f288e
Jumpscale/sandbox_linux
sandbox/lib/pythonbin/asyncssh/asn1.py
[ "Apache-2.0" ]
Python
BitString
A string of bits This object can be initialized either with a byte string and an optional count of the number of least-significant bits in the last byte which should not be included in the value, or with a string consisting only of the digits '0' and '1'. An optional 'named' flag can also be set, indicating that the BitString was specified with named bits, indicating that the proper DER encoding of it should strip any trailing zeroes.
A string of bits This object can be initialized either with a byte string and an optional count of the number of least-significant bits in the last byte which should not be included in the value, or with a string consisting only of the digits '0' and '1'. An optional 'named' flag can also be set, indicating that the BitString was specified with named bits, indicating that the proper DER encoding of it should strip any trailing zeroes.
[ "A", "string", "of", "bits", "This", "object", "can", "be", "initialized", "either", "with", "a", "byte", "string", "and", "an", "optional", "count", "of", "the", "number", "of", "least", "-", "significant", "bits", "in", "the", "last", "byte", "which", "should", "not", "be", "included", "in", "the", "value", "or", "with", "a", "string", "consisting", "only", "of", "the", "digits", "'", "0", "'", "and", "'", "1", "'", ".", "An", "optional", "'", "named", "'", "flag", "can", "also", "be", "set", "indicating", "that", "the", "BitString", "was", "specified", "with", "named", "bits", "indicating", "that", "the", "proper", "DER", "encoding", "of", "it", "should", "strip", "any", "trailing", "zeroes", "." ]
class BitString: """A string of bits This object can be initialized either with a byte string and an optional count of the number of least-significant bits in the last byte which should not be included in the value, or with a string consisting only of the digits '0' and '1'. An optional 'named' flag can also be set, indicating that the BitString was specified with named bits, indicating that the proper DER encoding of it should strip any trailing zeroes. """ def __init__(self, value, unused=0, named=False): if unused < 0 or unused > 7: raise ASN1EncodeError('Unused bit count must be between 0 and 7') if isinstance(value, bytes): if unused: if not value: raise ASN1EncodeError('Can\'t have unused bits with empty ' 'value') elif value[-1] & ((1 << unused) - 1): raise ASN1EncodeError('Unused bits in value should be ' 'zero') elif isinstance(value, str): if unused: raise ASN1EncodeError('Unused bit count should not be set ' 'when providing a string') used = len(value) % 8 unused = 8 - used if used else 0 value += unused * '0' value = bytes(int(value[i:i+8], 2) for i in range(0, len(value), 8)) else: raise ASN1EncodeError('Unexpected type of bit string value') if named: while value and not value[-1] & (1 << unused): unused += 1 if unused == 8: value = value[:-1] unused = 0 self.value = value self.unused = unused def __str__(self): result = ''.join(bin(b)[2:].zfill(8) for b in self.value) if self.unused: result = result[:-self.unused] return result def __repr__(self): return "BitString('%s')" % self def __eq__(self, other): return (isinstance(other, type(self)) and self.value == other.value and self.unused == other.unused) def __hash__(self): return hash((self.value, self.unused)) def encode(self): """Encode a DER bit string""" return bytes((self.unused,)) + self.value @classmethod def decode(cls, constructed, content): """Decode a DER bit string""" if constructed: raise ASN1DecodeError('BIT STRING should not be constructed') if not content or content[0] > 7: raise ASN1DecodeError('Invalid unused bit count') return cls(content[1:], unused=content[0])
[ "class", "BitString", ":", "def", "__init__", "(", "self", ",", "value", ",", "unused", "=", "0", ",", "named", "=", "False", ")", ":", "if", "unused", "<", "0", "or", "unused", ">", "7", ":", "raise", "ASN1EncodeError", "(", "'Unused bit count must be between 0 and 7'", ")", "if", "isinstance", "(", "value", ",", "bytes", ")", ":", "if", "unused", ":", "if", "not", "value", ":", "raise", "ASN1EncodeError", "(", "'Can\\'t have unused bits with empty '", "'value'", ")", "elif", "value", "[", "-", "1", "]", "&", "(", "(", "1", "<<", "unused", ")", "-", "1", ")", ":", "raise", "ASN1EncodeError", "(", "'Unused bits in value should be '", "'zero'", ")", "elif", "isinstance", "(", "value", ",", "str", ")", ":", "if", "unused", ":", "raise", "ASN1EncodeError", "(", "'Unused bit count should not be set '", "'when providing a string'", ")", "used", "=", "len", "(", "value", ")", "%", "8", "unused", "=", "8", "-", "used", "if", "used", "else", "0", "value", "+=", "unused", "*", "'0'", "value", "=", "bytes", "(", "int", "(", "value", "[", "i", ":", "i", "+", "8", "]", ",", "2", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "value", ")", ",", "8", ")", ")", "else", ":", "raise", "ASN1EncodeError", "(", "'Unexpected type of bit string value'", ")", "if", "named", ":", "while", "value", "and", "not", "value", "[", "-", "1", "]", "&", "(", "1", "<<", "unused", ")", ":", "unused", "+=", "1", "if", "unused", "==", "8", ":", "value", "=", "value", "[", ":", "-", "1", "]", "unused", "=", "0", "self", ".", "value", "=", "value", "self", ".", "unused", "=", "unused", "def", "__str__", "(", "self", ")", ":", "result", "=", "''", ".", "join", "(", "bin", "(", "b", ")", "[", "2", ":", "]", ".", "zfill", "(", "8", ")", "for", "b", "in", "self", ".", "value", ")", "if", "self", ".", "unused", ":", "result", "=", "result", "[", ":", "-", "self", ".", "unused", "]", "return", "result", "def", "__repr__", "(", "self", ")", ":", "return", "\"BitString('%s')\"", "%", "self", "def", "__eq__", "(", "self", ",", "other", ")", ":", "return", "(", "isinstance", "(", "other", ",", "type", "(", "self", ")", ")", "and", "self", ".", "value", "==", "other", ".", "value", "and", "self", ".", "unused", "==", "other", ".", "unused", ")", "def", "__hash__", "(", "self", ")", ":", "return", "hash", "(", "(", "self", ".", "value", ",", "self", ".", "unused", ")", ")", "def", "encode", "(", "self", ")", ":", "\"\"\"Encode a DER bit string\"\"\"", "return", "bytes", "(", "(", "self", ".", "unused", ",", ")", ")", "+", "self", ".", "value", "@", "classmethod", "def", "decode", "(", "cls", ",", "constructed", ",", "content", ")", ":", "\"\"\"Decode a DER bit string\"\"\"", "if", "constructed", ":", "raise", "ASN1DecodeError", "(", "'BIT STRING should not be constructed'", ")", "if", "not", "content", "or", "content", "[", "0", "]", ">", "7", ":", "raise", "ASN1DecodeError", "(", "'Invalid unused bit count'", ")", "return", "cls", "(", "content", "[", "1", ":", "]", ",", "unused", "=", "content", "[", "0", "]", ")" ]
A string of bits This object can be initialized either with a byte string and an optional count of the number of least-significant bits in the last byte which should not be included in the value, or with a string consisting only of the digits '0' and '1'.
[ "A", "string", "of", "bits", "This", "object", "can", "be", "initialized", "either", "with", "a", "byte", "string", "and", "an", "optional", "count", "of", "the", "number", "of", "least", "-", "significant", "bits", "in", "the", "last", "byte", "which", "should", "not", "be", "included", "in", "the", "value", "or", "with", "a", "string", "consisting", "only", "of", "the", "digits", "'", "0", "'", "and", "'", "1", "'", "." ]
[ "\"\"\"A string of bits\n\n This object can be initialized either with a byte string and an\n optional count of the number of least-significant bits in the last\n byte which should not be included in the value, or with a string\n consisting only of the digits '0' and '1'.\n\n An optional 'named' flag can also be set, indicating that the\n BitString was specified with named bits, indicating that the proper\n DER encoding of it should strip any trailing zeroes.\n\n \"\"\"", "\"\"\"Encode a DER bit string\"\"\"", "\"\"\"Decode a DER bit string\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
618
105
e350a540a4908d54902f74f59a6636d1cb136305
ctagg/ebay_shopping
lib/ebay_shopping.rb
[ "MIT" ]
Ruby
Item
# # The EbayShopping::Item class is used for the items returned by common ebay search methods (e.g. FindItemsAdvanced, GetSingleItem, etc). # It provides a number of ways of accessing the item's attributes, with reader methods named after the most common attributes, and an # all-purpose [] method for less-frequent ones, e.g. item["Storefront"]. #
The EbayShopping::Item class is used for the items returned by common ebay search methods . It provides a number of ways of accessing the item's attributes, with reader methods named after the most common attributes, and an all-purpose [] method for less-frequent ones, e.g. item["Storefront"].
[ "The", "EbayShopping", "::", "Item", "class", "is", "used", "for", "the", "items", "returned", "by", "common", "ebay", "search", "methods", ".", "It", "provides", "a", "number", "of", "ways", "of", "accessing", "the", "item", "'", "s", "attributes", "with", "reader", "methods", "named", "after", "the", "most", "common", "attributes", "and", "an", "all", "-", "purpose", "[]", "method", "for", "less", "-", "frequent", "ones", "e", ".", "g", ".", "item", "[", "\"", "Storefront", "\"", "]", "." ]
class Item < GenericItem attr_reader :bid_count, :description, :gallery_url, :item_id, :primary_category_name, :view_item_url_for_natural_search def converted_current_price EbayShopping::Money.new(@converted_current_price) if @converted_current_price end # This is calculated from the end time (and ignores the time_left attribute, which is stored in the IS8601 duration format, which I haven't seen a # conversion for, though it's prob easy to do) def time_left duration = (end_time - Time.now).to_i result, res = [], 0 [["days", 86400], ["hours", 3600], ["minutes", 60]].each do |i| res, duration = duration.divmod(i[1]) result << "#{res} #{i[0]}" if res > 0 end result.join(", ") end # Returns the end time of the item's auction as UTC time def end_time Time.xmlschema(@end_time).getlocal end end
[ "class", "Item", "<", "GenericItem", "attr_reader", ":bid_count", ",", ":description", ",", ":gallery_url", ",", ":item_id", ",", ":primary_category_name", ",", ":view_item_url_for_natural_search", "def", "converted_current_price", "EbayShopping", "::", "Money", ".", "new", "(", "@converted_current_price", ")", "if", "@converted_current_price", "end", "def", "time_left", "duration", "=", "(", "end_time", "-", "Time", ".", "now", ")", ".", "to_i", "result", ",", "res", "=", "[", "]", ",", "0", "[", "[", "\"days\"", ",", "86400", "]", ",", "[", "\"hours\"", ",", "3600", "]", ",", "[", "\"minutes\"", ",", "60", "]", "]", ".", "each", "do", "|", "i", "|", "res", ",", "duration", "=", "duration", ".", "divmod", "(", "i", "[", "1", "]", ")", "result", "<<", "\"#{res} #{i[0]}\"", "if", "res", ">", "0", "end", "result", ".", "join", "(", "\", \"", ")", "end", "def", "end_time", "Time", ".", "xmlschema", "(", "@end_time", ")", ".", "getlocal", "end", "end" ]
The EbayShopping::Item class is used for the items returned by common ebay search methods (e.g.
[ "The", "EbayShopping", "::", "Item", "class", "is", "used", "for", "the", "items", "returned", "by", "common", "ebay", "search", "methods", "(", "e", ".", "g", "." ]
[ "# This is calculated from the end time (and ignores the time_left attribute, which is stored in the IS8601 duration format, which I haven't seen a ", "# conversion for, though it's prob easy to do)", "# Returns the end time of the item's auction as UTC time" ]
[ { "param": "GenericItem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "GenericItem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
255
83
ed0e9851e217f7da23b84d94134a5c5c3eba7f5f
sven-n/OpenMU
src/Persistence/Initialization/Terrains.Designer.cs
[ "MIT" ]
C#
Terrains
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Terrains { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Terrains() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MUnique.OpenMU.Persistence.Initialization.Terrains", typeof(Terrains).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static byte[] Terrain1 { get { object obj = ResourceManager.GetObject("Terrain1", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain10 { get { object obj = ResourceManager.GetObject("Terrain10", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain11 { get { object obj = ResourceManager.GetObject("Terrain11", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain12 { get { object obj = ResourceManager.GetObject("Terrain12", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain19 { get { object obj = ResourceManager.GetObject("Terrain19", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain2 { get { object obj = ResourceManager.GetObject("Terrain2", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain25 { get { object obj = ResourceManager.GetObject("Terrain25", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain3 { get { object obj = ResourceManager.GetObject("Terrain3", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain31 { get { object obj = ResourceManager.GetObject("Terrain31", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain32 { get { object obj = ResourceManager.GetObject("Terrain32", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain33 { get { object obj = ResourceManager.GetObject("Terrain33", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain34 { get { object obj = ResourceManager.GetObject("Terrain34", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain34_Close { get { object obj = ResourceManager.GetObject("Terrain34_Close", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain35 { get { object obj = ResourceManager.GetObject("Terrain35", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain35_OCCUPIED { get { object obj = ResourceManager.GetObject("Terrain35_OCCUPIED", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain35_PEACE { get { object obj = ResourceManager.GetObject("Terrain35_PEACE", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain35_WAR { get { object obj = ResourceManager.GetObject("Terrain35_WAR", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain36 { get { object obj = ResourceManager.GetObject("Terrain36", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain37 { get { object obj = ResourceManager.GetObject("Terrain37", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain38 { get { object obj = ResourceManager.GetObject("Terrain38", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain39 { get { object obj = ResourceManager.GetObject("Terrain39", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain4 { get { object obj = ResourceManager.GetObject("Terrain4", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain40 { get { object obj = ResourceManager.GetObject("Terrain40", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain40_CLOSE { get { object obj = ResourceManager.GetObject("Terrain40_CLOSE", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain40_OPEN { get { object obj = ResourceManager.GetObject("Terrain40_OPEN", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain41 { get { object obj = ResourceManager.GetObject("Terrain41", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain42 { get { object obj = ResourceManager.GetObject("Terrain42", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain43 { get { object obj = ResourceManager.GetObject("Terrain43", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain44 { get { object obj = ResourceManager.GetObject("Terrain44", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain46 { get { object obj = ResourceManager.GetObject("Terrain46", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain47 { get { object obj = ResourceManager.GetObject("Terrain47", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain5 { get { object obj = ResourceManager.GetObject("Terrain5", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain51 { get { object obj = ResourceManager.GetObject("Terrain51", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain52 { get { object obj = ResourceManager.GetObject("Terrain52", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain53 { get { object obj = ResourceManager.GetObject("Terrain53", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain54 { get { object obj = ResourceManager.GetObject("Terrain54", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain55 { get { object obj = ResourceManager.GetObject("Terrain55", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain56 { get { object obj = ResourceManager.GetObject("Terrain56", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain57 { get { object obj = ResourceManager.GetObject("Terrain57", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain58 { get { object obj = ResourceManager.GetObject("Terrain58", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain59 { get { object obj = ResourceManager.GetObject("Terrain59", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain6 { get { object obj = ResourceManager.GetObject("Terrain6", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain61 { get { object obj = ResourceManager.GetObject("Terrain61", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain62 { get { object obj = ResourceManager.GetObject("Terrain62", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain63 { get { object obj = ResourceManager.GetObject("Terrain63", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain64 { get { object obj = ResourceManager.GetObject("Terrain64", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain65 { get { object obj = ResourceManager.GetObject("Terrain65", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain66 { get { object obj = ResourceManager.GetObject("Terrain66", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain67 { get { object obj = ResourceManager.GetObject("Terrain67", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain68 { get { object obj = ResourceManager.GetObject("Terrain68", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain69 { get { object obj = ResourceManager.GetObject("Terrain69", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain7 { get { object obj = ResourceManager.GetObject("Terrain7", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain70 { get { object obj = ResourceManager.GetObject("Terrain70", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain71 { get { object obj = ResourceManager.GetObject("Terrain71", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain72 { get { object obj = ResourceManager.GetObject("Terrain72", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain73 { get { object obj = ResourceManager.GetObject("Terrain73", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain74 { get { object obj = ResourceManager.GetObject("Terrain74", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain75 { get { object obj = ResourceManager.GetObject("Terrain75", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain78 { get { object obj = ResourceManager.GetObject("Terrain78", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain79 { get { object obj = ResourceManager.GetObject("Terrain79", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain8 { get { object obj = ResourceManager.GetObject("Terrain8", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain80 { get { object obj = ResourceManager.GetObject("Terrain80", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain81 { get { object obj = ResourceManager.GetObject("Terrain81", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain82 { get { object obj = ResourceManager.GetObject("Terrain82", resourceCulture); return ((byte[])(obj)); } } internal static byte[] Terrain9 { get { object obj = ResourceManager.GetObject("Terrain9", resourceCulture); return ((byte[])(obj)); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Terrains", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Terrains", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "MUnique.OpenMU.Persistence.Initialization.Terrains", "\"", ",", "typeof", "(", "Terrains", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain1", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain1", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain10", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain10", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain11", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain11", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain12", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain12", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain19", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain19", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain2", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain2", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain25", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain25", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain3", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain3", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain31", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain31", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain32", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain32", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain33", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain33", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain34", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain34", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain34_Close", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain34_Close", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain35", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain35", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain35_OCCUPIED", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain35_OCCUPIED", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain35_PEACE", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain35_PEACE", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain35_WAR", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain35_WAR", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain36", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain36", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain37", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain37", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain38", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain38", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain39", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain39", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain4", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain4", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain40", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain40", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain40_CLOSE", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain40_CLOSE", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain40_OPEN", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain40_OPEN", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain41", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain41", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain42", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain42", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain43", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain43", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain44", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain44", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain46", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain46", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain47", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain47", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain5", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain5", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain51", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain51", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain52", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain52", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain53", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain53", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain54", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain54", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain55", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain55", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain56", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain56", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain57", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain57", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain58", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain58", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain59", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain59", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain6", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain6", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain61", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain61", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain62", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain62", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain63", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain63", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain64", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain64", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain65", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain65", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain66", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain66", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain67", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain67", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain68", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain68", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain69", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain69", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain7", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain7", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain70", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain70", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain71", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain71", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain72", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain72", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain73", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain73", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain74", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain74", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain75", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain75", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain78", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain78", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain79", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain79", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain8", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain8", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain80", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain80", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain81", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain81", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain82", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain82", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "internal", "static", "byte", "[", "]", "Terrain9", "{", "get", "{", "object", "obj", "=", "ResourceManager", ".", "GetObject", "(", "\"", "Terrain9", "\"", ",", "resourceCulture", ")", ";", "return", "(", "(", "byte", "[", "]", ")", "(", "obj", ")", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>", "/// <summary>", "/// Looks up a localized resource of type System.Byte[].", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
2,742
84
5caa1bd0a9926e0b11f4157b9831eb706468eff4
Matej-Chmel/space-invaders-java
src/space_invaders/game/collisions/Bruteforce.java
[ "CC0-1.0" ]
Java
Bruteforce
/* * this collision class checks every worldObject with each that can be hit by that object * for 55 enemies and 4 players * we end up with roughly 3520 comparisons per frame * if 55 enemy bullets and 30 player bullets are present at the time of frame * * we also have to add 1 comparison against out of canvas state for each bullet * in total that is 3605 comparisons per frame * below 5000, it is considered fine for mid-end computer */
this collision class checks every worldObject with each that can be hit by that object for 55 enemies and 4 players we end up with roughly 3520 comparisons per frame if 55 enemy bullets and 30 player bullets are present at the time of frame we also have to add 1 comparison against out of canvas state for each bullet in total that is 3605 comparisons per frame below 5000, it is considered fine for mid-end computer
[ "this", "collision", "class", "checks", "every", "worldObject", "with", "each", "that", "can", "be", "hit", "by", "that", "object", "for", "55", "enemies", "and", "4", "players", "we", "end", "up", "with", "roughly", "3520", "comparisons", "per", "frame", "if", "55", "enemy", "bullets", "and", "30", "player", "bullets", "are", "present", "at", "the", "time", "of", "frame", "we", "also", "have", "to", "add", "1", "comparison", "against", "out", "of", "canvas", "state", "for", "each", "bullet", "in", "total", "that", "is", "3605", "comparisons", "per", "frame", "below", "5000", "it", "is", "considered", "fine", "for", "mid", "-", "end", "computer" ]
public class Bruteforce extends CollisionComputer { private Size world_size; public Bruteforce(BattleGroup battleGroup, PlayerManager PM) { super(battleGroup, PM); world_size = CanvasManager.getGameCM().getSize(); } @Override public void computeCollisions() { // player bullets <-> enemies for (Bullet bullet : playerBullets) { if (bullet.isAlive()) { enemyLabel: for (ArrayList<Enemy> enemylist : lists_of_enemies) { for (Enemy enemy : new ArrayList<>(enemylist)) { if (enemy.isAlive()) if (checkCollisionBetween(bullet, enemy)) break enemyLabel; } } } } // enemy bullets <-> players for (Bullet bullet : enemyBullets) { if (bullet.isAlive()) { for (Player player : players) if (checkCollisionBetween(bullet, player)) break; } } // enemy bullets <-> player bullets for (Bullet enemyBullet : enemyBullets) { if (enemyBullet.isAlive()) { for (Bullet playerBullet : playerBullets) { if (playerBullet.isAlive()) if (checkCollisionBetween(enemyBullet, playerBullet)) break; } } } removeEmptyLists(); } @Override public void removeBulletsOutOfCanvas() { for (Bullet bullet : enemyBullets) if (bullet.isOutOfCanvas(world_size)) bullet.hit(false); for (Bullet bullet : playerBullets) if (bullet.isOutOfCanvas(world_size)) bullet.hit(true); } }
[ "public", "class", "Bruteforce", "extends", "CollisionComputer", "{", "private", "Size", "world_size", ";", "public", "Bruteforce", "(", "BattleGroup", "battleGroup", ",", "PlayerManager", "PM", ")", "{", "super", "(", "battleGroup", ",", "PM", ")", ";", "world_size", "=", "CanvasManager", ".", "getGameCM", "(", ")", ".", "getSize", "(", ")", ";", "}", "@", "Override", "public", "void", "computeCollisions", "(", ")", "{", "for", "(", "Bullet", "bullet", ":", "playerBullets", ")", "{", "if", "(", "bullet", ".", "isAlive", "(", ")", ")", "{", "enemyLabel", ":", "for", "(", "ArrayList", "<", "Enemy", ">", "enemylist", ":", "lists_of_enemies", ")", "{", "for", "(", "Enemy", "enemy", ":", "new", "ArrayList", "<", ">", "(", "enemylist", ")", ")", "{", "if", "(", "enemy", ".", "isAlive", "(", ")", ")", "if", "(", "checkCollisionBetween", "(", "bullet", ",", "enemy", ")", ")", "break", "enemyLabel", ";", "}", "}", "}", "}", "for", "(", "Bullet", "bullet", ":", "enemyBullets", ")", "{", "if", "(", "bullet", ".", "isAlive", "(", ")", ")", "{", "for", "(", "Player", "player", ":", "players", ")", "if", "(", "checkCollisionBetween", "(", "bullet", ",", "player", ")", ")", "break", ";", "}", "}", "for", "(", "Bullet", "enemyBullet", ":", "enemyBullets", ")", "{", "if", "(", "enemyBullet", ".", "isAlive", "(", ")", ")", "{", "for", "(", "Bullet", "playerBullet", ":", "playerBullets", ")", "{", "if", "(", "playerBullet", ".", "isAlive", "(", ")", ")", "if", "(", "checkCollisionBetween", "(", "enemyBullet", ",", "playerBullet", ")", ")", "break", ";", "}", "}", "}", "removeEmptyLists", "(", ")", ";", "}", "@", "Override", "public", "void", "removeBulletsOutOfCanvas", "(", ")", "{", "for", "(", "Bullet", "bullet", ":", "enemyBullets", ")", "if", "(", "bullet", ".", "isOutOfCanvas", "(", "world_size", ")", ")", "bullet", ".", "hit", "(", "false", ")", ";", "for", "(", "Bullet", "bullet", ":", "playerBullets", ")", "if", "(", "bullet", ".", "isOutOfCanvas", "(", "world_size", ")", ")", "bullet", ".", "hit", "(", "true", ")", ";", "}", "}" ]
this collision class checks every worldObject with each that can be hit by that object for 55 enemies and 4 players we end up with roughly 3520 comparisons per frame if 55 enemy bullets and 30 player bullets are present at the time of frame
[ "this", "collision", "class", "checks", "every", "worldObject", "with", "each", "that", "can", "be", "hit", "by", "that", "object", "for", "55", "enemies", "and", "4", "players", "we", "end", "up", "with", "roughly", "3520", "comparisons", "per", "frame", "if", "55", "enemy", "bullets", "and", "30", "player", "bullets", "are", "present", "at", "the", "time", "of", "frame" ]
[ "// player bullets <-> enemies", "// enemy bullets <-> players", "// enemy bullets <-> player bullets" ]
[ { "param": "CollisionComputer", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "CollisionComputer", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
19
364
117
551393016293c707269296d8da10d77d79667f7f
srcarter3/awips2
edexOsgi/com.raytheon.uf.common.registry.schemas.ebxml/src/oasis/names/tc/ebxml/regrep/xsd/rim/v4/VersionInfoType.java
[ "Apache-2.0" ]
Java
VersionInfoType
/** * Represents information about the version of the object it is describing. * * <p> * Java class for VersionInfoType complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="VersionInfoType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="versionName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="userVersionName" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * <pre> * * SOFTWARE HISTORY * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 2012 bphillip Initial implementation * 10/17/2013 1682 bphillip Added software history * 12/2/2013 1829 bphillip Added hashcode and equals * </pre> * * @author bphillip * @version 1 */
Represents information about the version of the object it is describing. Java class for VersionInfoType complex type. The following schema fragment specifies the expected content contained within this class. SOFTWARE HISTORY Date Ticket# Engineer Description 2012 bphillip Initial implementation 10/17/2013 1682 bphillip Added software history 12/2/2013 1829 bphillip Added hashcode and equals @author bphillip @version 1
[ "Represents", "information", "about", "the", "version", "of", "the", "object", "it", "is", "describing", ".", "Java", "class", "for", "VersionInfoType", "complex", "type", ".", "The", "following", "schema", "fragment", "specifies", "the", "expected", "content", "contained", "within", "this", "class", ".", "SOFTWARE", "HISTORY", "Date", "Ticket#", "Engineer", "Description", "2012", "bphillip", "Initial", "implementation", "10", "/", "17", "/", "2013", "1682", "bphillip", "Added", "software", "history", "12", "/", "2", "/", "2013", "1829", "bphillip", "Added", "hashcode", "and", "equals", "@author", "bphillip", "@version", "1" ]
@Embeddable @XmlRootElement(name = "VersionInfo") @XmlAccessorType(XmlAccessType.NONE) @DynamicSerialize public class VersionInfoType implements Serializable, IPersistableDataObject<String>, Comparable<VersionInfoType> { private static final long serialVersionUID = -2869857115641981790L; @Column @XmlAttribute @DynamicSerializeElement protected String versionName = "1"; @Column @XmlAttribute @DynamicSerializeElement protected String userVersionName; public VersionInfoType() { } public VersionInfoType(String versionName) { this.versionName = versionName; } /** * Gets the value of the versionName property. * * @return possible object is {@link String } * */ public String getVersionName() { return versionName; } /** * Sets the value of the versionName property. * * @param value * allowed object is {@link String } * */ public void setVersionName(String value) { this.versionName = value; } /** * Gets the value of the userVersionName property. * * @return possible object is {@link String } * */ public String getUserVersionName() { return userVersionName; } /** * Sets the value of the userVersionName property. * * @param value * allowed object is {@link String } * */ public void setUserVersionName(String value) { this.userVersionName = value; } @Override public String toString() { return versionName + "_" + userVersionName; } @Override public String getIdentifier() { return versionName; } @Override public int compareTo(VersionInfoType obj) { if (this.versionName == null && obj.getVersionName() == null) { return 0; } else if (this.versionName == null) { return -1; } else if (obj.getVersionName() == null) { return 1; } String[] versionParts1 = this.versionName.split("\\."); String[] versionParts2 = obj.versionName.split("\\."); for (int i = 0; i < versionParts1.length; i++) { int part1 = Integer.parseInt(versionParts1[i]); if (i >= versionParts2.length) { return 1; } int part2 = Integer.parseInt(versionParts2[i]); if (part1 > part2) { return 1; } else if (part1 < part2) { return -1; } else if (i >= versionParts1.length - 1 && versionParts2.length > i) { return -1; } } return 0; } public boolean greaterThan(VersionInfoType obj) { return this.compareTo(obj) > 0 ? true : false; } public boolean greaterThanEquals(VersionInfoType obj) { return this.compareTo(obj) >= 0 ? true : false; } public boolean lessThan(VersionInfoType obj) { return this.compareTo(obj) < 0 ? true : false; } public boolean lessThanEquals(VersionInfoType obj) { return this.compareTo(obj) <= 0 ? true : false; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((userVersionName == null) ? 0 : userVersionName.hashCode()); result = prime * result + ((versionName == null) ? 0 : versionName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; VersionInfoType other = (VersionInfoType) obj; if (userVersionName == null) { if (other.userVersionName != null) return false; } else if (!userVersionName.equals(other.userVersionName)) return false; if (versionName == null) { if (other.versionName != null) return false; } else if (!versionName.equals(other.versionName)) return false; return true; } }
[ "@", "Embeddable", "@", "XmlRootElement", "(", "name", "=", "\"", "VersionInfo", "\"", ")", "@", "XmlAccessorType", "(", "XmlAccessType", ".", "NONE", ")", "@", "DynamicSerialize", "public", "class", "VersionInfoType", "implements", "Serializable", ",", "IPersistableDataObject", "<", "String", ">", ",", "Comparable", "<", "VersionInfoType", ">", "{", "private", "static", "final", "long", "serialVersionUID", "=", "-", "2869857115641981790L", ";", "@", "Column", "@", "XmlAttribute", "@", "DynamicSerializeElement", "protected", "String", "versionName", "=", "\"", "1", "\"", ";", "@", "Column", "@", "XmlAttribute", "@", "DynamicSerializeElement", "protected", "String", "userVersionName", ";", "public", "VersionInfoType", "(", ")", "{", "}", "public", "VersionInfoType", "(", "String", "versionName", ")", "{", "this", ".", "versionName", "=", "versionName", ";", "}", "/**\n * Gets the value of the versionName property.\n * \n * @return possible object is {@link String }\n * \n */", "public", "String", "getVersionName", "(", ")", "{", "return", "versionName", ";", "}", "/**\n * Sets the value of the versionName property.\n * \n * @param value\n * allowed object is {@link String }\n * \n */", "public", "void", "setVersionName", "(", "String", "value", ")", "{", "this", ".", "versionName", "=", "value", ";", "}", "/**\n * Gets the value of the userVersionName property.\n * \n * @return possible object is {@link String }\n * \n */", "public", "String", "getUserVersionName", "(", ")", "{", "return", "userVersionName", ";", "}", "/**\n * Sets the value of the userVersionName property.\n * \n * @param value\n * allowed object is {@link String }\n * \n */", "public", "void", "setUserVersionName", "(", "String", "value", ")", "{", "this", ".", "userVersionName", "=", "value", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "versionName", "+", "\"", "_", "\"", "+", "userVersionName", ";", "}", "@", "Override", "public", "String", "getIdentifier", "(", ")", "{", "return", "versionName", ";", "}", "@", "Override", "public", "int", "compareTo", "(", "VersionInfoType", "obj", ")", "{", "if", "(", "this", ".", "versionName", "==", "null", "&&", "obj", ".", "getVersionName", "(", ")", "==", "null", ")", "{", "return", "0", ";", "}", "else", "if", "(", "this", ".", "versionName", "==", "null", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "obj", ".", "getVersionName", "(", ")", "==", "null", ")", "{", "return", "1", ";", "}", "String", "[", "]", "versionParts1", "=", "this", ".", "versionName", ".", "split", "(", "\"", "\\\\", ".", "\"", ")", ";", "String", "[", "]", "versionParts2", "=", "obj", ".", "versionName", ".", "split", "(", "\"", "\\\\", ".", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "versionParts1", ".", "length", ";", "i", "++", ")", "{", "int", "part1", "=", "Integer", ".", "parseInt", "(", "versionParts1", "[", "i", "]", ")", ";", "if", "(", "i", ">=", "versionParts2", ".", "length", ")", "{", "return", "1", ";", "}", "int", "part2", "=", "Integer", ".", "parseInt", "(", "versionParts2", "[", "i", "]", ")", ";", "if", "(", "part1", ">", "part2", ")", "{", "return", "1", ";", "}", "else", "if", "(", "part1", "<", "part2", ")", "{", "return", "-", "1", ";", "}", "else", "if", "(", "i", ">=", "versionParts1", ".", "length", "-", "1", "&&", "versionParts2", ".", "length", ">", "i", ")", "{", "return", "-", "1", ";", "}", "}", "return", "0", ";", "}", "public", "boolean", "greaterThan", "(", "VersionInfoType", "obj", ")", "{", "return", "this", ".", "compareTo", "(", "obj", ")", ">", "0", "?", "true", ":", "false", ";", "}", "public", "boolean", "greaterThanEquals", "(", "VersionInfoType", "obj", ")", "{", "return", "this", ".", "compareTo", "(", "obj", ")", ">=", "0", "?", "true", ":", "false", ";", "}", "public", "boolean", "lessThan", "(", "VersionInfoType", "obj", ")", "{", "return", "this", ".", "compareTo", "(", "obj", ")", "<", "0", "?", "true", ":", "false", ";", "}", "public", "boolean", "lessThanEquals", "(", "VersionInfoType", "obj", ")", "{", "return", "this", ".", "compareTo", "(", "obj", ")", "<=", "0", "?", "true", ":", "false", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "final", "int", "prime", "=", "31", ";", "int", "result", "=", "1", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "userVersionName", "==", "null", ")", "?", "0", ":", "userVersionName", ".", "hashCode", "(", ")", ")", ";", "result", "=", "prime", "*", "result", "+", "(", "(", "versionName", "==", "null", ")", "?", "0", ":", "versionName", ".", "hashCode", "(", ")", ")", ";", "return", "result", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "obj", ")", "{", "if", "(", "this", "==", "obj", ")", "return", "true", ";", "if", "(", "obj", "==", "null", ")", "return", "false", ";", "if", "(", "getClass", "(", ")", "!=", "obj", ".", "getClass", "(", ")", ")", "return", "false", ";", "VersionInfoType", "other", "=", "(", "VersionInfoType", ")", "obj", ";", "if", "(", "userVersionName", "==", "null", ")", "{", "if", "(", "other", ".", "userVersionName", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "userVersionName", ".", "equals", "(", "other", ".", "userVersionName", ")", ")", "return", "false", ";", "if", "(", "versionName", "==", "null", ")", "{", "if", "(", "other", ".", "versionName", "!=", "null", ")", "return", "false", ";", "}", "else", "if", "(", "!", "versionName", ".", "equals", "(", "other", ".", "versionName", ")", ")", "return", "false", ";", "return", "true", ";", "}", "}" ]
Represents information about the version of the object it is describing.
[ "Represents", "information", "about", "the", "version", "of", "the", "object", "it", "is", "describing", "." ]
[]
[ { "param": "Serializable,\n IPersistableDataObject<String>, Comparable<VersionInfoType>", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable,\n IPersistableDataObject<String>, Comparable<VersionInfoType>", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
973
307
c101c83f15bcb63d307ac2aee4637d450dfdbc22
Animadversio/Visual_Neuro_InSilico_Exp
insilico_Exp.py
[ "Apache-2.0" ]
Python
ExperimentEvolve
Basic Evolution Experiments Default behavior is to use the current CMAES optimizer to optimize for 200 steps for the given unit. support Caffe or Torch Backend the render function should have such signature, input numpy array of B-by-code_length, output list of images. it also has a named parameter scale=255.0. which specify the range of pixel value of output.
Basic Evolution Experiments Default behavior is to use the current CMAES optimizer to optimize for 200 steps for the given unit. support Caffe or Torch Backend the render function should have such signature, input numpy array of B-by-code_length, output list of images. it also has a named parameter scale=255.0. which specify the range of pixel value of output.
[ "Basic", "Evolution", "Experiments", "Default", "behavior", "is", "to", "use", "the", "current", "CMAES", "optimizer", "to", "optimize", "for", "200", "steps", "for", "the", "given", "unit", ".", "support", "Caffe", "or", "Torch", "Backend", "the", "render", "function", "should", "have", "such", "signature", "input", "numpy", "array", "of", "B", "-", "by", "-", "code_length", "output", "list", "of", "images", ".", "it", "also", "has", "a", "named", "parameter", "scale", "=", "255", ".", "0", ".", "which", "specify", "the", "range", "of", "pixel", "value", "of", "output", "." ]
class ExperimentEvolve: """ Basic Evolution Experiments Default behavior is to use the current CMAES optimizer to optimize for 200 steps for the given unit. support Caffe or Torch Backend the render function should have such signature, input numpy array of B-by-code_length, output list of images. it also has a named parameter scale=255.0. which specify the range of pixel value of output. """ def __init__(self, model_unit, max_step=200, backend="caffe", optimizer=None, GAN="fc6", verbose=False): self.recording = [] self.scores_all = [] self.codes_all = [] self.generations = [] if backend == "caffe": self.CNNmodel = CNNmodel(model_unit[0]) # 'caffe-net' elif backend == "torch": if model_unit[0] is 'caffe-net': self.CNNmodel = CNNmodel_Torch(model_unit[0]) else: # alexnet, VGG, DENSE and anything else self.CNNmodel = TorchScorer(model_unit[0]) else: raise NotImplementedError self.CNNmodel.select_unit(model_unit) if GAN == "fc6" or GAN == "fc7" or GAN == "fc8": self.G = upconvGAN(name=GAN).cuda() self.render = self.G.render # function that map a 2d array of code (samp_n by code len) to a list of images # self.G = Generator(name=GAN) # self.render = self.G.render if GAN == "fc8": code_length = 1000 else: code_length = 4096 elif GAN == "BigGAN": from BigGAN_Evolution import BigGAN_embed_render self.render = BigGAN_embed_render code_length = 256 # 128 # 128d Class Embedding code or 256d full code could be used. elif GAN == "BigBiGAN": from NN_playground.BigBiGAN import BigBiGAN_render self.render = BigBiGAN_render code_length = 120 # 120 d space for Unconditional generation in BigBiGAN else: raise NotImplementedError if optimizer is not None: # Default optimizer is this self.optimizer = optimizer else: self.optimizer = CholeskyCMAES(code_length, population_size=None, init_sigma=init_sigma, init_code=np.zeros([1, code_length]), Aupdate_freq=Aupdate_freq, maximize=True, random_seed=None, optim_params={}) # CholeskyCMAES(recorddir=recorddir, space_dimen=code_length, init_sigma=init_sigma, # init_code=np.zeros([1, code_length]), Aupdate_freq=Aupdate_freq) # assert issubclass(type(optimizer), Optimizer) self.max_steps = max_step self.verbose = verbose self.code_length = code_length def run(self, init_code=None): self.recording = [] self.scores_all = [] self.codes_all = [] self.generations = [] t00 = time() for self.istep in range(self.max_steps): if self.istep == 0: if init_code is None: codes = np.random.randn(20, self.code_length) # codes = np.zeros([1, code_length]) if type(self.optimizer) is Genetic: # self.optimizer.load_init_population(initcodedir, ) codes, self.optimizer._genealogy = utils_old.load_codes2(initcodedir, self.optimizer._popsize) else: codes = init_code print('>>> step %d' % self.istep) t0 = time() self.current_images = self.render(codes, scale=255.0) t1 = time() # generate image from code synscores = self.CNNmodel.score(self.current_images) t2 = time() # score images codes_new = self.optimizer.step_simple(synscores, codes) t3 = time() # use results to update optimizer self.codes_all.append(codes) self.scores_all = self.scores_all + list(synscores) self.generations = self.generations + [self.istep] * len(synscores) codes = codes_new # summarize scores & delays if self.verbose: print('synthetic img scores: mean {}, all {}'.format(np.nanmean(synscores), -np.sort(-synscores))) else: print("img scores: mean %.2f max %.2f min %.2f"%(np.nanmean(synscores), np.nanmax(synscores), np.nanmin(synscores))) print(('step %d time: total %.2fs | ' + 'code visualize %.2fs score %.2fs optimizer step %.2fs') % (self.istep, t3 - t0, t1 - t0, t2 - t1, t3 - t2)) self.codes_all = np.concatenate(tuple(self.codes_all), axis=0) self.scores_all = np.array(self.scores_all) self.generations = np.array(self.generations) t11 = time() print("Summary\nGenerations: %d, Image samples: %d, Best score: %.2f (spent %.2f sec)" % (self.istep, self.codes_all.shape[0], self.scores_all.max(), t11 - t00)) def visualize_exp(self, show=False, title_str=""): """ Visualize the experiment by showing the maximal activating images and the scores in each generations """ idx_list = [] for geni in range(min(self.generations), max(self.generations) + 1): rel_idx = np.argmax(self.scores_all[self.generations == geni]) idx_list.append(np.nonzero(self.generations == geni)[0][rel_idx]) idx_list = np.array(idx_list) select_code = self.codes_all[idx_list, :] score_select = self.scores_all[idx_list] img_select = self.render(select_code, scale=1.0) fig = utils_old.visualize_img_list(img_select, score_select, show=show, nrow=None, title_str=title_str) if show: fig.show() return fig def visualize_best(self, show=False, title_str=""): """ Just Visualize the best Images for the experiment """ idx = np.argmax(self.scores_all) select_code = self.codes_all[idx:idx + 1, :] score_select = self.scores_all[idx] img_select = self.render(select_code, scale=1.0) fig = plt.figure(figsize=[3, 3]) plt.imshow(img_select[0]) plt.axis('off') plt.title("{0:.2f}".format(score_select) + title_str, fontsize=14) if show: plt.show() return fig def visualize_codenorm(self, show=True, title_str=""): code_norm = np.sqrt((self.codes_all ** 2).sum(axis=1)) figh = plt.figure() plt.scatter(self.generations, code_norm, s=16, alpha=0.6, label="all score") plt.title("Optimization Trajectory of Code Norm\n" + title_str) if show: plt.show() return figh def visualize_trajectory(self, show=True, title_str=""): """ Visualize the Score Trajectory """ gen_slice = np.arange(min(self.generations), max(self.generations) + 1) AvgScore = np.zeros_like(gen_slice) MaxScore = np.zeros_like(gen_slice) for i, geni in enumerate(gen_slice): AvgScore[i] = np.mean(self.scores_all[self.generations == geni]) MaxScore[i] = np.max(self.scores_all[self.generations == geni]) figh = plt.figure() plt.scatter(self.generations, self.scores_all, s=16, alpha=0.6, label="all score") plt.plot(gen_slice, AvgScore, color='black', label="Average score") plt.plot(gen_slice, MaxScore, color='red', label="Max score") plt.xlabel("generation #") plt.ylabel("CNN unit score") plt.title("Optimization Trajectory of Score\n" + title_str) plt.legend() if show: plt.show() return figh
[ "class", "ExperimentEvolve", ":", "def", "__init__", "(", "self", ",", "model_unit", ",", "max_step", "=", "200", ",", "backend", "=", "\"caffe\"", ",", "optimizer", "=", "None", ",", "GAN", "=", "\"fc6\"", ",", "verbose", "=", "False", ")", ":", "self", ".", "recording", "=", "[", "]", "self", ".", "scores_all", "=", "[", "]", "self", ".", "codes_all", "=", "[", "]", "self", ".", "generations", "=", "[", "]", "if", "backend", "==", "\"caffe\"", ":", "self", ".", "CNNmodel", "=", "CNNmodel", "(", "model_unit", "[", "0", "]", ")", "elif", "backend", "==", "\"torch\"", ":", "if", "model_unit", "[", "0", "]", "is", "'caffe-net'", ":", "self", ".", "CNNmodel", "=", "CNNmodel_Torch", "(", "model_unit", "[", "0", "]", ")", "else", ":", "self", ".", "CNNmodel", "=", "TorchScorer", "(", "model_unit", "[", "0", "]", ")", "else", ":", "raise", "NotImplementedError", "self", ".", "CNNmodel", ".", "select_unit", "(", "model_unit", ")", "if", "GAN", "==", "\"fc6\"", "or", "GAN", "==", "\"fc7\"", "or", "GAN", "==", "\"fc8\"", ":", "self", ".", "G", "=", "upconvGAN", "(", "name", "=", "GAN", ")", ".", "cuda", "(", ")", "self", ".", "render", "=", "self", ".", "G", ".", "render", "if", "GAN", "==", "\"fc8\"", ":", "code_length", "=", "1000", "else", ":", "code_length", "=", "4096", "elif", "GAN", "==", "\"BigGAN\"", ":", "from", "BigGAN_Evolution", "import", "BigGAN_embed_render", "self", ".", "render", "=", "BigGAN_embed_render", "code_length", "=", "256", "elif", "GAN", "==", "\"BigBiGAN\"", ":", "from", "NN_playground", ".", "BigBiGAN", "import", "BigBiGAN_render", "self", ".", "render", "=", "BigBiGAN_render", "code_length", "=", "120", "else", ":", "raise", "NotImplementedError", "if", "optimizer", "is", "not", "None", ":", "self", ".", "optimizer", "=", "optimizer", "else", ":", "self", ".", "optimizer", "=", "CholeskyCMAES", "(", "code_length", ",", "population_size", "=", "None", ",", "init_sigma", "=", "init_sigma", ",", "init_code", "=", "np", ".", "zeros", "(", "[", "1", ",", "code_length", "]", ")", ",", "Aupdate_freq", "=", "Aupdate_freq", ",", "maximize", "=", "True", ",", "random_seed", "=", "None", ",", "optim_params", "=", "{", "}", ")", "self", ".", "max_steps", "=", "max_step", "self", ".", "verbose", "=", "verbose", "self", ".", "code_length", "=", "code_length", "def", "run", "(", "self", ",", "init_code", "=", "None", ")", ":", "self", ".", "recording", "=", "[", "]", "self", ".", "scores_all", "=", "[", "]", "self", ".", "codes_all", "=", "[", "]", "self", ".", "generations", "=", "[", "]", "t00", "=", "time", "(", ")", "for", "self", ".", "istep", "in", "range", "(", "self", ".", "max_steps", ")", ":", "if", "self", ".", "istep", "==", "0", ":", "if", "init_code", "is", "None", ":", "codes", "=", "np", ".", "random", ".", "randn", "(", "20", ",", "self", ".", "code_length", ")", "if", "type", "(", "self", ".", "optimizer", ")", "is", "Genetic", ":", "codes", ",", "self", ".", "optimizer", ".", "_genealogy", "=", "utils_old", ".", "load_codes2", "(", "initcodedir", ",", "self", ".", "optimizer", ".", "_popsize", ")", "else", ":", "codes", "=", "init_code", "print", "(", "'>>> step %d'", "%", "self", ".", "istep", ")", "t0", "=", "time", "(", ")", "self", ".", "current_images", "=", "self", ".", "render", "(", "codes", ",", "scale", "=", "255.0", ")", "t1", "=", "time", "(", ")", "synscores", "=", "self", ".", "CNNmodel", ".", "score", "(", "self", ".", "current_images", ")", "t2", "=", "time", "(", ")", "codes_new", "=", "self", ".", "optimizer", ".", "step_simple", "(", "synscores", ",", "codes", ")", "t3", "=", "time", "(", ")", "self", ".", "codes_all", ".", "append", "(", "codes", ")", "self", ".", "scores_all", "=", "self", ".", "scores_all", "+", "list", "(", "synscores", ")", "self", ".", "generations", "=", "self", ".", "generations", "+", "[", "self", ".", "istep", "]", "*", "len", "(", "synscores", ")", "codes", "=", "codes_new", "if", "self", ".", "verbose", ":", "print", "(", "'synthetic img scores: mean {}, all {}'", ".", "format", "(", "np", ".", "nanmean", "(", "synscores", ")", ",", "-", "np", ".", "sort", "(", "-", "synscores", ")", ")", ")", "else", ":", "print", "(", "\"img scores: mean %.2f max %.2f min %.2f\"", "%", "(", "np", ".", "nanmean", "(", "synscores", ")", ",", "np", ".", "nanmax", "(", "synscores", ")", ",", "np", ".", "nanmin", "(", "synscores", ")", ")", ")", "print", "(", "(", "'step %d time: total %.2fs | '", "+", "'code visualize %.2fs score %.2fs optimizer step %.2fs'", ")", "%", "(", "self", ".", "istep", ",", "t3", "-", "t0", ",", "t1", "-", "t0", ",", "t2", "-", "t1", ",", "t3", "-", "t2", ")", ")", "self", ".", "codes_all", "=", "np", ".", "concatenate", "(", "tuple", "(", "self", ".", "codes_all", ")", ",", "axis", "=", "0", ")", "self", ".", "scores_all", "=", "np", ".", "array", "(", "self", ".", "scores_all", ")", "self", ".", "generations", "=", "np", ".", "array", "(", "self", ".", "generations", ")", "t11", "=", "time", "(", ")", "print", "(", "\"Summary\\nGenerations: %d, Image samples: %d, Best score: %.2f (spent %.2f sec)\"", "%", "(", "self", ".", "istep", ",", "self", ".", "codes_all", ".", "shape", "[", "0", "]", ",", "self", ".", "scores_all", ".", "max", "(", ")", ",", "t11", "-", "t00", ")", ")", "def", "visualize_exp", "(", "self", ",", "show", "=", "False", ",", "title_str", "=", "\"\"", ")", ":", "\"\"\" Visualize the experiment by showing the maximal activating images and the scores in each generations\n \"\"\"", "idx_list", "=", "[", "]", "for", "geni", "in", "range", "(", "min", "(", "self", ".", "generations", ")", ",", "max", "(", "self", ".", "generations", ")", "+", "1", ")", ":", "rel_idx", "=", "np", ".", "argmax", "(", "self", ".", "scores_all", "[", "self", ".", "generations", "==", "geni", "]", ")", "idx_list", ".", "append", "(", "np", ".", "nonzero", "(", "self", ".", "generations", "==", "geni", ")", "[", "0", "]", "[", "rel_idx", "]", ")", "idx_list", "=", "np", ".", "array", "(", "idx_list", ")", "select_code", "=", "self", ".", "codes_all", "[", "idx_list", ",", ":", "]", "score_select", "=", "self", ".", "scores_all", "[", "idx_list", "]", "img_select", "=", "self", ".", "render", "(", "select_code", ",", "scale", "=", "1.0", ")", "fig", "=", "utils_old", ".", "visualize_img_list", "(", "img_select", ",", "score_select", ",", "show", "=", "show", ",", "nrow", "=", "None", ",", "title_str", "=", "title_str", ")", "if", "show", ":", "fig", ".", "show", "(", ")", "return", "fig", "def", "visualize_best", "(", "self", ",", "show", "=", "False", ",", "title_str", "=", "\"\"", ")", ":", "\"\"\" Just Visualize the best Images for the experiment\n \"\"\"", "idx", "=", "np", ".", "argmax", "(", "self", ".", "scores_all", ")", "select_code", "=", "self", ".", "codes_all", "[", "idx", ":", "idx", "+", "1", ",", ":", "]", "score_select", "=", "self", ".", "scores_all", "[", "idx", "]", "img_select", "=", "self", ".", "render", "(", "select_code", ",", "scale", "=", "1.0", ")", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "[", "3", ",", "3", "]", ")", "plt", ".", "imshow", "(", "img_select", "[", "0", "]", ")", "plt", ".", "axis", "(", "'off'", ")", "plt", ".", "title", "(", "\"{0:.2f}\"", ".", "format", "(", "score_select", ")", "+", "title_str", ",", "fontsize", "=", "14", ")", "if", "show", ":", "plt", ".", "show", "(", ")", "return", "fig", "def", "visualize_codenorm", "(", "self", ",", "show", "=", "True", ",", "title_str", "=", "\"\"", ")", ":", "code_norm", "=", "np", ".", "sqrt", "(", "(", "self", ".", "codes_all", "**", "2", ")", ".", "sum", "(", "axis", "=", "1", ")", ")", "figh", "=", "plt", ".", "figure", "(", ")", "plt", ".", "scatter", "(", "self", ".", "generations", ",", "code_norm", ",", "s", "=", "16", ",", "alpha", "=", "0.6", ",", "label", "=", "\"all score\"", ")", "plt", ".", "title", "(", "\"Optimization Trajectory of Code Norm\\n\"", "+", "title_str", ")", "if", "show", ":", "plt", ".", "show", "(", ")", "return", "figh", "def", "visualize_trajectory", "(", "self", ",", "show", "=", "True", ",", "title_str", "=", "\"\"", ")", ":", "\"\"\" Visualize the Score Trajectory \"\"\"", "gen_slice", "=", "np", ".", "arange", "(", "min", "(", "self", ".", "generations", ")", ",", "max", "(", "self", ".", "generations", ")", "+", "1", ")", "AvgScore", "=", "np", ".", "zeros_like", "(", "gen_slice", ")", "MaxScore", "=", "np", ".", "zeros_like", "(", "gen_slice", ")", "for", "i", ",", "geni", "in", "enumerate", "(", "gen_slice", ")", ":", "AvgScore", "[", "i", "]", "=", "np", ".", "mean", "(", "self", ".", "scores_all", "[", "self", ".", "generations", "==", "geni", "]", ")", "MaxScore", "[", "i", "]", "=", "np", ".", "max", "(", "self", ".", "scores_all", "[", "self", ".", "generations", "==", "geni", "]", ")", "figh", "=", "plt", ".", "figure", "(", ")", "plt", ".", "scatter", "(", "self", ".", "generations", ",", "self", ".", "scores_all", ",", "s", "=", "16", ",", "alpha", "=", "0.6", ",", "label", "=", "\"all score\"", ")", "plt", ".", "plot", "(", "gen_slice", ",", "AvgScore", ",", "color", "=", "'black'", ",", "label", "=", "\"Average score\"", ")", "plt", ".", "plot", "(", "gen_slice", ",", "MaxScore", ",", "color", "=", "'red'", ",", "label", "=", "\"Max score\"", ")", "plt", ".", "xlabel", "(", "\"generation #\"", ")", "plt", ".", "ylabel", "(", "\"CNN unit score\"", ")", "plt", ".", "title", "(", "\"Optimization Trajectory of Score\\n\"", "+", "title_str", ")", "plt", ".", "legend", "(", ")", "if", "show", ":", "plt", ".", "show", "(", ")", "return", "figh" ]
Basic Evolution Experiments Default behavior is to use the current CMAES optimizer to optimize for 200 steps for the given unit.
[ "Basic", "Evolution", "Experiments", "Default", "behavior", "is", "to", "use", "the", "current", "CMAES", "optimizer", "to", "optimize", "for", "200", "steps", "for", "the", "given", "unit", "." ]
[ "\"\"\" Basic Evolution Experiments\n Default behavior is to use the current CMAES optimizer to optimize for 200 steps for the given unit.\n support Caffe or Torch Backend\n\n the render function should have such signature, input numpy array of B-by-code_length, output list of images.\n it also has a named parameter scale=255.0. which specify the range of pixel value of output.\n \"\"\"", "# 'caffe-net'", "# alexnet, VGG, DENSE and anything else", "# function that map a 2d array of code (samp_n by code len) to a list of images", "# self.G = Generator(name=GAN)", "# self.render = self.G.render", "# 128", "# 128d Class Embedding code or 256d full code could be used.", "# 120 d space for Unconditional generation in BigBiGAN", "# Default optimizer is this", "# CholeskyCMAES(recorddir=recorddir, space_dimen=code_length, init_sigma=init_sigma,", "# init_code=np.zeros([1, code_length]), Aupdate_freq=Aupdate_freq)", "# assert issubclass(type(optimizer), Optimizer)", "# codes = np.zeros([1, code_length])", "# self.optimizer.load_init_population(initcodedir, )", "# generate image from code", "# score images", "# use results to update optimizer", "# summarize scores & delays", "\"\"\" Visualize the experiment by showing the maximal activating images and the scores in each generations\n \"\"\"", "\"\"\" Just Visualize the best Images for the experiment\n \"\"\"", "\"\"\" Visualize the Score Trajectory \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
19
1,873
87
800fcb141646bd2b76583352cbb054e572fa4ebb
minuJeong/moderngl-window
moderngl_window/opengl/vao.py
[ "MIT" ]
Python
VAO
Represents a vertex array object. This is a wrapper class over ``moderngl.VertexArray`` to make interactions with programs/shaders simpler. Named buffers are added correspoding with attribute names in a vertex shader. When rendering the VAO an internal ``moderngl.VertextArray`` is created automatically mapping the named buffers compatible with the supplied program. This program is cached internally. The shader program doesn't need to use all the buffers registered in this wrapper. When a subset is used only the used buffers are mapped and the appropriate padding is calculated when interleaved data is used. You are not required to use this class, but most methods in the system creating vertexbuffers will return this type. You can obtain a single ``moderngl.VertexBuffer`` instance by calling :py:meth:`VAO.instance` method if you prefer to work directly on moderngl instances. Example:: # Separate buffers vao = VAO(name="test", mode=moderngl.POINTS) vao.buffer(positions, '3f', ['in_position']) vao.buffer(velocities, '3f', ['in_velocities']) # Interleaved vao = VAO(name="test", mode=moderngl.POINTS) vao.buffer(interleaved_data, '3f 3f', ['in_position', 'in_velocities']) .. code:: glsl # GLSL vertex shader in attributes in vec3 in_position; in vec3 in_velocities;
Represents a vertex array object. This is a wrapper class over ``moderngl.VertexArray`` to make interactions with programs/shaders simpler. Named buffers are added correspoding with attribute names in a vertex shader. When rendering the VAO an internal ``moderngl.VertextArray`` is created automatically mapping the named buffers compatible with the supplied program. This program is cached internally. The shader program doesn't need to use all the buffers registered in this wrapper. When a subset is used only the used buffers are mapped and the appropriate padding is calculated when interleaved data is used. You are not required to use this class, but most methods in the system creating vertexbuffers will return this type. : glsl GLSL vertex shader in attributes in vec3 in_position; in vec3 in_velocities.
[ "Represents", "a", "vertex", "array", "object", ".", "This", "is", "a", "wrapper", "class", "over", "`", "`", "moderngl", ".", "VertexArray", "`", "`", "to", "make", "interactions", "with", "programs", "/", "shaders", "simpler", ".", "Named", "buffers", "are", "added", "correspoding", "with", "attribute", "names", "in", "a", "vertex", "shader", ".", "When", "rendering", "the", "VAO", "an", "internal", "`", "`", "moderngl", ".", "VertextArray", "`", "`", "is", "created", "automatically", "mapping", "the", "named", "buffers", "compatible", "with", "the", "supplied", "program", ".", "This", "program", "is", "cached", "internally", ".", "The", "shader", "program", "doesn", "'", "t", "need", "to", "use", "all", "the", "buffers", "registered", "in", "this", "wrapper", ".", "When", "a", "subset", "is", "used", "only", "the", "used", "buffers", "are", "mapped", "and", "the", "appropriate", "padding", "is", "calculated", "when", "interleaved", "data", "is", "used", ".", "You", "are", "not", "required", "to", "use", "this", "class", "but", "most", "methods", "in", "the", "system", "creating", "vertexbuffers", "will", "return", "this", "type", ".", ":", "glsl", "GLSL", "vertex", "shader", "in", "attributes", "in", "vec3", "in_position", ";", "in", "vec3", "in_velocities", "." ]
class VAO: """ Represents a vertex array object. This is a wrapper class over ``moderngl.VertexArray`` to make interactions with programs/shaders simpler. Named buffers are added correspoding with attribute names in a vertex shader. When rendering the VAO an internal ``moderngl.VertextArray`` is created automatically mapping the named buffers compatible with the supplied program. This program is cached internally. The shader program doesn't need to use all the buffers registered in this wrapper. When a subset is used only the used buffers are mapped and the appropriate padding is calculated when interleaved data is used. You are not required to use this class, but most methods in the system creating vertexbuffers will return this type. You can obtain a single ``moderngl.VertexBuffer`` instance by calling :py:meth:`VAO.instance` method if you prefer to work directly on moderngl instances. Example:: # Separate buffers vao = VAO(name="test", mode=moderngl.POINTS) vao.buffer(positions, '3f', ['in_position']) vao.buffer(velocities, '3f', ['in_velocities']) # Interleaved vao = VAO(name="test", mode=moderngl.POINTS) vao.buffer(interleaved_data, '3f 3f', ['in_position', 'in_velocities']) .. code:: glsl # GLSL vertex shader in attributes in vec3 in_position; in vec3 in_velocities; """ def __init__(self, name="", mode=moderngl.TRIANGLES): """Create and empty VAO with a name and default render mode. Example:: VAO(name="cube", mode=moderngl.TRIANGLES) Keyword Args: name (str): Optional name for debug purposes mode (int): Default draw mode """ self.name = name self.mode = mode try: DRAW_MODES[self.mode] except KeyError: raise VAOError("Invalid draw mode. Options are {}".format(DRAW_MODES.values())) self._buffers = [] self._index_buffer = None self._index_element_size = None self.vertex_count = 0 self.vaos = {} @property def ctx(self): """moderngl.Context: The actite moderngl context""" return mglw.ctx() def render(self, program: moderngl.Program, mode=None, vertices=-1, first=0, instances=1): """Render the VAO. An internal ``moderngl.VertexBuffer`` with compatible buffer bindings is automatically created on the fly and cached internally. Args: program: The ``moderngl.Program`` Keyword Args: mode: Override the draw mode (``TRIANGLES`` etc) vertices (int): The number of vertices to transform first (int): The index of the first vertex to start with instances (int): The number of instances """ vao = self.instance(program) if mode is None: mode = self.mode vao.render(mode, vertices=vertices, first=first, instances=instances) def render_indirect(self, program: moderngl.Program, buffer, mode=None, count=-1, *, first=0): """The render primitive (mode) must be the same as the input primitive of the GeometryShader. The draw commands are 5 integers: (count, instanceCount, firstIndex, baseVertex, baseInstance). Args: program: The ``moderngl.Program`` buffer: The ``moderngl.Buffer`` containing indirect draw commands Keyword Args: mode (int): By default :py:data:`TRIANGLES` will be used. count (int): The number of draws. first (int): The index of the first indirect draw command. """ vao = self.instance(program) if mode is None: mode = self.mode vao.render_indirect(buffer, mode=mode, count=count, first=first) def transform(self, program: moderngl.Program, buffer: moderngl.Buffer, mode=None, vertices=-1, first=0, instances=1): """Transform vertices. Stores the output in a single buffer. Args: program: The ``moderngl.Program`` buffer: The ``moderngl.buffer`` to store the output Keyword Args: mode: Draw mode (for example ``moderngl.POINTS``) vertices (int): The number of vertices to transform first (int): The index of the first vertex to start with instances (int): The number of instances """ vao = self.instance(program) if mode is None: mode = self.mode vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances) def buffer(self, buffer, buffer_format: str, attribute_names: List[str]): """Register a buffer/vbo for the VAO. This can be called multiple times. adding multiple buffers (interleaved or not). Args: buffer: The buffer data. Can be ``numpy.array``, ``moderngl.Buffer`` or ``bytes``. buffer_format (str): The format of the buffer. (eg. ``3f 3f`` for interleaved positions and normals). attribute_names: A list of attribute names this buffer should map to. Returns: The ``moderngl.Buffer`` instance object. This is handy when providing ``bytes`` and ``numpy.array``. """ if not isinstance(attribute_names, list): attribute_names = [attribute_names, ] if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]: raise VAOError( ( "buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance" "(not {})".format(type(buffer)) ) ) if isinstance(buffer, numpy.ndarray): buffer = self.ctx.buffer(buffer.tobytes()) if isinstance(buffer, bytes): buffer = self.ctx.buffer(data=buffer) formats = buffer_format.split() if len(formats) != len(attribute_names): raise VAOError("Format '{}' does not describe attributes {}".format(buffer_format, attribute_names)) self._buffers.append(BufferInfo(buffer, buffer_format, attribute_names)) self.vertex_count = self._buffers[-1].vertices return buffer def index_buffer(self, buffer, index_element_size=4): """Set the index buffer for this VAO. Args: buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes`` Keyword Args: index_element_size (int): Byte size of each element. 1, 2 or 4 """ if not type(buffer) in [moderngl.Buffer, numpy.ndarray, bytes]: raise VAOError("buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance") if isinstance(buffer, numpy.ndarray): buffer = self.ctx.buffer(buffer.tobytes()) if isinstance(buffer, bytes): buffer = self.ctx.buffer(data=buffer) self._index_buffer = buffer self._index_element_size = index_element_size def instance(self, program: moderngl.Program) -> moderngl.VertexArray: """Obtain the ``moderngl.VertexArray`` instance for the program. The instance is only created once and cached internally. Args: program (moderngl.Program): The program Returns: ``moderngl.VertexArray``: instance """ vao = self.vaos.get(program.glo) if vao: return vao program_attributes = [ name for name, attr in program._members.items() if isinstance(attr, moderngl.Attribute) and not attr.name.startswith('gl_') ] # Make sure all attributes are covered for attrib_name in program_attributes: # Do we have a buffer mapping to this attribute? if not sum(buffer.has_attribute(attrib_name) for buffer in self._buffers): raise VAOError(( "VAO {} doesn't have attribute {} for program {}.\n" "Program attributes: {}.\n" "VAO attributes: {}" ).format( self.name, attrib_name, program, program_attributes, [attr for buff in self._buffers for attr in buff.attributes] )) vao_content = [] # Pick out the attributes we can actually map for buffer in self._buffers: content = buffer.content(program_attributes) if content: vao_content.append(content) # Any attribute left is not accounted for if program_attributes: raise VAOError("Did not find a buffer mapping for {}".format([n for n in program_attributes])) # Create the vao if self._index_buffer: vao = self.ctx.vertex_array( program, vao_content, self._index_buffer, self._index_element_size, ) else: vao = self.ctx.vertex_array(program, vao_content) self.vaos[program.glo] = vao return vao def release(self, buffer=True): """Destroy all internally cached vaos and release all buffers. Keyword Args: buffers (bool): also release buffers """ for _, vao in self.vaos.items(): vao.release() if buffer: for buff in self._buffers: buff.buffer.release() if self._index_buffer: self._index_buffer.release() def get_buffer_by_name(self, name: str) -> BufferInfo: """Get the BufferInfo associated with a specific attribute name If no buffer is associated with the name `None` will be returned. Args: name (str): Name of the mapped attribute Returns: BufferInfo: BufferInfo instance """ for buffer in self._buffers: if name in buffer.attributes: return buffer return None
[ "class", "VAO", ":", "def", "__init__", "(", "self", ",", "name", "=", "\"\"", ",", "mode", "=", "moderngl", ".", "TRIANGLES", ")", ":", "\"\"\"Create and empty VAO with a name and default render mode.\n\n Example::\n\n VAO(name=\"cube\", mode=moderngl.TRIANGLES)\n\n Keyword Args:\n name (str): Optional name for debug purposes\n mode (int): Default draw mode\n \"\"\"", "self", ".", "name", "=", "name", "self", ".", "mode", "=", "mode", "try", ":", "DRAW_MODES", "[", "self", ".", "mode", "]", "except", "KeyError", ":", "raise", "VAOError", "(", "\"Invalid draw mode. Options are {}\"", ".", "format", "(", "DRAW_MODES", ".", "values", "(", ")", ")", ")", "self", ".", "_buffers", "=", "[", "]", "self", ".", "_index_buffer", "=", "None", "self", ".", "_index_element_size", "=", "None", "self", ".", "vertex_count", "=", "0", "self", ".", "vaos", "=", "{", "}", "@", "property", "def", "ctx", "(", "self", ")", ":", "\"\"\"moderngl.Context: The actite moderngl context\"\"\"", "return", "mglw", ".", "ctx", "(", ")", "def", "render", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ",", "mode", "=", "None", ",", "vertices", "=", "-", "1", ",", "first", "=", "0", ",", "instances", "=", "1", ")", ":", "\"\"\"Render the VAO.\n\n An internal ``moderngl.VertexBuffer`` with compatible buffer bindings\n is automatically created on the fly and cached internally.\n\n Args:\n program: The ``moderngl.Program``\n Keyword Args:\n mode: Override the draw mode (``TRIANGLES`` etc)\n vertices (int): The number of vertices to transform\n first (int): The index of the first vertex to start with\n instances (int): The number of instances\n \"\"\"", "vao", "=", "self", ".", "instance", "(", "program", ")", "if", "mode", "is", "None", ":", "mode", "=", "self", ".", "mode", "vao", ".", "render", "(", "mode", ",", "vertices", "=", "vertices", ",", "first", "=", "first", ",", "instances", "=", "instances", ")", "def", "render_indirect", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ",", "buffer", ",", "mode", "=", "None", ",", "count", "=", "-", "1", ",", "*", ",", "first", "=", "0", ")", ":", "\"\"\"The render primitive (mode) must be the same as the input primitive of the GeometryShader.\n The draw commands are 5 integers: (count, instanceCount, firstIndex, baseVertex, baseInstance).\n\n Args:\n program: The ``moderngl.Program``\n buffer: The ``moderngl.Buffer`` containing indirect draw commands\n Keyword Args:\n mode (int): By default :py:data:`TRIANGLES` will be used.\n count (int): The number of draws.\n first (int): The index of the first indirect draw command.\n \"\"\"", "vao", "=", "self", ".", "instance", "(", "program", ")", "if", "mode", "is", "None", ":", "mode", "=", "self", ".", "mode", "vao", ".", "render_indirect", "(", "buffer", ",", "mode", "=", "mode", ",", "count", "=", "count", ",", "first", "=", "first", ")", "def", "transform", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ",", "buffer", ":", "moderngl", ".", "Buffer", ",", "mode", "=", "None", ",", "vertices", "=", "-", "1", ",", "first", "=", "0", ",", "instances", "=", "1", ")", ":", "\"\"\"Transform vertices. Stores the output in a single buffer.\n\n Args:\n program: The ``moderngl.Program``\n buffer: The ``moderngl.buffer`` to store the output\n Keyword Args:\n mode: Draw mode (for example ``moderngl.POINTS``)\n vertices (int): The number of vertices to transform\n first (int): The index of the first vertex to start with\n instances (int): The number of instances\n \"\"\"", "vao", "=", "self", ".", "instance", "(", "program", ")", "if", "mode", "is", "None", ":", "mode", "=", "self", ".", "mode", "vao", ".", "transform", "(", "buffer", ",", "mode", "=", "mode", ",", "vertices", "=", "vertices", ",", "first", "=", "first", ",", "instances", "=", "instances", ")", "def", "buffer", "(", "self", ",", "buffer", ",", "buffer_format", ":", "str", ",", "attribute_names", ":", "List", "[", "str", "]", ")", ":", "\"\"\"Register a buffer/vbo for the VAO. This can be called multiple times.\n adding multiple buffers (interleaved or not).\n\n Args:\n buffer: The buffer data. Can be ``numpy.array``, ``moderngl.Buffer`` or ``bytes``.\n buffer_format (str): The format of the buffer. (eg. ``3f 3f`` for interleaved positions and normals).\n attribute_names: A list of attribute names this buffer should map to.\n Returns:\n The ``moderngl.Buffer`` instance object. This is handy when providing ``bytes`` and ``numpy.array``.\n \"\"\"", "if", "not", "isinstance", "(", "attribute_names", ",", "list", ")", ":", "attribute_names", "=", "[", "attribute_names", ",", "]", "if", "not", "type", "(", "buffer", ")", "in", "[", "moderngl", ".", "Buffer", ",", "numpy", ".", "ndarray", ",", "bytes", "]", ":", "raise", "VAOError", "(", "(", "\"buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance\"", "\"(not {})\"", ".", "format", "(", "type", "(", "buffer", ")", ")", ")", ")", "if", "isinstance", "(", "buffer", ",", "numpy", ".", "ndarray", ")", ":", "buffer", "=", "self", ".", "ctx", ".", "buffer", "(", "buffer", ".", "tobytes", "(", ")", ")", "if", "isinstance", "(", "buffer", ",", "bytes", ")", ":", "buffer", "=", "self", ".", "ctx", ".", "buffer", "(", "data", "=", "buffer", ")", "formats", "=", "buffer_format", ".", "split", "(", ")", "if", "len", "(", "formats", ")", "!=", "len", "(", "attribute_names", ")", ":", "raise", "VAOError", "(", "\"Format '{}' does not describe attributes {}\"", ".", "format", "(", "buffer_format", ",", "attribute_names", ")", ")", "self", ".", "_buffers", ".", "append", "(", "BufferInfo", "(", "buffer", ",", "buffer_format", ",", "attribute_names", ")", ")", "self", ".", "vertex_count", "=", "self", ".", "_buffers", "[", "-", "1", "]", ".", "vertices", "return", "buffer", "def", "index_buffer", "(", "self", ",", "buffer", ",", "index_element_size", "=", "4", ")", ":", "\"\"\"Set the index buffer for this VAO.\n\n Args:\n buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``\n Keyword Args:\n index_element_size (int): Byte size of each element. 1, 2 or 4\n \"\"\"", "if", "not", "type", "(", "buffer", ")", "in", "[", "moderngl", ".", "Buffer", ",", "numpy", ".", "ndarray", ",", "bytes", "]", ":", "raise", "VAOError", "(", "\"buffer parameter must be a moderngl.Buffer, numpy.ndarray or bytes instance\"", ")", "if", "isinstance", "(", "buffer", ",", "numpy", ".", "ndarray", ")", ":", "buffer", "=", "self", ".", "ctx", ".", "buffer", "(", "buffer", ".", "tobytes", "(", ")", ")", "if", "isinstance", "(", "buffer", ",", "bytes", ")", ":", "buffer", "=", "self", ".", "ctx", ".", "buffer", "(", "data", "=", "buffer", ")", "self", ".", "_index_buffer", "=", "buffer", "self", ".", "_index_element_size", "=", "index_element_size", "def", "instance", "(", "self", ",", "program", ":", "moderngl", ".", "Program", ")", "->", "moderngl", ".", "VertexArray", ":", "\"\"\"Obtain the ``moderngl.VertexArray`` instance for the program.\n\n The instance is only created once and cached internally.\n\n Args:\n program (moderngl.Program): The program\n\n Returns:\n ``moderngl.VertexArray``: instance\n \"\"\"", "vao", "=", "self", ".", "vaos", ".", "get", "(", "program", ".", "glo", ")", "if", "vao", ":", "return", "vao", "program_attributes", "=", "[", "name", "for", "name", ",", "attr", "in", "program", ".", "_members", ".", "items", "(", ")", "if", "isinstance", "(", "attr", ",", "moderngl", ".", "Attribute", ")", "and", "not", "attr", ".", "name", ".", "startswith", "(", "'gl_'", ")", "]", "for", "attrib_name", "in", "program_attributes", ":", "if", "not", "sum", "(", "buffer", ".", "has_attribute", "(", "attrib_name", ")", "for", "buffer", "in", "self", ".", "_buffers", ")", ":", "raise", "VAOError", "(", "(", "\"VAO {} doesn't have attribute {} for program {}.\\n\"", "\"Program attributes: {}.\\n\"", "\"VAO attributes: {}\"", ")", ".", "format", "(", "self", ".", "name", ",", "attrib_name", ",", "program", ",", "program_attributes", ",", "[", "attr", "for", "buff", "in", "self", ".", "_buffers", "for", "attr", "in", "buff", ".", "attributes", "]", ")", ")", "vao_content", "=", "[", "]", "for", "buffer", "in", "self", ".", "_buffers", ":", "content", "=", "buffer", ".", "content", "(", "program_attributes", ")", "if", "content", ":", "vao_content", ".", "append", "(", "content", ")", "if", "program_attributes", ":", "raise", "VAOError", "(", "\"Did not find a buffer mapping for {}\"", ".", "format", "(", "[", "n", "for", "n", "in", "program_attributes", "]", ")", ")", "if", "self", ".", "_index_buffer", ":", "vao", "=", "self", ".", "ctx", ".", "vertex_array", "(", "program", ",", "vao_content", ",", "self", ".", "_index_buffer", ",", "self", ".", "_index_element_size", ",", ")", "else", ":", "vao", "=", "self", ".", "ctx", ".", "vertex_array", "(", "program", ",", "vao_content", ")", "self", ".", "vaos", "[", "program", ".", "glo", "]", "=", "vao", "return", "vao", "def", "release", "(", "self", ",", "buffer", "=", "True", ")", ":", "\"\"\"Destroy all internally cached vaos and release all buffers.\n\n Keyword Args:\n buffers (bool): also release buffers\n \"\"\"", "for", "_", ",", "vao", "in", "self", ".", "vaos", ".", "items", "(", ")", ":", "vao", ".", "release", "(", ")", "if", "buffer", ":", "for", "buff", "in", "self", ".", "_buffers", ":", "buff", ".", "buffer", ".", "release", "(", ")", "if", "self", ".", "_index_buffer", ":", "self", ".", "_index_buffer", ".", "release", "(", ")", "def", "get_buffer_by_name", "(", "self", ",", "name", ":", "str", ")", "->", "BufferInfo", ":", "\"\"\"Get the BufferInfo associated with a specific attribute name\n\n If no buffer is associated with the name `None` will be returned.\n\n Args:\n name (str): Name of the mapped attribute\n Returns:\n BufferInfo: BufferInfo instance\n \"\"\"", "for", "buffer", "in", "self", ".", "_buffers", ":", "if", "name", "in", "buffer", ".", "attributes", ":", "return", "buffer", "return", "None" ]
Represents a vertex array object.
[ "Represents", "a", "vertex", "array", "object", "." ]
[ "\"\"\"\n Represents a vertex array object.\n\n This is a wrapper class over ``moderngl.VertexArray`` to make interactions\n with programs/shaders simpler. Named buffers are added correspoding with\n attribute names in a vertex shader. When rendering the VAO an internal\n ``moderngl.VertextArray`` is created automatically mapping the named buffers\n compatible with the supplied program. This program is cached internally.\n\n The shader program doesn't need to use all the buffers registered in\n this wrapper. When a subset is used only the used buffers are mapped\n and the appropriate padding is calculated when interleaved data is used.\n\n You are not required to use this class, but most methods in the\n system creating vertexbuffers will return this type. You can obtain\n a single ``moderngl.VertexBuffer`` instance by calling :py:meth:`VAO.instance`\n method if you prefer to work directly on moderngl instances.\n\n Example::\n\n # Separate buffers\n vao = VAO(name=\"test\", mode=moderngl.POINTS)\n vao.buffer(positions, '3f', ['in_position'])\n vao.buffer(velocities, '3f', ['in_velocities'])\n\n # Interleaved\n vao = VAO(name=\"test\", mode=moderngl.POINTS)\n vao.buffer(interleaved_data, '3f 3f', ['in_position', 'in_velocities'])\n\n .. code:: glsl\n\n # GLSL vertex shader in attributes\n in vec3 in_position;\n in vec3 in_velocities;\n\n \"\"\"", "\"\"\"Create and empty VAO with a name and default render mode.\n\n Example::\n\n VAO(name=\"cube\", mode=moderngl.TRIANGLES)\n\n Keyword Args:\n name (str): Optional name for debug purposes\n mode (int): Default draw mode\n \"\"\"", "\"\"\"moderngl.Context: The actite moderngl context\"\"\"", "\"\"\"Render the VAO.\n\n An internal ``moderngl.VertexBuffer`` with compatible buffer bindings\n is automatically created on the fly and cached internally.\n\n Args:\n program: The ``moderngl.Program``\n Keyword Args:\n mode: Override the draw mode (``TRIANGLES`` etc)\n vertices (int): The number of vertices to transform\n first (int): The index of the first vertex to start with\n instances (int): The number of instances\n \"\"\"", "\"\"\"The render primitive (mode) must be the same as the input primitive of the GeometryShader.\n The draw commands are 5 integers: (count, instanceCount, firstIndex, baseVertex, baseInstance).\n\n Args:\n program: The ``moderngl.Program``\n buffer: The ``moderngl.Buffer`` containing indirect draw commands\n Keyword Args:\n mode (int): By default :py:data:`TRIANGLES` will be used.\n count (int): The number of draws.\n first (int): The index of the first indirect draw command.\n \"\"\"", "\"\"\"Transform vertices. Stores the output in a single buffer.\n\n Args:\n program: The ``moderngl.Program``\n buffer: The ``moderngl.buffer`` to store the output\n Keyword Args:\n mode: Draw mode (for example ``moderngl.POINTS``)\n vertices (int): The number of vertices to transform\n first (int): The index of the first vertex to start with\n instances (int): The number of instances\n \"\"\"", "\"\"\"Register a buffer/vbo for the VAO. This can be called multiple times.\n adding multiple buffers (interleaved or not).\n\n Args:\n buffer: The buffer data. Can be ``numpy.array``, ``moderngl.Buffer`` or ``bytes``.\n buffer_format (str): The format of the buffer. (eg. ``3f 3f`` for interleaved positions and normals).\n attribute_names: A list of attribute names this buffer should map to.\n Returns:\n The ``moderngl.Buffer`` instance object. This is handy when providing ``bytes`` and ``numpy.array``.\n \"\"\"", "\"\"\"Set the index buffer for this VAO.\n\n Args:\n buffer: ``moderngl.Buffer``, ``numpy.array`` or ``bytes``\n Keyword Args:\n index_element_size (int): Byte size of each element. 1, 2 or 4\n \"\"\"", "\"\"\"Obtain the ``moderngl.VertexArray`` instance for the program.\n\n The instance is only created once and cached internally.\n\n Args:\n program (moderngl.Program): The program\n\n Returns:\n ``moderngl.VertexArray``: instance\n \"\"\"", "# Make sure all attributes are covered", "# Do we have a buffer mapping to this attribute?", "# Pick out the attributes we can actually map", "# Any attribute left is not accounted for", "# Create the vao", "\"\"\"Destroy all internally cached vaos and release all buffers.\n\n Keyword Args:\n buffers (bool): also release buffers\n \"\"\"", "\"\"\"Get the BufferInfo associated with a specific attribute name\n\n If no buffer is associated with the name `None` will be returned.\n\n Args:\n name (str): Name of the mapped attribute\n Returns:\n BufferInfo: BufferInfo instance\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
2,135
334
8b1b69bb14a3815da604b6257d4742c5c6af214f
Dot42Xna/master
Generated/v2.3.3/Org.Apache.Http.Impl.Io.cs
[ "Apache-2.0" ]
C#
IdentityOutputStream
/// <summary> /// <para>A stream for writing with an "identity" transport encoding.</para><para><para></para><para></para><title>Revision:</title><para>560343 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/impl/io/IdentityOutputStream /// </java-name>
A stream for writing with an "identity" transport encoding.Revision:560343 4.0
[ "A", "stream", "for", "writing", "with", "an", "\"", "identity", "\"", "transport", "encoding", ".", "Revision", ":", "560343", "4", ".", "0" ]
[Dot42.DexImport("org/apache/http/impl/io/IdentityOutputStream", AccessFlags = 33)] public partial class IdentityOutputStream : global::Java.Io.OutputStream { [Dot42.DexImport("<init>", "(Lorg/apache/http/io/SessionOutputBuffer;)V", AccessFlags = 1)] public IdentityOutputStream(global::Org.Apache.Http.Io.ISessionOutputBuffer @out) { } [Dot42.DexImport("close", "()V", AccessFlags = 1)] public override void Close() { } [Dot42.DexImport("flush", "()V", AccessFlags = 1)] public override void Flush() { } [Dot42.DexImport("write", "([BII)V", AccessFlags = 1)] public override void Write(sbyte[] buffer, int offset, int count) { } [Dot42.DexImport("write", "([BII)V", AccessFlags = 1, IgnoreFromJava = true)] public override void Write(byte[] buffer, int offset, int count) { } [Dot42.DexImport("write", "([B)V", AccessFlags = 1)] public override void Write(sbyte[] oneByte) { } [Dot42.DexImport("write", "([B)V", AccessFlags = 1, IgnoreFromJava = true)] public override void Write(byte[] oneByte) { } [Dot42.DexImport("write", "(I)V", AccessFlags = 1)] public override void Write(int oneByte) { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal IdentityOutputStream() { } }
[ "[", "Dot42", ".", "DexImport", "(", "\"", "org/apache/http/impl/io/IdentityOutputStream", "\"", ",", "AccessFlags", "=", "33", ")", "]", "public", "partial", "class", "IdentityOutputStream", ":", "global", "::", "Java", ".", "Io", ".", "OutputStream", "{", "[", "Dot42", ".", "DexImport", "(", "\"", "<init>", "\"", ",", "\"", "(Lorg/apache/http/io/SessionOutputBuffer;)V", "\"", ",", "AccessFlags", "=", "1", ")", "]", "public", "IdentityOutputStream", "(", "global", "::", "Org", ".", "Apache", ".", "Http", ".", "Io", ".", "ISessionOutputBuffer", "@out", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "close", "\"", ",", "\"", "()V", "\"", ",", "AccessFlags", "=", "1", ")", "]", "public", "override", "void", "Close", "(", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "flush", "\"", ",", "\"", "()V", "\"", ",", "AccessFlags", "=", "1", ")", "]", "public", "override", "void", "Flush", "(", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "write", "\"", ",", "\"", "([BII)V", "\"", ",", "AccessFlags", "=", "1", ")", "]", "public", "override", "void", "Write", "(", "sbyte", "[", "]", "buffer", ",", "int", "offset", ",", "int", "count", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "write", "\"", ",", "\"", "([BII)V", "\"", ",", "AccessFlags", "=", "1", ",", "IgnoreFromJava", "=", "true", ")", "]", "public", "override", "void", "Write", "(", "byte", "[", "]", "buffer", ",", "int", "offset", ",", "int", "count", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "write", "\"", ",", "\"", "([B)V", "\"", ",", "AccessFlags", "=", "1", ")", "]", "public", "override", "void", "Write", "(", "sbyte", "[", "]", "oneByte", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "write", "\"", ",", "\"", "([B)V", "\"", ",", "AccessFlags", "=", "1", ",", "IgnoreFromJava", "=", "true", ")", "]", "public", "override", "void", "Write", "(", "byte", "[", "]", "oneByte", ")", "{", "}", "[", "Dot42", ".", "DexImport", "(", "\"", "write", "\"", ",", "\"", "(I)V", "\"", ",", "AccessFlags", "=", "1", ")", "]", "public", "override", "void", "Write", "(", "int", "oneByte", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsable", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Never", ")", "]", "internal", "IdentityOutputStream", "(", ")", "{", "}", "}" ]
A stream for writing with an "identity" transport encoding.Revision:560343 4.0
[ "A", "stream", "for", "writing", "with", "an", "\"", "identity", "\"", "transport", "encoding", ".", "Revision", ":", "560343", "4", ".", "0" ]
[ "/* scope: __dot42__ */", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Does not close the underlying socket output.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// close", "/// </java-name>", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Flushes this stream. Implementations of this method should ensure that any buffered data is written out. This implementation does nothing.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// flush", "/// </java-name>", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Writes <c> count </c> bytes from the byte array <c> buffer </c> starting at position <c> offset </c> to this stream.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// write", "/// </java-name>", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Writes <c> count </c> bytes from the byte array <c> buffer </c> starting at position <c> offset </c> to this stream.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// write", "/// </java-name>", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Writes a single byte to this stream. Only the least significant byte of the integer <c> oneByte </c> is written to the stream.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// write", "/// </java-name>", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Writes a single byte to this stream. Only the least significant byte of the integer <c> oneByte </c> is written to the stream.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// write", "/// </java-name>", "/* MethodBuilder.Create */", "/// <summary>", "/// <para>Writes a single byte to this stream. Only the least significant byte of the integer <c> oneByte </c> is written to the stream.</para><para></para> ", "/// </summary>", "/// <java-name>", "/// write", "/// </java-name>", "/* MethodBuilder.Create */", "/* TypeBuilder.AddDefaultConstructor */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "java-name", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
13
424
88
14ae426f69cbe23808b37843a49580f5eb89d829
TomMD/pinot
pinot-core/src/main/java/com/linkedin/pinot/core/query/selection/SelectionOperatorService.java
[ "Apache-2.0" ]
Java
SelectionOperatorService
/** * The <code>SelectionOperatorService</code> class provides the services for selection queries with * <code>ORDER BY</code>. * <p>Expected behavior: * <ul> * <li> * Return selection results with the same order of columns as user passed in. * <ul> * <li>Eg. SELECT colB, colA, colC FROM table -> [valB, valA, valC]</li> * </ul> * </li> * <li> * For 'SELECT *', return columns with alphabetically order. * <ul> * <li>Eg. SELECT * FROM table -> [valA, valB, valC]</li> * </ul> * </li> * <li> * Order by does not change the order of columns in selection results. * <ul> * <li>Eg. SELECT colB, colA, colC FROM table ORDER BY calC -> [valB, valA, valC]</li> * </ul> * </li> * </ul> */
The SelectionOperatorService class provides the services for selection queries with ORDER BY. Expected behavior: Return selection results with the same order of columns as user passed in. Eg. SELECT colB, colA, colC FROM table -> [valB, valA, valC] For 'SELECT *', return columns with alphabetically order. Eg. SELECT * FROM table -> [valA, valB, valC] Order by does not change the order of columns in selection results. Eg. SELECT colB, colA, colC FROM table ORDER BY calC -> [valB, valA, valC]
[ "The", "SelectionOperatorService", "class", "provides", "the", "services", "for", "selection", "queries", "with", "ORDER", "BY", ".", "Expected", "behavior", ":", "Return", "selection", "results", "with", "the", "same", "order", "of", "columns", "as", "user", "passed", "in", ".", "Eg", ".", "SELECT", "colB", "colA", "colC", "FROM", "table", "-", ">", "[", "valB", "valA", "valC", "]", "For", "'", "SELECT", "*", "'", "return", "columns", "with", "alphabetically", "order", ".", "Eg", ".", "SELECT", "*", "FROM", "table", "-", ">", "[", "valA", "valB", "valC", "]", "Order", "by", "does", "not", "change", "the", "order", "of", "columns", "in", "selection", "results", ".", "Eg", ".", "SELECT", "colB", "colA", "colC", "FROM", "table", "ORDER", "BY", "calC", "-", ">", "[", "valB", "valA", "valC", "]" ]
public class SelectionOperatorService { private final List<String> _selectionColumns; private final List<SelectionSort> _sortSequence; private final DataSchema _dataSchema; private final int _selectionOffset; private final int _maxNumRows; private final PriorityQueue<Serializable[]> _rows; private long _numDocsScanned = 0; /** * Constructor for <code>SelectionOperatorService</code> with {@link IndexSegment}. (Inner segment) * * @param selection selection query. * @param indexSegment index segment. */ public SelectionOperatorService(@Nonnull Selection selection, @Nonnull IndexSegment indexSegment) { _selectionColumns = SelectionOperatorUtils.getSelectionColumns(selection.getSelectionColumns(), indexSegment); _sortSequence = getSortSequence(selection.getSelectionSortSequence()); _dataSchema = SelectionOperatorUtils.extractDataSchema(_sortSequence, _selectionColumns, indexSegment); // Select rows from offset to offset + size. _selectionOffset = selection.getOffset(); _maxNumRows = _selectionOffset + selection.getSize(); _rows = new PriorityQueue<>(_maxNumRows, getStrictComparator()); } /** * Constructor for <code>SelectionOperatorService</code> with {@link DataSchema}. (Inter segment) * * @param selection selection query. * @param dataSchema data schema. */ public SelectionOperatorService(@Nonnull Selection selection, @Nonnull DataSchema dataSchema) { _selectionColumns = SelectionOperatorUtils.getSelectionColumns(selection.getSelectionColumns(), dataSchema); _sortSequence = getSortSequence(selection.getSelectionSortSequence()); _dataSchema = dataSchema; // Select rows from offset to offset + size. _selectionOffset = selection.getOffset(); _maxNumRows = _selectionOffset + selection.getSize(); _rows = new PriorityQueue<>(_maxNumRows, getTypeCompatibleComparator()); } /** * Helper method to handle duplicate sort columns. * * @return de-duplicated list of sort sequences. */ @Nonnull private List<SelectionSort> getSortSequence(List<SelectionSort> selectionSorts) { List<SelectionSort> deDupedSelectionSorts = new ArrayList<>(); Set<String> sortColumns = new HashSet<>(); for (SelectionSort selectionSort : selectionSorts) { String sortColumn = selectionSort.getColumn(); if (!sortColumns.contains(sortColumn)) { deDupedSelectionSorts.add(selectionSort); sortColumns.add(sortColumn); } } return deDupedSelectionSorts; } /** * Helper method to get the strict {@link Comparator} for selection rows. (Inner segment) * <p>Strict comparator does not allow any schema mismatch (more performance driven). * * @return strict {@link Comparator} for selection rows. */ @Nonnull private Comparator<Serializable[]> getStrictComparator() { return new Comparator<Serializable[]>() { @Override public int compare(Serializable[] o1, Serializable[] o2) { int numSortColumns = _sortSequence.size(); for (int i = 0; i < numSortColumns; i++) { int ret = 0; SelectionSort selectionSort = _sortSequence.get(i); Serializable v1 = o1[i]; Serializable v2 = o2[i]; // Only compare single-value columns. switch (_dataSchema.getColumnDataType(i)) { case INT: if (!selectionSort.isIsAsc()) { ret = ((Integer) v1).compareTo((Integer) v2); } else { ret = ((Integer) v2).compareTo((Integer) v1); } break; case LONG: if (!selectionSort.isIsAsc()) { ret = ((Long) v1).compareTo((Long) v2); } else { ret = ((Long) v2).compareTo((Long) v1); } break; case FLOAT: if (!selectionSort.isIsAsc()) { ret = ((Float) v1).compareTo((Float) v2); } else { ret = ((Float) v2).compareTo((Float) v1); } break; case DOUBLE: if (!selectionSort.isIsAsc()) { ret = ((Double) v1).compareTo((Double) v2); } else { ret = ((Double) v2).compareTo((Double) v1); } break; case STRING: if (!selectionSort.isIsAsc()) { ret = ((String) v1).compareTo((String) v2); } else { ret = ((String) v2).compareTo((String) v1); } break; default: break; } if (ret != 0) { return ret; } } return 0; } }; } /** * Helper method to get the type-compatible {@link Comparator} for selection rows. (Inter segment) * <p>Type-compatible comparator allows compatible types to compare with each other. * * @return flexible {@link Comparator} for selection rows. */ @Nonnull private Comparator<Serializable[]> getTypeCompatibleComparator() { return new Comparator<Serializable[]>() { @Override public int compare(Serializable[] o1, Serializable[] o2) { int numSortColumns = _sortSequence.size(); for (int i = 0; i < numSortColumns; i++) { int ret = 0; SelectionSort selectionSort = _sortSequence.get(i); Serializable v1 = o1[i]; Serializable v2 = o2[i]; // Only compare single-value columns. if (v1 instanceof Number) { if (!selectionSort.isIsAsc()) { ret = Double.compare(((Number) v1).doubleValue(), ((Number) v2).doubleValue()); } else { ret = Double.compare(((Number) v2).doubleValue(), ((Number) v1).doubleValue()); } } else if (v1 instanceof String) { if (!selectionSort.isIsAsc()) { ret = ((String) v1).compareTo((String) v2); } else { ret = ((String) v2).compareTo((String) v1); } } if (ret != 0) { return ret; } } return 0; } }; } /** * Get the {@link DataSchema}. * * @return data schema. */ @Nonnull public DataSchema getDataSchema() { return _dataSchema; } /** * Get the selection results. * * @return selection results. */ @Nonnull public PriorityQueue<Serializable[]> getRows() { return _rows; } /** * Get number of documents scanned. (Inner segment) * * @return number of documents scanned. */ public long getNumDocsScanned() { return _numDocsScanned; } /** * Iterate over {@link Block}s, extract values from them and merge the values to the selection results for selection * queries with <code>ORDER BY</code>. (Inner segment) * * @param blockDocIdIterator block document id iterator. * @param blocks {@link Block} array. */ public void iterateOnBlocksWithOrdering(@Nonnull BlockDocIdIterator blockDocIdIterator, @Nonnull Block[] blocks) { Comparator<Integer> rowDocIdComparator = new CompositeDocIdValComparator(_sortSequence, blocks); PriorityQueue<Integer> rowDocIdPriorityQueue = new PriorityQueue<>(_maxNumRows, rowDocIdComparator); int docId; while ((docId = blockDocIdIterator.next()) != Constants.EOF) { _numDocsScanned++; SelectionOperatorUtils.addToPriorityQueue(docId, rowDocIdPriorityQueue, _maxNumRows); } SelectionFetcher selectionFetcher = new SelectionFetcher(blocks, _dataSchema); Collection<Serializable[]> rows = new ArrayList<>(rowDocIdPriorityQueue.size()); for (int rowDocId : rowDocIdPriorityQueue) { rows.add(selectionFetcher.getRow(rowDocId)); } SelectionOperatorUtils.mergeWithOrdering(_rows, rows, _maxNumRows); } /** * Reduce a collection of {@link DataTable}s to selection rows for selection queries with <code>ORDER BY</code>. * (Broker side) * * @param selectionResults {@link Map} from {@link ServerInstance} to {@link DataTable}. */ public void reduceWithOrdering(@Nonnull Map<ServerInstance, DataTable> selectionResults) { for (DataTable dataTable : selectionResults.values()) { int numRows = dataTable.getNumberOfRows(); for (int rowId = 0; rowId < numRows; rowId++) { Serializable[] row = SelectionOperatorUtils.extractRowFromDataTable(dataTable, rowId); SelectionOperatorUtils.addToPriorityQueue(row, _rows, _maxNumRows); } } } /** * Render the unformatted selection rows to a formatted {@link SelectionResults} object for selection queries with * <code>ORDER BY</code>. (Broker side) * <p>{@link SelectionResults} object will be used to build the broker response. * <p>Should be called after method "reduceWithOrdering()". * * @return {@link SelectionResults} object results. */ @Nonnull public SelectionResults renderSelectionResultsWithOrdering() { LinkedList<Serializable[]> rowsInSelectionResults = new LinkedList<>(); int[] columnIndices = getColumnIndices(); while (_rows.size() > _selectionOffset) { rowsInSelectionResults.addFirst(getFormattedRowWithOrdering(_rows.poll(), columnIndices)); } return new SelectionResults(_selectionColumns, rowsInSelectionResults); } /** * Helper method to get each selection column index in data schema. * * @return column indices. */ private int[] getColumnIndices() { int numSelectionColumns = _selectionColumns.size(); int[] columnIndices = new int[numSelectionColumns]; int numColumnsInDataSchema = _dataSchema.size(); Map<String, Integer> dataSchemaIndices = new HashMap<>(numColumnsInDataSchema); for (int i = 0; i < numColumnsInDataSchema; i++) { dataSchemaIndices.put(_dataSchema.getColumnName(i), i); } for (int i = 0; i < numSelectionColumns; i++) { columnIndices[i] = dataSchemaIndices.get(_selectionColumns.get(i)); } return columnIndices; } /** * Helper method to format a selection row, make all values string or string array type based on data schema passed in * for selection queries with <code>ORDER BY</code>. (Broker side) * <p>Formatted row is used to build the {@link SelectionResults}. * * @param row selection row to be formatted. * @param columnIndices column indices of original rows. * @return formatted selection row. */ @Nonnull private Serializable[] getFormattedRowWithOrdering(@Nonnull Serializable[] row, @Nonnull int[] columnIndices) { int numColumns = columnIndices.length; Serializable[] formattedRow = new Serializable[numColumns]; for (int i = 0; i < numColumns; i++) { int columnIndex = columnIndices[i]; formattedRow[i] = SelectionOperatorUtils.getFormattedValue(row[columnIndex], _dataSchema.getColumnDataType(columnIndex)); } return formattedRow; } }
[ "public", "class", "SelectionOperatorService", "{", "private", "final", "List", "<", "String", ">", "_selectionColumns", ";", "private", "final", "List", "<", "SelectionSort", ">", "_sortSequence", ";", "private", "final", "DataSchema", "_dataSchema", ";", "private", "final", "int", "_selectionOffset", ";", "private", "final", "int", "_maxNumRows", ";", "private", "final", "PriorityQueue", "<", "Serializable", "[", "]", ">", "_rows", ";", "private", "long", "_numDocsScanned", "=", "0", ";", "/**\n * Constructor for <code>SelectionOperatorService</code> with {@link IndexSegment}. (Inner segment)\n *\n * @param selection selection query.\n * @param indexSegment index segment.\n */", "public", "SelectionOperatorService", "(", "@", "Nonnull", "Selection", "selection", ",", "@", "Nonnull", "IndexSegment", "indexSegment", ")", "{", "_selectionColumns", "=", "SelectionOperatorUtils", ".", "getSelectionColumns", "(", "selection", ".", "getSelectionColumns", "(", ")", ",", "indexSegment", ")", ";", "_sortSequence", "=", "getSortSequence", "(", "selection", ".", "getSelectionSortSequence", "(", ")", ")", ";", "_dataSchema", "=", "SelectionOperatorUtils", ".", "extractDataSchema", "(", "_sortSequence", ",", "_selectionColumns", ",", "indexSegment", ")", ";", "_selectionOffset", "=", "selection", ".", "getOffset", "(", ")", ";", "_maxNumRows", "=", "_selectionOffset", "+", "selection", ".", "getSize", "(", ")", ";", "_rows", "=", "new", "PriorityQueue", "<", ">", "(", "_maxNumRows", ",", "getStrictComparator", "(", ")", ")", ";", "}", "/**\n * Constructor for <code>SelectionOperatorService</code> with {@link DataSchema}. (Inter segment)\n *\n * @param selection selection query.\n * @param dataSchema data schema.\n */", "public", "SelectionOperatorService", "(", "@", "Nonnull", "Selection", "selection", ",", "@", "Nonnull", "DataSchema", "dataSchema", ")", "{", "_selectionColumns", "=", "SelectionOperatorUtils", ".", "getSelectionColumns", "(", "selection", ".", "getSelectionColumns", "(", ")", ",", "dataSchema", ")", ";", "_sortSequence", "=", "getSortSequence", "(", "selection", ".", "getSelectionSortSequence", "(", ")", ")", ";", "_dataSchema", "=", "dataSchema", ";", "_selectionOffset", "=", "selection", ".", "getOffset", "(", ")", ";", "_maxNumRows", "=", "_selectionOffset", "+", "selection", ".", "getSize", "(", ")", ";", "_rows", "=", "new", "PriorityQueue", "<", ">", "(", "_maxNumRows", ",", "getTypeCompatibleComparator", "(", ")", ")", ";", "}", "/**\n * Helper method to handle duplicate sort columns.\n *\n * @return de-duplicated list of sort sequences.\n */", "@", "Nonnull", "private", "List", "<", "SelectionSort", ">", "getSortSequence", "(", "List", "<", "SelectionSort", ">", "selectionSorts", ")", "{", "List", "<", "SelectionSort", ">", "deDupedSelectionSorts", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "Set", "<", "String", ">", "sortColumns", "=", "new", "HashSet", "<", ">", "(", ")", ";", "for", "(", "SelectionSort", "selectionSort", ":", "selectionSorts", ")", "{", "String", "sortColumn", "=", "selectionSort", ".", "getColumn", "(", ")", ";", "if", "(", "!", "sortColumns", ".", "contains", "(", "sortColumn", ")", ")", "{", "deDupedSelectionSorts", ".", "add", "(", "selectionSort", ")", ";", "sortColumns", ".", "add", "(", "sortColumn", ")", ";", "}", "}", "return", "deDupedSelectionSorts", ";", "}", "/**\n * Helper method to get the strict {@link Comparator} for selection rows. (Inner segment)\n * <p>Strict comparator does not allow any schema mismatch (more performance driven).\n *\n * @return strict {@link Comparator} for selection rows.\n */", "@", "Nonnull", "private", "Comparator", "<", "Serializable", "[", "]", ">", "getStrictComparator", "(", ")", "{", "return", "new", "Comparator", "<", "Serializable", "[", "]", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "Serializable", "[", "]", "o1", ",", "Serializable", "[", "]", "o2", ")", "{", "int", "numSortColumns", "=", "_sortSequence", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numSortColumns", ";", "i", "++", ")", "{", "int", "ret", "=", "0", ";", "SelectionSort", "selectionSort", "=", "_sortSequence", ".", "get", "(", "i", ")", ";", "Serializable", "v1", "=", "o1", "[", "i", "]", ";", "Serializable", "v2", "=", "o2", "[", "i", "]", ";", "switch", "(", "_dataSchema", ".", "getColumnDataType", "(", "i", ")", ")", "{", "case", "INT", ":", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "(", "(", "Integer", ")", "v1", ")", ".", "compareTo", "(", "(", "Integer", ")", "v2", ")", ";", "}", "else", "{", "ret", "=", "(", "(", "Integer", ")", "v2", ")", ".", "compareTo", "(", "(", "Integer", ")", "v1", ")", ";", "}", "break", ";", "case", "LONG", ":", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "(", "(", "Long", ")", "v1", ")", ".", "compareTo", "(", "(", "Long", ")", "v2", ")", ";", "}", "else", "{", "ret", "=", "(", "(", "Long", ")", "v2", ")", ".", "compareTo", "(", "(", "Long", ")", "v1", ")", ";", "}", "break", ";", "case", "FLOAT", ":", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "(", "(", "Float", ")", "v1", ")", ".", "compareTo", "(", "(", "Float", ")", "v2", ")", ";", "}", "else", "{", "ret", "=", "(", "(", "Float", ")", "v2", ")", ".", "compareTo", "(", "(", "Float", ")", "v1", ")", ";", "}", "break", ";", "case", "DOUBLE", ":", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "(", "(", "Double", ")", "v1", ")", ".", "compareTo", "(", "(", "Double", ")", "v2", ")", ";", "}", "else", "{", "ret", "=", "(", "(", "Double", ")", "v2", ")", ".", "compareTo", "(", "(", "Double", ")", "v1", ")", ";", "}", "break", ";", "case", "STRING", ":", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "(", "(", "String", ")", "v1", ")", ".", "compareTo", "(", "(", "String", ")", "v2", ")", ";", "}", "else", "{", "ret", "=", "(", "(", "String", ")", "v2", ")", ".", "compareTo", "(", "(", "String", ")", "v1", ")", ";", "}", "break", ";", "default", ":", "break", ";", "}", "if", "(", "ret", "!=", "0", ")", "{", "return", "ret", ";", "}", "}", "return", "0", ";", "}", "}", ";", "}", "/**\n * Helper method to get the type-compatible {@link Comparator} for selection rows. (Inter segment)\n * <p>Type-compatible comparator allows compatible types to compare with each other.\n *\n * @return flexible {@link Comparator} for selection rows.\n */", "@", "Nonnull", "private", "Comparator", "<", "Serializable", "[", "]", ">", "getTypeCompatibleComparator", "(", ")", "{", "return", "new", "Comparator", "<", "Serializable", "[", "]", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "Serializable", "[", "]", "o1", ",", "Serializable", "[", "]", "o2", ")", "{", "int", "numSortColumns", "=", "_sortSequence", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numSortColumns", ";", "i", "++", ")", "{", "int", "ret", "=", "0", ";", "SelectionSort", "selectionSort", "=", "_sortSequence", ".", "get", "(", "i", ")", ";", "Serializable", "v1", "=", "o1", "[", "i", "]", ";", "Serializable", "v2", "=", "o2", "[", "i", "]", ";", "if", "(", "v1", "instanceof", "Number", ")", "{", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "Double", ".", "compare", "(", "(", "(", "Number", ")", "v1", ")", ".", "doubleValue", "(", ")", ",", "(", "(", "Number", ")", "v2", ")", ".", "doubleValue", "(", ")", ")", ";", "}", "else", "{", "ret", "=", "Double", ".", "compare", "(", "(", "(", "Number", ")", "v2", ")", ".", "doubleValue", "(", ")", ",", "(", "(", "Number", ")", "v1", ")", ".", "doubleValue", "(", ")", ")", ";", "}", "}", "else", "if", "(", "v1", "instanceof", "String", ")", "{", "if", "(", "!", "selectionSort", ".", "isIsAsc", "(", ")", ")", "{", "ret", "=", "(", "(", "String", ")", "v1", ")", ".", "compareTo", "(", "(", "String", ")", "v2", ")", ";", "}", "else", "{", "ret", "=", "(", "(", "String", ")", "v2", ")", ".", "compareTo", "(", "(", "String", ")", "v1", ")", ";", "}", "}", "if", "(", "ret", "!=", "0", ")", "{", "return", "ret", ";", "}", "}", "return", "0", ";", "}", "}", ";", "}", "/**\n * Get the {@link DataSchema}.\n *\n * @return data schema.\n */", "@", "Nonnull", "public", "DataSchema", "getDataSchema", "(", ")", "{", "return", "_dataSchema", ";", "}", "/**\n * Get the selection results.\n *\n * @return selection results.\n */", "@", "Nonnull", "public", "PriorityQueue", "<", "Serializable", "[", "]", ">", "getRows", "(", ")", "{", "return", "_rows", ";", "}", "/**\n * Get number of documents scanned. (Inner segment)\n *\n * @return number of documents scanned.\n */", "public", "long", "getNumDocsScanned", "(", ")", "{", "return", "_numDocsScanned", ";", "}", "/**\n * Iterate over {@link Block}s, extract values from them and merge the values to the selection results for selection\n * queries with <code>ORDER BY</code>. (Inner segment)\n *\n * @param blockDocIdIterator block document id iterator.\n * @param blocks {@link Block} array.\n */", "public", "void", "iterateOnBlocksWithOrdering", "(", "@", "Nonnull", "BlockDocIdIterator", "blockDocIdIterator", ",", "@", "Nonnull", "Block", "[", "]", "blocks", ")", "{", "Comparator", "<", "Integer", ">", "rowDocIdComparator", "=", "new", "CompositeDocIdValComparator", "(", "_sortSequence", ",", "blocks", ")", ";", "PriorityQueue", "<", "Integer", ">", "rowDocIdPriorityQueue", "=", "new", "PriorityQueue", "<", ">", "(", "_maxNumRows", ",", "rowDocIdComparator", ")", ";", "int", "docId", ";", "while", "(", "(", "docId", "=", "blockDocIdIterator", ".", "next", "(", ")", ")", "!=", "Constants", ".", "EOF", ")", "{", "_numDocsScanned", "++", ";", "SelectionOperatorUtils", ".", "addToPriorityQueue", "(", "docId", ",", "rowDocIdPriorityQueue", ",", "_maxNumRows", ")", ";", "}", "SelectionFetcher", "selectionFetcher", "=", "new", "SelectionFetcher", "(", "blocks", ",", "_dataSchema", ")", ";", "Collection", "<", "Serializable", "[", "]", ">", "rows", "=", "new", "ArrayList", "<", ">", "(", "rowDocIdPriorityQueue", ".", "size", "(", ")", ")", ";", "for", "(", "int", "rowDocId", ":", "rowDocIdPriorityQueue", ")", "{", "rows", ".", "add", "(", "selectionFetcher", ".", "getRow", "(", "rowDocId", ")", ")", ";", "}", "SelectionOperatorUtils", ".", "mergeWithOrdering", "(", "_rows", ",", "rows", ",", "_maxNumRows", ")", ";", "}", "/**\n * Reduce a collection of {@link DataTable}s to selection rows for selection queries with <code>ORDER BY</code>.\n * (Broker side)\n *\n * @param selectionResults {@link Map} from {@link ServerInstance} to {@link DataTable}.\n */", "public", "void", "reduceWithOrdering", "(", "@", "Nonnull", "Map", "<", "ServerInstance", ",", "DataTable", ">", "selectionResults", ")", "{", "for", "(", "DataTable", "dataTable", ":", "selectionResults", ".", "values", "(", ")", ")", "{", "int", "numRows", "=", "dataTable", ".", "getNumberOfRows", "(", ")", ";", "for", "(", "int", "rowId", "=", "0", ";", "rowId", "<", "numRows", ";", "rowId", "++", ")", "{", "Serializable", "[", "]", "row", "=", "SelectionOperatorUtils", ".", "extractRowFromDataTable", "(", "dataTable", ",", "rowId", ")", ";", "SelectionOperatorUtils", ".", "addToPriorityQueue", "(", "row", ",", "_rows", ",", "_maxNumRows", ")", ";", "}", "}", "}", "/**\n * Render the unformatted selection rows to a formatted {@link SelectionResults} object for selection queries with\n * <code>ORDER BY</code>. (Broker side)\n * <p>{@link SelectionResults} object will be used to build the broker response.\n * <p>Should be called after method \"reduceWithOrdering()\".\n *\n * @return {@link SelectionResults} object results.\n */", "@", "Nonnull", "public", "SelectionResults", "renderSelectionResultsWithOrdering", "(", ")", "{", "LinkedList", "<", "Serializable", "[", "]", ">", "rowsInSelectionResults", "=", "new", "LinkedList", "<", ">", "(", ")", ";", "int", "[", "]", "columnIndices", "=", "getColumnIndices", "(", ")", ";", "while", "(", "_rows", ".", "size", "(", ")", ">", "_selectionOffset", ")", "{", "rowsInSelectionResults", ".", "addFirst", "(", "getFormattedRowWithOrdering", "(", "_rows", ".", "poll", "(", ")", ",", "columnIndices", ")", ")", ";", "}", "return", "new", "SelectionResults", "(", "_selectionColumns", ",", "rowsInSelectionResults", ")", ";", "}", "/**\n * Helper method to get each selection column index in data schema.\n *\n * @return column indices.\n */", "private", "int", "[", "]", "getColumnIndices", "(", ")", "{", "int", "numSelectionColumns", "=", "_selectionColumns", ".", "size", "(", ")", ";", "int", "[", "]", "columnIndices", "=", "new", "int", "[", "numSelectionColumns", "]", ";", "int", "numColumnsInDataSchema", "=", "_dataSchema", ".", "size", "(", ")", ";", "Map", "<", "String", ",", "Integer", ">", "dataSchemaIndices", "=", "new", "HashMap", "<", ">", "(", "numColumnsInDataSchema", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numColumnsInDataSchema", ";", "i", "++", ")", "{", "dataSchemaIndices", ".", "put", "(", "_dataSchema", ".", "getColumnName", "(", "i", ")", ",", "i", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numSelectionColumns", ";", "i", "++", ")", "{", "columnIndices", "[", "i", "]", "=", "dataSchemaIndices", ".", "get", "(", "_selectionColumns", ".", "get", "(", "i", ")", ")", ";", "}", "return", "columnIndices", ";", "}", "/**\n * Helper method to format a selection row, make all values string or string array type based on data schema passed in\n * for selection queries with <code>ORDER BY</code>. (Broker side)\n * <p>Formatted row is used to build the {@link SelectionResults}.\n *\n * @param row selection row to be formatted.\n * @param columnIndices column indices of original rows.\n * @return formatted selection row.\n */", "@", "Nonnull", "private", "Serializable", "[", "]", "getFormattedRowWithOrdering", "(", "@", "Nonnull", "Serializable", "[", "]", "row", ",", "@", "Nonnull", "int", "[", "]", "columnIndices", ")", "{", "int", "numColumns", "=", "columnIndices", ".", "length", ";", "Serializable", "[", "]", "formattedRow", "=", "new", "Serializable", "[", "numColumns", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "numColumns", ";", "i", "++", ")", "{", "int", "columnIndex", "=", "columnIndices", "[", "i", "]", ";", "formattedRow", "[", "i", "]", "=", "SelectionOperatorUtils", ".", "getFormattedValue", "(", "row", "[", "columnIndex", "]", ",", "_dataSchema", ".", "getColumnDataType", "(", "columnIndex", ")", ")", ";", "}", "return", "formattedRow", ";", "}", "}" ]
The <code>SelectionOperatorService</code> class provides the services for selection queries with <code>ORDER BY</code>.
[ "The", "<code", ">", "SelectionOperatorService<", "/", "code", ">", "class", "provides", "the", "services", "for", "selection", "queries", "with", "<code", ">", "ORDER", "BY<", "/", "code", ">", "." ]
[ "// Select rows from offset to offset + size.", "// Select rows from offset to offset + size.", "// Only compare single-value columns.", "// Only compare single-value columns." ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
23
2,479
241
8d85ec56313426b6a9fe0fdbf24c6b28b912b888
fillumina/PerformanceTools
performance-tools/src/main/java/com/fillumina/performance/producer/progression/AutoProgressionPerformanceInstrumenter.java
[ "Apache-2.0" ]
Java
AutoProgressionPerformanceInstrumenter
/** * Instrumenter that increases the number of iterations until a target * stability is met. * <p> * It produces statistics based on the average results of the last round of * iterations. * Beware that the execution can be very long so set a sensible timeout and, * if it takes too long, try to relax the maximum allowed standard deviation. * * @author Francesco Illuminati */
Instrumenter that increases the number of iterations until a target stability is met. It produces statistics based on the average results of the last round of iterations. Beware that the execution can be very long so set a sensible timeout and, if it takes too long, try to relax the maximum allowed standard deviation. @author Francesco Illuminati
[ "Instrumenter", "that", "increases", "the", "number", "of", "iterations", "until", "a", "target", "stability", "is", "met", ".", "It", "produces", "statistics", "based", "on", "the", "average", "results", "of", "the", "last", "round", "of", "iterations", ".", "Beware", "that", "the", "execution", "can", "be", "very", "long", "so", "set", "a", "sensible", "timeout", "and", "if", "it", "takes", "too", "long", "try", "to", "relax", "the", "maximum", "allowed", "standard", "deviation", ".", "@author", "Francesco", "Illuminati" ]
public class AutoProgressionPerformanceInstrumenter extends AbstractInstrumentablePerformanceProducer <AutoProgressionPerformanceInstrumenter> implements Serializable, InstrumentablePerformanceExecutor<AutoProgressionPerformanceInstrumenter>, PerformanceExecutorInstrumenter { private static final long serialVersionUID = 1L; private final ProgressionPerformanceInstrumenter progressionPerformance; private List<StandardDeviationConsumer> standardDeviationConsumers = new ArrayList<>(); /** * Creates a new instance using a builder with a * <i><a href='http://en.wikipedia.org/wiki/Fluent_interface'> * fluent interface</a></i>. */ public static AutoProgressionPerformanceInstrumenterBuilder builder() { return new AutoProgressionPerformanceInstrumenterBuilder(); } public AutoProgressionPerformanceInstrumenter( final AutoProgressionPerformanceInstrumenterBuilder builder) { final ProgressionPerformanceInstrumenterBuilder ppiBuilder = new ProgressionPerformanceInstrumenterBuilder(); ppiBuilder.setMessage(builder.getMessage()); ppiBuilder.setBaseAndMagnitude(builder.getBaseIterations(), 8); ppiBuilder.setSamplesPerStep(builder.getSamplesPerStep()); ppiBuilder.setCheckStdDeviation(builder.isCheckStdDeviation()); ppiBuilder.setTimeoutInNanoseconds(builder.getTimeoutInNanoseconds()); this.progressionPerformance = new ProgressionPerformanceInstrumenter(ppiBuilder) { private static final long serialVersionUID = 1L; @Override protected boolean stopIterating( final LoopPerformancesSequence performances) { final double stdDev = performances.calculateMaximumStandardDeviation(); callStandardDeviationConsumers( performances.getAverageIterations(), performances.getSamples(), stdDev); return stdDev < builder.getMaxStandardDeviation(); } }; } public AutoProgressionPerformanceInstrumenter( final ProgressionPerformanceInstrumenter progressionPerformance) { this.progressionPerformance = progressionPerformance; } @Override public AutoProgressionPerformanceInstrumenter instrument( final InstrumentablePerformanceExecutor<?> performanceExecutor) { progressionPerformance.instrument(performanceExecutor); return this; } @Override public AutoProgressionPerformanceInstrumenter ignoreTest( final String name, final Runnable test) { return this; } @Override public AutoProgressionPerformanceInstrumenter addTest( final String name, final Runnable test) { progressionPerformance.addTest(name, test); return this; } @Override public AutoProgressionPerformanceInstrumenter addPerformanceConsumer(final PerformanceConsumer... consumers) { progressionPerformance.addPerformanceConsumer(consumers); return this; } @Override public AutoProgressionPerformanceInstrumenter removePerformanceConsumer(final PerformanceConsumer... consumers) { progressionPerformance.removePerformanceConsumer(consumers); return this; } @Override public LoopPerformancesHolder execute() { return progressionPerformance.execute(); } @Override public AutoProgressionPerformanceInstrumenter warmup() { progressionPerformance.warmup(); return this; } /** * Adds a {@link StandardDeviationConsumer} that will be called at every * step with the average standard deviation of all the {@code samples} * of that step. * @param consumers the {@link StandardDeviationConsumer} * @return {@code this} to allow for <i>fluent interface</i> */ public AutoProgressionPerformanceInstrumenter addStandardDeviationConsumer( final StandardDeviationConsumer... consumers) { for (final StandardDeviationConsumer consumer: consumers) { if (consumer != null) { standardDeviationConsumers.add(consumer); } } return this; } private void callStandardDeviationConsumers( final long iterations, final long samples, final double stdDev) { for (final StandardDeviationConsumer consumer: standardDeviationConsumers) { consumer.consume(iterations, samples, stdDev); } } }
[ "public", "class", "AutoProgressionPerformanceInstrumenter", "extends", "AbstractInstrumentablePerformanceProducer", "<", "AutoProgressionPerformanceInstrumenter", ">", "implements", "Serializable", ",", "InstrumentablePerformanceExecutor", "<", "AutoProgressionPerformanceInstrumenter", ">", ",", "PerformanceExecutorInstrumenter", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "final", "ProgressionPerformanceInstrumenter", "progressionPerformance", ";", "private", "List", "<", "StandardDeviationConsumer", ">", "standardDeviationConsumers", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "/**\n * Creates a new instance using a builder with a\n * <i><a href='http://en.wikipedia.org/wiki/Fluent_interface'>\n * fluent interface</a></i>.\n */", "public", "static", "AutoProgressionPerformanceInstrumenterBuilder", "builder", "(", ")", "{", "return", "new", "AutoProgressionPerformanceInstrumenterBuilder", "(", ")", ";", "}", "public", "AutoProgressionPerformanceInstrumenter", "(", "final", "AutoProgressionPerformanceInstrumenterBuilder", "builder", ")", "{", "final", "ProgressionPerformanceInstrumenterBuilder", "ppiBuilder", "=", "new", "ProgressionPerformanceInstrumenterBuilder", "(", ")", ";", "ppiBuilder", ".", "setMessage", "(", "builder", ".", "getMessage", "(", ")", ")", ";", "ppiBuilder", ".", "setBaseAndMagnitude", "(", "builder", ".", "getBaseIterations", "(", ")", ",", "8", ")", ";", "ppiBuilder", ".", "setSamplesPerStep", "(", "builder", ".", "getSamplesPerStep", "(", ")", ")", ";", "ppiBuilder", ".", "setCheckStdDeviation", "(", "builder", ".", "isCheckStdDeviation", "(", ")", ")", ";", "ppiBuilder", ".", "setTimeoutInNanoseconds", "(", "builder", ".", "getTimeoutInNanoseconds", "(", ")", ")", ";", "this", ".", "progressionPerformance", "=", "new", "ProgressionPerformanceInstrumenter", "(", "ppiBuilder", ")", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "@", "Override", "protected", "boolean", "stopIterating", "(", "final", "LoopPerformancesSequence", "performances", ")", "{", "final", "double", "stdDev", "=", "performances", ".", "calculateMaximumStandardDeviation", "(", ")", ";", "callStandardDeviationConsumers", "(", "performances", ".", "getAverageIterations", "(", ")", ",", "performances", ".", "getSamples", "(", ")", ",", "stdDev", ")", ";", "return", "stdDev", "<", "builder", ".", "getMaxStandardDeviation", "(", ")", ";", "}", "}", ";", "}", "public", "AutoProgressionPerformanceInstrumenter", "(", "final", "ProgressionPerformanceInstrumenter", "progressionPerformance", ")", "{", "this", ".", "progressionPerformance", "=", "progressionPerformance", ";", "}", "@", "Override", "public", "AutoProgressionPerformanceInstrumenter", "instrument", "(", "final", "InstrumentablePerformanceExecutor", "<", "?", ">", "performanceExecutor", ")", "{", "progressionPerformance", ".", "instrument", "(", "performanceExecutor", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AutoProgressionPerformanceInstrumenter", "ignoreTest", "(", "final", "String", "name", ",", "final", "Runnable", "test", ")", "{", "return", "this", ";", "}", "@", "Override", "public", "AutoProgressionPerformanceInstrumenter", "addTest", "(", "final", "String", "name", ",", "final", "Runnable", "test", ")", "{", "progressionPerformance", ".", "addTest", "(", "name", ",", "test", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AutoProgressionPerformanceInstrumenter", "addPerformanceConsumer", "(", "final", "PerformanceConsumer", "...", "consumers", ")", "{", "progressionPerformance", ".", "addPerformanceConsumer", "(", "consumers", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "AutoProgressionPerformanceInstrumenter", "removePerformanceConsumer", "(", "final", "PerformanceConsumer", "...", "consumers", ")", "{", "progressionPerformance", ".", "removePerformanceConsumer", "(", "consumers", ")", ";", "return", "this", ";", "}", "@", "Override", "public", "LoopPerformancesHolder", "execute", "(", ")", "{", "return", "progressionPerformance", ".", "execute", "(", ")", ";", "}", "@", "Override", "public", "AutoProgressionPerformanceInstrumenter", "warmup", "(", ")", "{", "progressionPerformance", ".", "warmup", "(", ")", ";", "return", "this", ";", "}", "/**\n * Adds a {@link StandardDeviationConsumer} that will be called at every\n * step with the average standard deviation of all the {@code samples}\n * of that step.\n * @param consumers the {@link StandardDeviationConsumer}\n * @return {@code this} to allow for <i>fluent interface</i>\n */", "public", "AutoProgressionPerformanceInstrumenter", "addStandardDeviationConsumer", "(", "final", "StandardDeviationConsumer", "...", "consumers", ")", "{", "for", "(", "final", "StandardDeviationConsumer", "consumer", ":", "consumers", ")", "{", "if", "(", "consumer", "!=", "null", ")", "{", "standardDeviationConsumers", ".", "add", "(", "consumer", ")", ";", "}", "}", "return", "this", ";", "}", "private", "void", "callStandardDeviationConsumers", "(", "final", "long", "iterations", ",", "final", "long", "samples", ",", "final", "double", "stdDev", ")", "{", "for", "(", "final", "StandardDeviationConsumer", "consumer", ":", "standardDeviationConsumers", ")", "{", "consumer", ".", "consume", "(", "iterations", ",", "samples", ",", "stdDev", ")", ";", "}", "}", "}" ]
Instrumenter that increases the number of iterations until a target stability is met.
[ "Instrumenter", "that", "increases", "the", "number", "of", "iterations", "until", "a", "target", "stability", "is", "met", "." ]
[]
[ { "param": "Serializable,\n InstrumentablePerformanceExecutor<AutoProgressionPerformanceInstrumenter>,\n PerformanceExecutorInstrumenter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable,\n InstrumentablePerformanceExecutor<AutoProgressionPerformanceInstrumenter>,\n PerformanceExecutorInstrumenter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
850
83
db829da44614b1439fad46137c1e76c095376435
hfs/maproulette-python-client
maproulette/models/priority_rule.py
[ "Apache-2.0" ]
Python
PriorityRuleModel
A model for a priority rule definition in MapRoulette. :param condition: the logical condition to use to string together multiple rules. The valid options for conditions are defined by the :class:`~maproulette.models.priority_rule.Conditions` enum. :type condition: Conditions or str :param rules: one or more rules to use for the priority rule definition. Rules should be instances of the :class:`~maproulette.models.priority_rule.PriorityRule` class. :type rules: PriorityRule or list
A model for a priority rule definition in MapRoulette.
[ "A", "model", "for", "a", "priority", "rule", "definition", "in", "MapRoulette", "." ]
class PriorityRuleModel: """A model for a priority rule definition in MapRoulette. :param condition: the logical condition to use to string together multiple rules. The valid options for conditions are defined by the :class:`~maproulette.models.priority_rule.Conditions` enum. :type condition: Conditions or str :param rules: one or more rules to use for the priority rule definition. Rules should be instances of the :class:`~maproulette.models.priority_rule.PriorityRule` class. :type rules: PriorityRule or list """ @property def condition(self): """The condition to use to chain together multiple priority rules""" return self._condition @condition.setter def condition(self, value): if isinstance(value, Conditions): self._condition = value.value else: if value not in Conditions.list(): raise ValueError(f"Priority condition must be one of {Conditions.list()}.") self._condition = value @property def rules(self): """The list of priority rules to be used in the priority rule model""" return self._rules @rules.setter def rules(self, value): self._rules = value def __init__(self, condition, rules): """The constructor for the PriorityRuleModel class""" self.condition = condition self.rules = list() if isinstance(rules, list): if len(rules) > 0: for i in rules: if isinstance(i, PriorityRule): self.rules.append(i.to_dict()) else: raise ValueError("Rules must be PriorityRule instances") else: ValueError("Rule list cannot be empty") elif isinstance(rules, PriorityRule): self.rules.append(rules.to_dict()) else: raise ValueError("Rules must be PriorityRule instances") def to_dict(self): """Converts all properties of a priority rule model object into a dictionary""" return { "condition": self._condition, "rules": self._rules } def to_json(self): """Converts all properties of a priority rule model object into a JSON object""" return json.dumps(self.to_dict())
[ "class", "PriorityRuleModel", ":", "@", "property", "def", "condition", "(", "self", ")", ":", "\"\"\"The condition to use to chain together multiple priority rules\"\"\"", "return", "self", ".", "_condition", "@", "condition", ".", "setter", "def", "condition", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "Conditions", ")", ":", "self", ".", "_condition", "=", "value", ".", "value", "else", ":", "if", "value", "not", "in", "Conditions", ".", "list", "(", ")", ":", "raise", "ValueError", "(", "f\"Priority condition must be one of {Conditions.list()}.\"", ")", "self", ".", "_condition", "=", "value", "@", "property", "def", "rules", "(", "self", ")", ":", "\"\"\"The list of priority rules to be used in the priority rule model\"\"\"", "return", "self", ".", "_rules", "@", "rules", ".", "setter", "def", "rules", "(", "self", ",", "value", ")", ":", "self", ".", "_rules", "=", "value", "def", "__init__", "(", "self", ",", "condition", ",", "rules", ")", ":", "\"\"\"The constructor for the PriorityRuleModel class\"\"\"", "self", ".", "condition", "=", "condition", "self", ".", "rules", "=", "list", "(", ")", "if", "isinstance", "(", "rules", ",", "list", ")", ":", "if", "len", "(", "rules", ")", ">", "0", ":", "for", "i", "in", "rules", ":", "if", "isinstance", "(", "i", ",", "PriorityRule", ")", ":", "self", ".", "rules", ".", "append", "(", "i", ".", "to_dict", "(", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Rules must be PriorityRule instances\"", ")", "else", ":", "ValueError", "(", "\"Rule list cannot be empty\"", ")", "elif", "isinstance", "(", "rules", ",", "PriorityRule", ")", ":", "self", ".", "rules", ".", "append", "(", "rules", ".", "to_dict", "(", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Rules must be PriorityRule instances\"", ")", "def", "to_dict", "(", "self", ")", ":", "\"\"\"Converts all properties of a priority rule model object into a dictionary\"\"\"", "return", "{", "\"condition\"", ":", "self", ".", "_condition", ",", "\"rules\"", ":", "self", ".", "_rules", "}", "def", "to_json", "(", "self", ")", ":", "\"\"\"Converts all properties of a priority rule model object into a JSON object\"\"\"", "return", "json", ".", "dumps", "(", "self", ".", "to_dict", "(", ")", ")" ]
A model for a priority rule definition in MapRoulette.
[ "A", "model", "for", "a", "priority", "rule", "definition", "in", "MapRoulette", "." ]
[ "\"\"\"A model for a priority rule definition in MapRoulette.\n\n :param condition: the logical condition to use to string together multiple rules. The valid options for conditions\n are defined by the :class:`~maproulette.models.priority_rule.Conditions` enum.\n :type condition: Conditions or str\n :param rules: one or more rules to use for the priority rule definition. Rules should be instances of the\n :class:`~maproulette.models.priority_rule.PriorityRule` class.\n :type rules: PriorityRule or list\n \"\"\"", "\"\"\"The condition to use to chain together multiple priority rules\"\"\"", "\"\"\"The list of priority rules to be used in the priority rule model\"\"\"", "\"\"\"The constructor for the PriorityRuleModel class\"\"\"", "\"\"\"Converts all properties of a priority rule model object into a dictionary\"\"\"", "\"\"\"Converts all properties of a priority rule model object into a JSON object\"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "condition", "type": null, "docstring": "the logical condition to use to string together multiple rules. The valid options for conditions\nare defined by the :class:`~maproulette.models.priority_rule.Conditions` enum.", "docstring_tokens": [ "the", "logical", "condition", "to", "use", "to", "string", "together", "multiple", "rules", ".", "The", "valid", "options", "for", "conditions", "are", "defined", "by", "the", ":", "class", ":", "`", "~maproulette", ".", "models", ".", "priority_rule", ".", "Conditions", "`", "enum", "." ], "default": null, "is_optional": null }, { "identifier": "rules", "type": null, "docstring": "one or more rules to use for the priority rule definition. Rules should be instances of the\n:class:`~maproulette.models.priority_rule.PriorityRule` class.", "docstring_tokens": [ "one", "or", "more", "rules", "to", "use", "for", "the", "priority", "rule", "definition", ".", "Rules", "should", "be", "instances", "of", "the", ":", "class", ":", "`", "~maproulette", ".", "models", ".", "priority_rule", ".", "PriorityRule", "`", "class", "." ], "default": null, "is_optional": null } ], "others": [] }
false
18
461
111
dfd4f6803a31000591804a180560de7bceef266f
ackepenek/solr
solr/core/src/java/org/apache/solr/update/processor/UUIDUpdateProcessorFactory.java
[ "Apache-2.0" ]
Java
UUIDUpdateProcessorFactory
/** * An update processor that adds a newly generated <code>UUID</code> value to any document being * added that does not already have a value in the specified field. * * <p>In the example configuration below, if a document does not contain a value in the <code>id * </code> field, a new <code>UUID</code> will be generated and added as the value of that field. * <br> * * <pre class="prettyprint"> * &lt;processor class="solr.UUIDUpdateProcessorFactory"&gt; * &lt;str name="fieldName"&gt;id&lt;/str&gt; * &lt;/processor&gt; * </pre> * * <p>You can also invoke the processor with request handler param(s) as <code>uuid.fieldname</code> * with <code>processor=uuid</code> curl -X POST -H Content-Type: application/json * http://localhost:8983/solr/test/update/json/docs?processor=uuid;ampersand;uuid.fieldName=id;ampersand;commit=true * --data-binary {"id":"1","title": "titleA"} * * <p>NOTE: The param(s) provided in request handler will override / supersede processor's config. * * <p>If field name is omitted in processor configuration and not provided in request handler * param(s), then {@link org.apache.solr.schema.IndexSchema#getUniqueKeyField()} is used as field * and a new <code>UUID</code> will be generated and added as the value of that field. The field * type of the uniqueKeyField must be anything which accepts a string or UUID value. * * @see UUID * @since 4.0.0 */
An update processor that adds a newly generated UUID value to any document being added that does not already have a value in the specified field. In the example configuration below, if a document does not contain a value in the id field, a new UUID will be generated and added as the value of that field. NOTE: The param(s) provided in request handler will override / supersede processor's config. If field name is omitted in processor configuration and not provided in request handler param(s), then org.apache.solr.schema.IndexSchema#getUniqueKeyField() is used as field and a new UUID will be generated and added as the value of that field. The field type of the uniqueKeyField must be anything which accepts a string or UUID value.
[ "An", "update", "processor", "that", "adds", "a", "newly", "generated", "UUID", "value", "to", "any", "document", "being", "added", "that", "does", "not", "already", "have", "a", "value", "in", "the", "specified", "field", ".", "In", "the", "example", "configuration", "below", "if", "a", "document", "does", "not", "contain", "a", "value", "in", "the", "id", "field", "a", "new", "UUID", "will", "be", "generated", "and", "added", "as", "the", "value", "of", "that", "field", ".", "NOTE", ":", "The", "param", "(", "s", ")", "provided", "in", "request", "handler", "will", "override", "/", "supersede", "processor", "'", "s", "config", ".", "If", "field", "name", "is", "omitted", "in", "processor", "configuration", "and", "not", "provided", "in", "request", "handler", "param", "(", "s", ")", "then", "org", ".", "apache", ".", "solr", ".", "schema", ".", "IndexSchema#getUniqueKeyField", "()", "is", "used", "as", "field", "and", "a", "new", "UUID", "will", "be", "generated", "and", "added", "as", "the", "value", "of", "that", "field", ".", "The", "field", "type", "of", "the", "uniqueKeyField", "must", "be", "anything", "which", "accepts", "a", "string", "or", "UUID", "value", "." ]
public class UUIDUpdateProcessorFactory extends UpdateRequestProcessorFactory { private static final String PREFIX_PARAM = "uuid."; public static final String NAME = "uuid"; private static final String FIELD_PARAM = "fieldName"; protected String fieldName = null; public void init(NamedList<?> args) { Object obj = args.remove(FIELD_PARAM); if (null != obj) { fieldName = obj.toString(); } } public UpdateRequestProcessor getInstance( SolrQueryRequest req, SolrQueryResponse rsp, UpdateRequestProcessor next) { String fieldName = this.fieldName; String fname = req.getParams().get(PREFIX_PARAM + FIELD_PARAM); if (!StringUtils.isEmpty(fname)) { fieldName = fname; } if (StringUtils.isEmpty(fieldName)) { SchemaField schemaField = req.getSchema().getUniqueKeyField(); fieldName = schemaField.getName(); } return new AbstractDefaultValueUpdateProcessorFactory.DefaultValueUpdateProcessor( fieldName, next) { @Override public Object getDefaultValue() { return UUID.randomUUID().toString().toLowerCase(Locale.ROOT); } }; } }
[ "public", "class", "UUIDUpdateProcessorFactory", "extends", "UpdateRequestProcessorFactory", "{", "private", "static", "final", "String", "PREFIX_PARAM", "=", "\"", "uuid.", "\"", ";", "public", "static", "final", "String", "NAME", "=", "\"", "uuid", "\"", ";", "private", "static", "final", "String", "FIELD_PARAM", "=", "\"", "fieldName", "\"", ";", "protected", "String", "fieldName", "=", "null", ";", "public", "void", "init", "(", "NamedList", "<", "?", ">", "args", ")", "{", "Object", "obj", "=", "args", ".", "remove", "(", "FIELD_PARAM", ")", ";", "if", "(", "null", "!=", "obj", ")", "{", "fieldName", "=", "obj", ".", "toString", "(", ")", ";", "}", "}", "public", "UpdateRequestProcessor", "getInstance", "(", "SolrQueryRequest", "req", ",", "SolrQueryResponse", "rsp", ",", "UpdateRequestProcessor", "next", ")", "{", "String", "fieldName", "=", "this", ".", "fieldName", ";", "String", "fname", "=", "req", ".", "getParams", "(", ")", ".", "get", "(", "PREFIX_PARAM", "+", "FIELD_PARAM", ")", ";", "if", "(", "!", "StringUtils", ".", "isEmpty", "(", "fname", ")", ")", "{", "fieldName", "=", "fname", ";", "}", "if", "(", "StringUtils", ".", "isEmpty", "(", "fieldName", ")", ")", "{", "SchemaField", "schemaField", "=", "req", ".", "getSchema", "(", ")", ".", "getUniqueKeyField", "(", ")", ";", "fieldName", "=", "schemaField", ".", "getName", "(", ")", ";", "}", "return", "new", "AbstractDefaultValueUpdateProcessorFactory", ".", "DefaultValueUpdateProcessor", "(", "fieldName", ",", "next", ")", "{", "@", "Override", "public", "Object", "getDefaultValue", "(", ")", "{", "return", "UUID", ".", "randomUUID", "(", ")", ".", "toString", "(", ")", ".", "toLowerCase", "(", "Locale", ".", "ROOT", ")", ";", "}", "}", ";", "}", "}" ]
An update processor that adds a newly generated <code>UUID</code> value to any document being added that does not already have a value in the specified field.
[ "An", "update", "processor", "that", "adds", "a", "newly", "generated", "<code", ">", "UUID<", "/", "code", ">", "value", "to", "any", "document", "being", "added", "that", "does", "not", "already", "have", "a", "value", "in", "the", "specified", "field", "." ]
[]
[ { "param": "UpdateRequestProcessorFactory", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "UpdateRequestProcessorFactory", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
236
374
29b6d3b42f08fc17f20174d7de611c0c087561b5
keboola/python-component
src/keboola/component/dao.py
[ "MIT" ]
Python
TableMetadata
Abstraction of metadata and table_metadata than can be provided within the manifest file. This is useful for creation of table/column descriptions, assigning column base types etc. without knowing the complexity of the json object and the internal KBC metadata keys. Example: ```python tm = TableMetadata() # or alternatively load from existing manifest # tm = TableMetadata(manifest_dict) # add column types tm.add_column_types({"column_a":"INTEGER", "column_b":SupportedDataTypes.BOOLEAN.value}) # add table description tm.add_table_description("desc") # add column description tm.add_column_descriptions({"column_a":"Integer columns", "column_b":"my boolean test"}) # add arbitrary table metadata tm.add_table_metadata("my_arbitrary_key","some value") # update manifest manifest = {} manifest['metadata'] = tm.get_table_metadata_for_manifest() manifest['column_metadata'] = tm.get_column_metadata_for_manifest() ```
Abstraction of metadata and table_metadata than can be provided within the manifest file. This is useful for creation of table/column descriptions, assigning column base types etc. without knowing the complexity of the json object and the internal KBC metadata keys.
[ "Abstraction", "of", "metadata", "and", "table_metadata", "than", "can", "be", "provided", "within", "the", "manifest", "file", ".", "This", "is", "useful", "for", "creation", "of", "table", "/", "column", "descriptions", "assigning", "column", "base", "types", "etc", ".", "without", "knowing", "the", "complexity", "of", "the", "json", "object", "and", "the", "internal", "KBC", "metadata", "keys", "." ]
class TableMetadata: """ Abstraction of metadata and table_metadata than can be provided within the manifest file. This is useful for creation of table/column descriptions, assigning column base types etc. without knowing the complexity of the json object and the internal KBC metadata keys. Example: ```python tm = TableMetadata() # or alternatively load from existing manifest # tm = TableMetadata(manifest_dict) # add column types tm.add_column_types({"column_a":"INTEGER", "column_b":SupportedDataTypes.BOOLEAN.value}) # add table description tm.add_table_description("desc") # add column description tm.add_column_descriptions({"column_a":"Integer columns", "column_b":"my boolean test"}) # add arbitrary table metadata tm.add_table_metadata("my_arbitrary_key","some value") # update manifest manifest = {} manifest['metadata'] = tm.get_table_metadata_for_manifest() manifest['column_metadata'] = tm.get_column_metadata_for_manifest() ``` """ def __init__(self, manifest: dict = None): """ Args: manifest (dict): Existing manifest file """ self.table_metadata = dict() self.column_metadata = dict() if manifest: self.load_table_metadata_from_manifest(manifest) def load_table_metadata_from_manifest(self, manifest: dict): """ Load metadata from manifest file. Args: manifest: Returns:TableMetadata """ # column metadata for column, metadata_list in manifest.get('column_metadata', {}).items(): for metadata in metadata_list: if not metadata.get('key') and metadata.get('value'): continue key = metadata['key'] value = metadata['value'] self.add_column_metadata(column, key, value) # table metadata for metadata in manifest.get('metadata', []): if not metadata.get('key') and metadata.get('value'): continue key = metadata['key'] value = metadata['value'] self.add_table_metadata(key, value) def get_table_metadata_for_manifest(self) -> List[dict]: """ Returns table metadata list as required by the [manifest format] (https://developers.keboola.com/extend/common-interface/manifest-files/#dataintables-manifests) e.g. tm = TableMetadata() manifest['metadata'] = tm.table_metadata Returns: List[dict] """ final_metadata_list = [{'key': key, 'value': self.table_metadata[key]} for key in self.table_metadata] return final_metadata_list def get_column_metadata_for_manifest(self) -> dict: """ Returns column metadata dict as required by the [manifest format](https://developers.keboola.com/extend/common-interface/manifest-files/#dataintables -manifests) e.g. tm = TableMetadata() manifest['column_metadata'] = tm.column_metadata Returns: dict """ final_column_metadata = dict() # collect unique metadata keys for column in self.column_metadata: column_metadata_dicts = self.column_metadata[column] if not final_column_metadata.get(column): final_column_metadata[column] = list() column_metadata = [{'key': key, 'value': column_metadata_dicts[key]} for key in column_metadata_dicts] final_column_metadata[column].extend(column_metadata) return final_column_metadata @property def table_description(self) -> str: """ Returns table description (KBC.description) Returns: str """ return self.table_metadata.get(KBCMetadataKeys.description.value) @property def column_datatypes(self) -> dict: """ Return dictionary of column base datatypes e.g. {"col1name":"basetype"} Returns: dict e.g. {"col1name":"basetype"} """ return self.get_columns_metadata_by_key(KBCMetadataKeys.base_data_type.value) @property def column_descriptions(self) -> dict: """ Return dictionary of column descriptions e.g. {"col1name":"desc"} Returns: dict e.g. {"col1name":"desc"} """ return self.get_columns_metadata_by_key(KBCMetadataKeys.description.value) def get_columns_metadata_by_key(self, metadata_key) -> dict: """ Returns all columns with specified metadata_key as dictionary of column:metadata_key pairs e.g. {"col1name":"value_of_metadata_with_the_key"} Returns: dict e.g. {"col1name":"value_of_metadata_with_the_key"} """ column_types = dict() for col in self.column_metadata: if col.get(metadata_key): column_types[col] = col[metadata_key] return column_types def add_column_descriptions(self, column_descriptions: dict): """ Add column description metadata. It will be shown in the KBC Storage UI. Args: column_descriptions: dict -> {"colname":"description"} """ for col in column_descriptions: self.add_column_metadata(col, KBCMetadataKeys.description.value, column_descriptions[col]) def add_column_data_types(self, column_types: Dict[str, Union[SupportedDataTypes, str]]): """ Add column types metadata. Note that only supported datatypes (<keboola.component.dao.ColumnDataTypes>) may be provided. The value accepts either instance of ColumnDataTypes or a valid string. Args: column_types (Dict[str, Union[SupportedDataTypes, str]]): dict -> {"colname":"datatype"} Raises: ValueError when the provided data type value is not recognized """ for col in column_types: self.add_column_data_type(col, column_types[col]) def add_column_data_type(self, column: str, data_type: Union[SupportedDataTypes, str], source_data_type: str = None, nullable: bool = False, length: str = None, default=None): """ Add single column data type Args: column (str): name of the column data_type (Union[SupportedDataTypes, str]): Either instance of ColumnDataTypes enum or a valid string. Basetype supported by KBC. base type of a column as defined in [php-datatypes](https://github.com/keboola/php-datatypes#base-types); see getBaseType implementations (e.g., [mysql](https://github.com/keboola/ php-datatypes/blob/325fe4eff3e3dfae986ebbdb769eaefd18be6086/src/Definition/MySQL.php#L225)) for mapping between KBC.datatype.type and KBC.datatype.basetype source_data_type (str): Optional. Data type of a column - extracted value from the source. nullable (bool): Is column nullable? KBC input mapping converts empty values to NULL length (str): Column length when applicable e.g. 39,8; 4000 default: Default value Raises: ValueError when the provided data_type is not recognized """ if isinstance(data_type, SupportedDataTypes): base_type = data_type.value else: self._validate_data_types({column: data_type}) base_type = data_type self.add_column_metadata(column, KBCMetadataKeys.base_data_type.value, base_type) self.add_column_metadata(column, KBCMetadataKeys.data_type_nullable.value, nullable) if source_data_type is not None: self.add_column_metadata(column, KBCMetadataKeys.source_data_type.value, source_data_type) if length is not None: self.add_column_metadata(column, KBCMetadataKeys.data_type_length.value, length) if default is not None: self.add_column_metadata(column, KBCMetadataKeys.data_type_default.value, default) def add_table_description(self, description: str): """ Adds/Updates table description that is displayed in the Storage UI Args: description: str """ self.add_table_metadata(KBCMetadataKeys.description.value, description) def add_table_metadata(self, key: str, value: str): """ Add/Updates table metadata and ensures the Key is unique. Args: """ self.table_metadata = {**self.table_metadata, **{key: value}} def add_column_metadata(self, column: str, key: str, value: Union[str, bool, int]): """ Add/Updates column metadata and ensures the Key is unique. Args: """ if not self.column_metadata.get(column): self.column_metadata[column] = dict() self.column_metadata[column][key] = value def add_multiple_column_metadata(self, column_metadata: Dict[str, List[dict]]): """ Add key-value pairs to column metadata. **NOTE:** Ensures uniqueness Args: column_metadata: dict {"column_name":[{"some_key":"some_value"}]} """ for column, metadata_list in column_metadata: for metadata in metadata_list: key = metadata.items()[0] value = metadata[key] self.add_column_metadata(column, key, value) @staticmethod def _validate_data_types(column_types: dict): errors = [] for col in column_types: dtype = column_types[col] if not SupportedDataTypes.is_valid_type(dtype): errors.append(f'Datatype "{dtype}" is not valid KBC Basetype!') if errors: raise ValueError(', '.join(errors) + f'\n Supported base types are: [{SupportedDataTypes.list()}]')
[ "class", "TableMetadata", ":", "def", "__init__", "(", "self", ",", "manifest", ":", "dict", "=", "None", ")", ":", "\"\"\"\n\n Args:\n manifest (dict): Existing manifest file\n \"\"\"", "self", ".", "table_metadata", "=", "dict", "(", ")", "self", ".", "column_metadata", "=", "dict", "(", ")", "if", "manifest", ":", "self", ".", "load_table_metadata_from_manifest", "(", "manifest", ")", "def", "load_table_metadata_from_manifest", "(", "self", ",", "manifest", ":", "dict", ")", ":", "\"\"\"\n Load metadata from manifest file.\n\n Args:\n manifest:\n\n Returns:TableMetadata\n\n \"\"\"", "for", "column", ",", "metadata_list", "in", "manifest", ".", "get", "(", "'column_metadata'", ",", "{", "}", ")", ".", "items", "(", ")", ":", "for", "metadata", "in", "metadata_list", ":", "if", "not", "metadata", ".", "get", "(", "'key'", ")", "and", "metadata", ".", "get", "(", "'value'", ")", ":", "continue", "key", "=", "metadata", "[", "'key'", "]", "value", "=", "metadata", "[", "'value'", "]", "self", ".", "add_column_metadata", "(", "column", ",", "key", ",", "value", ")", "for", "metadata", "in", "manifest", ".", "get", "(", "'metadata'", ",", "[", "]", ")", ":", "if", "not", "metadata", ".", "get", "(", "'key'", ")", "and", "metadata", ".", "get", "(", "'value'", ")", ":", "continue", "key", "=", "metadata", "[", "'key'", "]", "value", "=", "metadata", "[", "'value'", "]", "self", ".", "add_table_metadata", "(", "key", ",", "value", ")", "def", "get_table_metadata_for_manifest", "(", "self", ")", "->", "List", "[", "dict", "]", ":", "\"\"\"\n Returns table metadata list as required by the\n [manifest format]\n (https://developers.keboola.com/extend/common-interface/manifest-files/#dataintables-manifests)\n\n e.g.\n tm = TableMetadata()\n manifest['metadata'] = tm.table_metadata\n\n Returns: List[dict]\n\n \"\"\"", "final_metadata_list", "=", "[", "{", "'key'", ":", "key", ",", "'value'", ":", "self", ".", "table_metadata", "[", "key", "]", "}", "for", "key", "in", "self", ".", "table_metadata", "]", "return", "final_metadata_list", "def", "get_column_metadata_for_manifest", "(", "self", ")", "->", "dict", ":", "\"\"\"\n Returns column metadata dict as required by the\n [manifest format](https://developers.keboola.com/extend/common-interface/manifest-files/#dataintables\n -manifests)\n\n e.g.\n tm = TableMetadata()\n manifest['column_metadata'] = tm.column_metadata\n\n Returns: dict\n\n \"\"\"", "final_column_metadata", "=", "dict", "(", ")", "for", "column", "in", "self", ".", "column_metadata", ":", "column_metadata_dicts", "=", "self", ".", "column_metadata", "[", "column", "]", "if", "not", "final_column_metadata", ".", "get", "(", "column", ")", ":", "final_column_metadata", "[", "column", "]", "=", "list", "(", ")", "column_metadata", "=", "[", "{", "'key'", ":", "key", ",", "'value'", ":", "column_metadata_dicts", "[", "key", "]", "}", "for", "key", "in", "column_metadata_dicts", "]", "final_column_metadata", "[", "column", "]", ".", "extend", "(", "column_metadata", ")", "return", "final_column_metadata", "@", "property", "def", "table_description", "(", "self", ")", "->", "str", ":", "\"\"\"\n Returns table description (KBC.description)\n\n Returns: str\n\n \"\"\"", "return", "self", ".", "table_metadata", ".", "get", "(", "KBCMetadataKeys", ".", "description", ".", "value", ")", "@", "property", "def", "column_datatypes", "(", "self", ")", "->", "dict", ":", "\"\"\"\n Return dictionary of column base datatypes\n e.g. {\"col1name\":\"basetype\"}\n\n Returns: dict e.g. {\"col1name\":\"basetype\"}\n\n \"\"\"", "return", "self", ".", "get_columns_metadata_by_key", "(", "KBCMetadataKeys", ".", "base_data_type", ".", "value", ")", "@", "property", "def", "column_descriptions", "(", "self", ")", "->", "dict", ":", "\"\"\"\n Return dictionary of column descriptions\n e.g. {\"col1name\":\"desc\"}\n\n Returns: dict e.g. {\"col1name\":\"desc\"}\n\n \"\"\"", "return", "self", ".", "get_columns_metadata_by_key", "(", "KBCMetadataKeys", ".", "description", ".", "value", ")", "def", "get_columns_metadata_by_key", "(", "self", ",", "metadata_key", ")", "->", "dict", ":", "\"\"\"\n Returns all columns with specified metadata_key as dictionary of column:metadata_key pairs\n e.g. {\"col1name\":\"value_of_metadata_with_the_key\"}\n\n Returns: dict e.g. {\"col1name\":\"value_of_metadata_with_the_key\"}\n\n \"\"\"", "column_types", "=", "dict", "(", ")", "for", "col", "in", "self", ".", "column_metadata", ":", "if", "col", ".", "get", "(", "metadata_key", ")", ":", "column_types", "[", "col", "]", "=", "col", "[", "metadata_key", "]", "return", "column_types", "def", "add_column_descriptions", "(", "self", ",", "column_descriptions", ":", "dict", ")", ":", "\"\"\"\n Add column description metadata. It will be shown in the KBC Storage UI.\n\n Args:\n column_descriptions: dict -> {\"colname\":\"description\"}\n\n \"\"\"", "for", "col", "in", "column_descriptions", ":", "self", ".", "add_column_metadata", "(", "col", ",", "KBCMetadataKeys", ".", "description", ".", "value", ",", "column_descriptions", "[", "col", "]", ")", "def", "add_column_data_types", "(", "self", ",", "column_types", ":", "Dict", "[", "str", ",", "Union", "[", "SupportedDataTypes", ",", "str", "]", "]", ")", ":", "\"\"\"\n Add column types metadata. Note that only supported datatypes\n (<keboola.component.dao.ColumnDataTypes>) may be provided. The value accepts either instance of ColumnDataTypes\n or a valid string.\n\n Args:\n column_types (Dict[str, Union[SupportedDataTypes, str]]): dict -> {\"colname\":\"datatype\"}\n\n Raises:\n ValueError when the provided data type value is not recognized\n \"\"\"", "for", "col", "in", "column_types", ":", "self", ".", "add_column_data_type", "(", "col", ",", "column_types", "[", "col", "]", ")", "def", "add_column_data_type", "(", "self", ",", "column", ":", "str", ",", "data_type", ":", "Union", "[", "SupportedDataTypes", ",", "str", "]", ",", "source_data_type", ":", "str", "=", "None", ",", "nullable", ":", "bool", "=", "False", ",", "length", ":", "str", "=", "None", ",", "default", "=", "None", ")", ":", "\"\"\"\n Add single column data type\n Args:\n column (str): name of the column\n data_type (Union[SupportedDataTypes, str]):\n Either instance of ColumnDataTypes enum or a valid string. Basetype supported by KBC.\n base type of a column as defined in\n [php-datatypes](https://github.com/keboola/php-datatypes#base-types);\n see getBaseType implementations (e.g., [mysql](https://github.com/keboola/\n php-datatypes/blob/325fe4eff3e3dfae986ebbdb769eaefd18be6086/src/Definition/MySQL.php#L225))\n for mapping between KBC.datatype.type and KBC.datatype.basetype\n source_data_type (str):\n Optional. Data type of a column - extracted value from the source.\n nullable (bool): Is column nullable? KBC input mapping converts empty values to NULL\n length (str): Column length when applicable e.g. 39,8; 4000\n default: Default value\n\n Raises:\n ValueError when the provided data_type is not recognized\n\n \"\"\"", "if", "isinstance", "(", "data_type", ",", "SupportedDataTypes", ")", ":", "base_type", "=", "data_type", ".", "value", "else", ":", "self", ".", "_validate_data_types", "(", "{", "column", ":", "data_type", "}", ")", "base_type", "=", "data_type", "self", ".", "add_column_metadata", "(", "column", ",", "KBCMetadataKeys", ".", "base_data_type", ".", "value", ",", "base_type", ")", "self", ".", "add_column_metadata", "(", "column", ",", "KBCMetadataKeys", ".", "data_type_nullable", ".", "value", ",", "nullable", ")", "if", "source_data_type", "is", "not", "None", ":", "self", ".", "add_column_metadata", "(", "column", ",", "KBCMetadataKeys", ".", "source_data_type", ".", "value", ",", "source_data_type", ")", "if", "length", "is", "not", "None", ":", "self", ".", "add_column_metadata", "(", "column", ",", "KBCMetadataKeys", ".", "data_type_length", ".", "value", ",", "length", ")", "if", "default", "is", "not", "None", ":", "self", ".", "add_column_metadata", "(", "column", ",", "KBCMetadataKeys", ".", "data_type_default", ".", "value", ",", "default", ")", "def", "add_table_description", "(", "self", ",", "description", ":", "str", ")", ":", "\"\"\"\n Adds/Updates table description that is displayed in the Storage UI\n Args:\n description: str\n \"\"\"", "self", ".", "add_table_metadata", "(", "KBCMetadataKeys", ".", "description", ".", "value", ",", "description", ")", "def", "add_table_metadata", "(", "self", ",", "key", ":", "str", ",", "value", ":", "str", ")", ":", "\"\"\"\n Add/Updates table metadata and ensures the Key is unique.\n Args:\n\n \"\"\"", "self", ".", "table_metadata", "=", "{", "**", "self", ".", "table_metadata", ",", "**", "{", "key", ":", "value", "}", "}", "def", "add_column_metadata", "(", "self", ",", "column", ":", "str", ",", "key", ":", "str", ",", "value", ":", "Union", "[", "str", ",", "bool", ",", "int", "]", ")", ":", "\"\"\"\n Add/Updates column metadata and ensures the Key is unique.\n Args:\n\n \"\"\"", "if", "not", "self", ".", "column_metadata", ".", "get", "(", "column", ")", ":", "self", ".", "column_metadata", "[", "column", "]", "=", "dict", "(", ")", "self", ".", "column_metadata", "[", "column", "]", "[", "key", "]", "=", "value", "def", "add_multiple_column_metadata", "(", "self", ",", "column_metadata", ":", "Dict", "[", "str", ",", "List", "[", "dict", "]", "]", ")", ":", "\"\"\"\n Add key-value pairs to column metadata.\n\n **NOTE:** Ensures uniqueness\n Args:\n column_metadata: dict {\"column_name\":[{\"some_key\":\"some_value\"}]}\n \"\"\"", "for", "column", ",", "metadata_list", "in", "column_metadata", ":", "for", "metadata", "in", "metadata_list", ":", "key", "=", "metadata", ".", "items", "(", ")", "[", "0", "]", "value", "=", "metadata", "[", "key", "]", "self", ".", "add_column_metadata", "(", "column", ",", "key", ",", "value", ")", "@", "staticmethod", "def", "_validate_data_types", "(", "column_types", ":", "dict", ")", ":", "errors", "=", "[", "]", "for", "col", "in", "column_types", ":", "dtype", "=", "column_types", "[", "col", "]", "if", "not", "SupportedDataTypes", ".", "is_valid_type", "(", "dtype", ")", ":", "errors", ".", "append", "(", "f'Datatype \"{dtype}\" is not valid KBC Basetype!'", ")", "if", "errors", ":", "raise", "ValueError", "(", "', '", ".", "join", "(", "errors", ")", "+", "f'\\n Supported base types are: [{SupportedDataTypes.list()}]'", ")" ]
Abstraction of metadata and table_metadata than can be provided within the manifest file.
[ "Abstraction", "of", "metadata", "and", "table_metadata", "than", "can", "be", "provided", "within", "the", "manifest", "file", "." ]
[ "\"\"\"\n Abstraction of metadata and table_metadata than can be provided within the manifest file. This is useful for\n creation\n of table/column descriptions, assigning column base types etc. without knowing the complexity\n of the json object and the internal KBC metadata keys.\n\n Example:\n\n ```python\n\n tm = TableMetadata()\n\n # or alternatively load from existing manifest\n # tm = TableMetadata(manifest_dict)\n\n # add column types\n tm.add_column_types({\"column_a\":\"INTEGER\", \"column_b\":SupportedDataTypes.BOOLEAN.value})\n\n # add table description\n tm.add_table_description(\"desc\")\n\n # add column description\n tm.add_column_descriptions({\"column_a\":\"Integer columns\", \"column_b\":\"my boolean test\"})\n\n # add arbitrary table metadata\n tm.add_table_metadata(\"my_arbitrary_key\",\"some value\")\n\n # update manifest\n manifest = {}\n manifest['metadata'] = tm.get_table_metadata_for_manifest()\n manifest['column_metadata'] = tm.get_column_metadata_for_manifest()\n ```\n\n\n \"\"\"", "\"\"\"\n\n Args:\n manifest (dict): Existing manifest file\n \"\"\"", "\"\"\"\n Load metadata from manifest file.\n\n Args:\n manifest:\n\n Returns:TableMetadata\n\n \"\"\"", "# column metadata", "# table metadata", "\"\"\"\n Returns table metadata list as required by the\n [manifest format]\n (https://developers.keboola.com/extend/common-interface/manifest-files/#dataintables-manifests)\n\n e.g.\n tm = TableMetadata()\n manifest['metadata'] = tm.table_metadata\n\n Returns: List[dict]\n\n \"\"\"", "\"\"\"\n Returns column metadata dict as required by the\n [manifest format](https://developers.keboola.com/extend/common-interface/manifest-files/#dataintables\n -manifests)\n\n e.g.\n tm = TableMetadata()\n manifest['column_metadata'] = tm.column_metadata\n\n Returns: dict\n\n \"\"\"", "# collect unique metadata keys", "\"\"\"\n Returns table description (KBC.description)\n\n Returns: str\n\n \"\"\"", "\"\"\"\n Return dictionary of column base datatypes\n e.g. {\"col1name\":\"basetype\"}\n\n Returns: dict e.g. {\"col1name\":\"basetype\"}\n\n \"\"\"", "\"\"\"\n Return dictionary of column descriptions\n e.g. {\"col1name\":\"desc\"}\n\n Returns: dict e.g. {\"col1name\":\"desc\"}\n\n \"\"\"", "\"\"\"\n Returns all columns with specified metadata_key as dictionary of column:metadata_key pairs\n e.g. {\"col1name\":\"value_of_metadata_with_the_key\"}\n\n Returns: dict e.g. {\"col1name\":\"value_of_metadata_with_the_key\"}\n\n \"\"\"", "\"\"\"\n Add column description metadata. It will be shown in the KBC Storage UI.\n\n Args:\n column_descriptions: dict -> {\"colname\":\"description\"}\n\n \"\"\"", "\"\"\"\n Add column types metadata. Note that only supported datatypes\n (<keboola.component.dao.ColumnDataTypes>) may be provided. The value accepts either instance of ColumnDataTypes\n or a valid string.\n\n Args:\n column_types (Dict[str, Union[SupportedDataTypes, str]]): dict -> {\"colname\":\"datatype\"}\n\n Raises:\n ValueError when the provided data type value is not recognized\n \"\"\"", "\"\"\"\n Add single column data type\n Args:\n column (str): name of the column\n data_type (Union[SupportedDataTypes, str]):\n Either instance of ColumnDataTypes enum or a valid string. Basetype supported by KBC.\n base type of a column as defined in\n [php-datatypes](https://github.com/keboola/php-datatypes#base-types);\n see getBaseType implementations (e.g., [mysql](https://github.com/keboola/\n php-datatypes/blob/325fe4eff3e3dfae986ebbdb769eaefd18be6086/src/Definition/MySQL.php#L225))\n for mapping between KBC.datatype.type and KBC.datatype.basetype\n source_data_type (str):\n Optional. Data type of a column - extracted value from the source.\n nullable (bool): Is column nullable? KBC input mapping converts empty values to NULL\n length (str): Column length when applicable e.g. 39,8; 4000\n default: Default value\n\n Raises:\n ValueError when the provided data_type is not recognized\n\n \"\"\"", "\"\"\"\n Adds/Updates table description that is displayed in the Storage UI\n Args:\n description: str\n \"\"\"", "\"\"\"\n Add/Updates table metadata and ensures the Key is unique.\n Args:\n\n \"\"\"", "\"\"\"\n Add/Updates column metadata and ensures the Key is unique.\n Args:\n\n \"\"\"", "\"\"\"\n Add key-value pairs to column metadata.\n\n **NOTE:** Ensures uniqueness\n Args:\n column_metadata: dict {\"column_name\":[{\"some_key\":\"some_value\"}]}\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "examples", "docstring": "```python\n\ntm = TableMetadata()\n\nor alternatively load from existing manifest\ntm = TableMetadata(manifest_dict)\n\nadd column types\ntm.add_column_types({\"column_a\":\"INTEGER\", \"column_b\":SupportedDataTypes.BOOLEAN.value})\n\nadd table description\ntm.add_table_description(\"desc\")\n\nadd column description\ntm.add_column_descriptions({\"column_a\":\"Integer columns\", \"column_b\":\"my boolean test\"})\n\nadd arbitrary table metadata\ntm.add_table_metadata(\"my_arbitrary_key\",\"some value\")\n\n", "docstring_tokens": [ "`", "`", "`", "python", "tm", "=", "TableMetadata", "()", "or", "alternatively", "load", "from", "existing", "manifest", "tm", "=", "TableMetadata", "(", "manifest_dict", ")", "add", "column", "types", "tm", ".", "add_column_types", "(", "{", "\"", "column_a", "\"", ":", "\"", "INTEGER", "\"", "\"", "column_b", "\"", ":", "SupportedDataTypes", ".", "BOOLEAN", ".", "value", "}", ")", "add", "table", "description", "tm", ".", "add_table_description", "(", "\"", "desc", "\"", ")", "add", "column", "description", "tm", ".", "add_column_descriptions", "(", "{", "\"", "column_a", "\"", ":", "\"", "Integer", "columns", "\"", "\"", "column_b", "\"", ":", "\"", "my", "boolean", "test", "\"", "}", ")", "add", "arbitrary", "table", "metadata", "tm", ".", "add_table_metadata", "(", "\"", "my_arbitrary_key", "\"", "\"", "some", "value", "\"", ")" ] } ] }
false
16
2,067
219
70d0e5b5c86c14dbbcf3615c3c73e83fab271ddf
Trievo/sia
src/main/java/com/trievosoftware/application/service/dto/DiscordUserCriteria.java
[ "Apache-2.0" ]
Java
DiscordUserCriteria
/** * Criteria class for the DiscordUser entity. This class is used in DiscordUserResource to * receive all the possible filtering options from the Http GET request parameters. * For example the following could be a valid requests: * <code> /discord-users?id.greaterThan=5&amp;attr1.contains=something&amp;attr2.specified=false</code> * As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use * fix type specific filters. */
Criteria class for the DiscordUser entity. This class is used in DiscordUserResource to receive all the possible filtering options from the Http GET request parameters. For example the following could be a valid requests: /discord-users?id.greaterThan=5&attr1.contains=something&attr2.specified=false As Spring is unable to properly convert the types, unless specific Filter class are used, we need to use fix type specific filters.
[ "Criteria", "class", "for", "the", "DiscordUser", "entity", ".", "This", "class", "is", "used", "in", "DiscordUserResource", "to", "receive", "all", "the", "possible", "filtering", "options", "from", "the", "Http", "GET", "request", "parameters", ".", "For", "example", "the", "following", "could", "be", "a", "valid", "requests", ":", "/", "discord", "-", "users?id", ".", "greaterThan", "=", "5&attr1", ".", "contains", "=", "something&attr2", ".", "specified", "=", "false", "As", "Spring", "is", "unable", "to", "properly", "convert", "the", "types", "unless", "specific", "Filter", "class", "are", "used", "we", "need", "to", "use", "fix", "type", "specific", "filters", "." ]
public class DiscordUserCriteria implements Serializable { private static final long serialVersionUID = 1L; private LongFilter id; private LongFilter userId; private IntegerFilter commandsIssued; private BooleanFilter blacklisted; public LongFilter getId() { return id; } public void setId(LongFilter id) { this.id = id; } public LongFilter getUserId() { return userId; } public void setUserId(LongFilter userId) { this.userId = userId; } public IntegerFilter getCommandsIssued() { return commandsIssued; } public void setCommandsIssued(IntegerFilter commandsIssued) { this.commandsIssued = commandsIssued; } public BooleanFilter getBlacklisted() { return blacklisted; } public void setBlacklisted(BooleanFilter blacklisted) { this.blacklisted = blacklisted; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final DiscordUserCriteria that = (DiscordUserCriteria) o; return Objects.equals(id, that.id) && Objects.equals(userId, that.userId) && Objects.equals(commandsIssued, that.commandsIssued) && Objects.equals(blacklisted, that.blacklisted); } @Override public int hashCode() { return Objects.hash( id, userId, commandsIssued, blacklisted ); } @Override public String toString() { return "DiscordUserCriteria{" + (id != null ? "id=" + id + ", " : "") + (userId != null ? "userId=" + userId + ", " : "") + (commandsIssued != null ? "commandsIssued=" + commandsIssued + ", " : "") + (blacklisted != null ? "blacklisted=" + blacklisted + ", " : "") + "}"; } }
[ "public", "class", "DiscordUserCriteria", "implements", "Serializable", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "private", "LongFilter", "id", ";", "private", "LongFilter", "userId", ";", "private", "IntegerFilter", "commandsIssued", ";", "private", "BooleanFilter", "blacklisted", ";", "public", "LongFilter", "getId", "(", ")", "{", "return", "id", ";", "}", "public", "void", "setId", "(", "LongFilter", "id", ")", "{", "this", ".", "id", "=", "id", ";", "}", "public", "LongFilter", "getUserId", "(", ")", "{", "return", "userId", ";", "}", "public", "void", "setUserId", "(", "LongFilter", "userId", ")", "{", "this", ".", "userId", "=", "userId", ";", "}", "public", "IntegerFilter", "getCommandsIssued", "(", ")", "{", "return", "commandsIssued", ";", "}", "public", "void", "setCommandsIssued", "(", "IntegerFilter", "commandsIssued", ")", "{", "this", ".", "commandsIssued", "=", "commandsIssued", ";", "}", "public", "BooleanFilter", "getBlacklisted", "(", ")", "{", "return", "blacklisted", ";", "}", "public", "void", "setBlacklisted", "(", "BooleanFilter", "blacklisted", ")", "{", "this", ".", "blacklisted", "=", "blacklisted", ";", "}", "@", "Override", "public", "boolean", "equals", "(", "Object", "o", ")", "{", "if", "(", "this", "==", "o", ")", "{", "return", "true", ";", "}", "if", "(", "o", "==", "null", "||", "getClass", "(", ")", "!=", "o", ".", "getClass", "(", ")", ")", "{", "return", "false", ";", "}", "final", "DiscordUserCriteria", "that", "=", "(", "DiscordUserCriteria", ")", "o", ";", "return", "Objects", ".", "equals", "(", "id", ",", "that", ".", "id", ")", "&&", "Objects", ".", "equals", "(", "userId", ",", "that", ".", "userId", ")", "&&", "Objects", ".", "equals", "(", "commandsIssued", ",", "that", ".", "commandsIssued", ")", "&&", "Objects", ".", "equals", "(", "blacklisted", ",", "that", ".", "blacklisted", ")", ";", "}", "@", "Override", "public", "int", "hashCode", "(", ")", "{", "return", "Objects", ".", "hash", "(", "id", ",", "userId", ",", "commandsIssued", ",", "blacklisted", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"", "DiscordUserCriteria{", "\"", "+", "(", "id", "!=", "null", "?", "\"", "id=", "\"", "+", "id", "+", "\"", ", ", "\"", ":", "\"", "\"", ")", "+", "(", "userId", "!=", "null", "?", "\"", "userId=", "\"", "+", "userId", "+", "\"", ", ", "\"", ":", "\"", "\"", ")", "+", "(", "commandsIssued", "!=", "null", "?", "\"", "commandsIssued=", "\"", "+", "commandsIssued", "+", "\"", ", ", "\"", ":", "\"", "\"", ")", "+", "(", "blacklisted", "!=", "null", "?", "\"", "blacklisted=", "\"", "+", "blacklisted", "+", "\"", ", ", "\"", ":", "\"", "\"", ")", "+", "\"", "}", "\"", ";", "}", "}" ]
Criteria class for the DiscordUser entity.
[ "Criteria", "class", "for", "the", "DiscordUser", "entity", "." ]
[]
[ { "param": "Serializable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Serializable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
16
432
108
7433771805d8bffd00fbde078b5f2ccbeff6bd3e
icraftsoftware/BizTalk.Factory
src/BizTalk.Dsl/Dsl/Binding/Adapter/SftpAdapter.Inbound.cs
[ "Apache-2.0" ]
C#
Inbound
/// <summary> /// Use the SFTP adapter to send and receive messages from a secure FTP server using the SSH file transfer /// protocol. /// </summary> /// <seealso href="https://msdn.microsoft.com/en-us/library/dn281088.aspx">SFTP Adapter Frequently Asked Questions</seealso> /// <seealso href="https://msdn.microsoft.com/en-us/library/jj684548.aspx">How to Configure an SFTP Receive Location</seealso>
Use the SFTP adapter to send and receive messages from a secure FTP server using the SSH file transfer protocol.
[ "Use", "the", "SFTP", "adapter", "to", "send", "and", "receive", "messages", "from", "a", "secure", "FTP", "server", "using", "the", "SSH", "file", "transfer", "protocol", "." ]
public class Inbound : SftpAdapter<SftpRLConfig>, IInboundAdapter { public Inbound() { PollingInterval = TimeSpan.Zero; ProxyPort = 1080; ProxyType = ProxyType.None; AccessAnySshServerHostKey = false; ClientAuthenticationMode = ClientAuthenticationMode.Password; EncryptionCipher = EncryptionCipher.Auto; Port = 22; } public Inbound(Action<Inbound> adapterConfigurator) : this() { adapterConfigurator(this); } #region Base Class Member Overrides protected override string GetAddress() { return "sftp://" + ServerAddress + ":" + Port + "/" + FolderPath + "/" + FileMask; } #endregion #region Other Settings public int ConnectionLimit { get { return _adapterConfig.ConnectionLimit; } set { _adapterConfig.ConnectionLimit = value; } } #endregion #region Polling Settings public TimeSpan PollingInterval { get { return BuildTimeSpan(_adapterConfig.PollingInterval, _adapterConfig.PollingIntervalUnit); } set { UnbuildTimeSpan( value, (i, u) => { _adapterConfig.PollingInterval = i; _adapterConfig.PollingIntervalUnit = u; }); } } #endregion #region Proxy Settings public string ProxyAddress { get { return _adapterConfig.ProxyAddress; } set { _adapterConfig.ProxyAddress = value; } } public int ProxyPort { get { return _adapterConfig.ProxyPort; } set { _adapterConfig.ProxyPort = value; } } public string ProxyUserName { get { return _adapterConfig.ProxyUserName; } set { _adapterConfig.ProxyUserName = value; } } public string ProxyPassword { get { return _adapterConfig.ProxyPassword; } set { _adapterConfig.ProxyPassword = value; } } public ProxyType ProxyType { get { return _adapterConfig.ProxyType; } set { _adapterConfig.ProxyType = value; } } #endregion #region Security Settings public bool AccessAnySshServerHostKey { get { return _adapterConfig.AccessAnySSHServerHostKey; } set { _adapterConfig.AccessAnySSHServerHostKey = value; } } public string SshServerHostKeyFingerPrint { get { return _adapterConfig.SSHServerHostKey; } set { _adapterConfig.SSHServerHostKey = value; } } public ClientAuthenticationMode ClientAuthenticationMode { get { return _adapterConfig.ClientAuthenticationMode; } set { _adapterConfig.ClientAuthenticationMode = value; } } public EncryptionCipher EncryptionCipher { get { return _adapterConfig.EncryptionCipher; } set { _adapterConfig.EncryptionCipher = value; } } public string PrivateKeyFile { get { return _adapterConfig.PrivateKeyFile; } set { _adapterConfig.PrivateKeyFile = value; } } public string PrivateKeyPassword { get { return _adapterConfig.PrivateKeyPassword; } set { _adapterConfig.PrivateKeyPassword = value; } } public string UserName { get { return _adapterConfig.UserName; } set { _adapterConfig.UserName = value; } } public string Password { get { return _adapterConfig.Password; } set { _adapterConfig.Password = value; } } #endregion #region SSH Server Settings public string ServerAddress { get { return _adapterConfig.ServerAddress; } set { _adapterConfig.ServerAddress = value; } } public int Port { get { return _adapterConfig.Port; } set { _adapterConfig.Port = value; } } public string FolderPath { get { return _adapterConfig.FolderPath; } set { _adapterConfig.FolderPath = value; } } public string FileMask { get { return _adapterConfig.FileMask; } set { _adapterConfig.FileMask = value; } } #endregion }
[ "public", "class", "Inbound", ":", "SftpAdapter", "<", "SftpRLConfig", ">", ",", "IInboundAdapter", "{", "public", "Inbound", "(", ")", "{", "PollingInterval", "=", "TimeSpan", ".", "Zero", ";", "ProxyPort", "=", "1080", ";", "ProxyType", "=", "ProxyType", ".", "None", ";", "AccessAnySshServerHostKey", "=", "false", ";", "ClientAuthenticationMode", "=", "ClientAuthenticationMode", ".", "Password", ";", "EncryptionCipher", "=", "EncryptionCipher", ".", "Auto", ";", "Port", "=", "22", ";", "}", "public", "Inbound", "(", "Action", "<", "Inbound", ">", "adapterConfigurator", ")", ":", "this", "(", ")", "{", "adapterConfigurator", "(", "this", ")", ";", "}", "region", " Base Class Member Overrides", "protected", "override", "string", "GetAddress", "(", ")", "{", "return", "\"", "sftp://", "\"", "+", "ServerAddress", "+", "\"", ":", "\"", "+", "Port", "+", "\"", "/", "\"", "+", "FolderPath", "+", "\"", "/", "\"", "+", "FileMask", ";", "}", "endregion", "region", " Other Settings", "public", "int", "ConnectionLimit", "{", "get", "{", "return", "_adapterConfig", ".", "ConnectionLimit", ";", "}", "set", "{", "_adapterConfig", ".", "ConnectionLimit", "=", "value", ";", "}", "}", "endregion", "region", " Polling Settings", "public", "TimeSpan", "PollingInterval", "{", "get", "{", "return", "BuildTimeSpan", "(", "_adapterConfig", ".", "PollingInterval", ",", "_adapterConfig", ".", "PollingIntervalUnit", ")", ";", "}", "set", "{", "UnbuildTimeSpan", "(", "value", ",", "(", "i", ",", "u", ")", "=>", "{", "_adapterConfig", ".", "PollingInterval", "=", "i", ";", "_adapterConfig", ".", "PollingIntervalUnit", "=", "u", ";", "}", ")", ";", "}", "}", "endregion", "region", " Proxy Settings", "public", "string", "ProxyAddress", "{", "get", "{", "return", "_adapterConfig", ".", "ProxyAddress", ";", "}", "set", "{", "_adapterConfig", ".", "ProxyAddress", "=", "value", ";", "}", "}", "public", "int", "ProxyPort", "{", "get", "{", "return", "_adapterConfig", ".", "ProxyPort", ";", "}", "set", "{", "_adapterConfig", ".", "ProxyPort", "=", "value", ";", "}", "}", "public", "string", "ProxyUserName", "{", "get", "{", "return", "_adapterConfig", ".", "ProxyUserName", ";", "}", "set", "{", "_adapterConfig", ".", "ProxyUserName", "=", "value", ";", "}", "}", "public", "string", "ProxyPassword", "{", "get", "{", "return", "_adapterConfig", ".", "ProxyPassword", ";", "}", "set", "{", "_adapterConfig", ".", "ProxyPassword", "=", "value", ";", "}", "}", "public", "ProxyType", "ProxyType", "{", "get", "{", "return", "_adapterConfig", ".", "ProxyType", ";", "}", "set", "{", "_adapterConfig", ".", "ProxyType", "=", "value", ";", "}", "}", "endregion", "region", " Security Settings", "public", "bool", "AccessAnySshServerHostKey", "{", "get", "{", "return", "_adapterConfig", ".", "AccessAnySSHServerHostKey", ";", "}", "set", "{", "_adapterConfig", ".", "AccessAnySSHServerHostKey", "=", "value", ";", "}", "}", "public", "string", "SshServerHostKeyFingerPrint", "{", "get", "{", "return", "_adapterConfig", ".", "SSHServerHostKey", ";", "}", "set", "{", "_adapterConfig", ".", "SSHServerHostKey", "=", "value", ";", "}", "}", "public", "ClientAuthenticationMode", "ClientAuthenticationMode", "{", "get", "{", "return", "_adapterConfig", ".", "ClientAuthenticationMode", ";", "}", "set", "{", "_adapterConfig", ".", "ClientAuthenticationMode", "=", "value", ";", "}", "}", "public", "EncryptionCipher", "EncryptionCipher", "{", "get", "{", "return", "_adapterConfig", ".", "EncryptionCipher", ";", "}", "set", "{", "_adapterConfig", ".", "EncryptionCipher", "=", "value", ";", "}", "}", "public", "string", "PrivateKeyFile", "{", "get", "{", "return", "_adapterConfig", ".", "PrivateKeyFile", ";", "}", "set", "{", "_adapterConfig", ".", "PrivateKeyFile", "=", "value", ";", "}", "}", "public", "string", "PrivateKeyPassword", "{", "get", "{", "return", "_adapterConfig", ".", "PrivateKeyPassword", ";", "}", "set", "{", "_adapterConfig", ".", "PrivateKeyPassword", "=", "value", ";", "}", "}", "public", "string", "UserName", "{", "get", "{", "return", "_adapterConfig", ".", "UserName", ";", "}", "set", "{", "_adapterConfig", ".", "UserName", "=", "value", ";", "}", "}", "public", "string", "Password", "{", "get", "{", "return", "_adapterConfig", ".", "Password", ";", "}", "set", "{", "_adapterConfig", ".", "Password", "=", "value", ";", "}", "}", "endregion", "region", " SSH Server Settings", "public", "string", "ServerAddress", "{", "get", "{", "return", "_adapterConfig", ".", "ServerAddress", ";", "}", "set", "{", "_adapterConfig", ".", "ServerAddress", "=", "value", ";", "}", "}", "public", "int", "Port", "{", "get", "{", "return", "_adapterConfig", ".", "Port", ";", "}", "set", "{", "_adapterConfig", ".", "Port", "=", "value", ";", "}", "}", "public", "string", "FolderPath", "{", "get", "{", "return", "_adapterConfig", ".", "FolderPath", ";", "}", "set", "{", "_adapterConfig", ".", "FolderPath", "=", "value", ";", "}", "}", "public", "string", "FileMask", "{", "get", "{", "return", "_adapterConfig", ".", "FileMask", ";", "}", "set", "{", "_adapterConfig", ".", "FileMask", "=", "value", ";", "}", "}", "endregion", "}" ]
Use the SFTP adapter to send and receive messages from a secure FTP server using the SSH file transfer protocol.
[ "Use", "the", "SFTP", "adapter", "to", "send", "and", "receive", "messages", "from", "a", "secure", "FTP", "server", "using", "the", "SSH", "file", "transfer", "protocol", "." ]
[ "// Polling Settings", "// Proxy Settings", "// Security Settings", "// SSH Server Settings", "/// <summary>", "/// Specify the maximum number of concurrent connections that can be opened to the server.", "/// </summary>", "/// <remarks>", "/// This setting is per server and per receive location. Consider the following scenarios:", "/// <list type=\"bullet\">", "/// <item>", "/// There are two receive locations that have the same configuration property values, including the", "/// ConnectionLimit property set to the same value. For example, the property is set to 6. In this situation,", "/// there is one connection pool (with 6 available connections) that is used by both receive locations.", "/// </item>", "/// <item>", "/// There are two receive locations configured with same configuration values, and have the ConnectionLimit", "/// property set to different values. For example, ReceiveLocation1 property is set to 6 and ReceiveLocation2", "/// property is set to 5. In this situation, each receive location has its own connection pool with its own", "/// available connections. ReceiveLocation1 connection pool has 6 available connections. ReceiveLocation2", "/// connection pool has 5 available connections.", "/// </item>", "/// </list>", "/// </remarks>", "/// <summary>", "/// Specify the intervals at which the adapter will poll the server.", "/// </summary>", "/// <remarks>", "/// <remarks>", "/// To poll continuously, set this value to <see cref=\"TimeSpan.Zero\"/>.", "/// </remarks>", "/// <remarks>", "/// It defaults to <see cref=\"TimeSpan.Zero\"/>.", "/// </remarks>", "/// </remarks>", "/// <summary>", "/// Specifies either the DNS name or the IP address of the proxy server.", "/// </summary>", "/// <summary>", "/// Specifies the port for the proxy server.", "/// </summary>", "/// <remarks>", "/// It defaults to <c>1080</c>.", "/// </remarks>", "/// <summary>", "/// Specifies the username for the proxy server.", "/// </summary>", "/// <summary>", "/// Specifies the password for the proxy server.", "/// </summary>", "/// <summary>", "/// Specifies the protocol used by the proxy server.", "/// </summary>", "/// <remarks>", "/// It defaults to <see cref=\"Microsoft.BizTalk.Adapter.Sftp.ProxyType.None\"/>.", "/// </remarks>", "/// <summary>", "/// If set to <c>True</c>, the receive location accepts any SSH public host key from the server. If set to", "/// <c>False</c>, the receive location uses the fingerprint of the server for authentication. You specify the", "/// fingerprint in the <see cref=\"SshServerHostKeyFingerPrint\"/> property.", "/// </summary>", "/// <remarks>", "/// It defaults to <c>False</c>.", "/// </remarks>", "/// <summary>", "/// Specifies the fingerprint of the server used by the adapter to authenticate the server if the <see", "/// cref=\"AccessAnySshServerHostKey\"/> property is set to <c>False</c>. If the fingerprints do not match, the", "/// connection fails.", "/// </summary>", "/// <summary>", "/// Specifies the authentication method that the receive location uses for authenticating the client to the SSH", "/// Server.", "/// </summary>", "/// <remarks>", "/// <para>", "/// If set to Password, you must specify the value in the <see", "/// cref=\"Microsoft.BizTalk.Adapter.Sftp.ClientAuthenticationMode.Password\"/> property. If set to <see", "/// cref=\"Microsoft.BizTalk.Adapter.Sftp.ClientAuthenticationMode.PublicKeyAuthentication\"/>, you must specify", "/// the private key of the user in the <see cref=\"PrivateKeyFile\"/> property. If set to <see", "/// cref=\"Microsoft.BizTalk.Adapter.Sftp.ClientAuthenticationMode.MultiFactorAuthentication\"/> you must provide", "/// <see cref=\"UserName\"/> with its <see cref=\"Password\"/> and <see cref=\"PrivateKeyFile\"/>. Additionally, if", "/// the private key is protected by a password, specify the password as well for the <see", "/// cref=\"PrivateKeyPassword\"/> property.", "/// </para>", "/// <para>", "/// It defaults to <see cref=\"Microsoft.BizTalk.Adapter.Sftp.ClientAuthenticationMode.Password\"/>.", "/// </para>", "/// </remarks>", "/// <summary>", "/// Specify the kind of encryption cipher.", "/// </summary>", "/// <summary>", "/// Specify the private key for the SFTP user if you set the <see cref=\"ClientAuthenticationMode\"/> to <see", "/// cref=\"Microsoft.BizTalk.Adapter.Sftp.ClientAuthenticationMode.PublicKeyAuthentication\"/>.", "/// </summary>", "/// <summary>", "/// Specify a private key password, if required for the key specified in the <see cref=\"PrivateKeyFile\"/>", "/// property.", "/// </summary>", "/// <summary>", "/// Specifies a username to log on to the SFTP server.", "/// </summary>", "/// <summary>", "/// Specify the SFTP user password if you set the <see cref=\"ClientAuthenticationMode\"/> to <see", "/// cref=\"Microsoft.BizTalk.Adapter.Sftp.ClientAuthenticationMode.Password\"/>.", "/// </summary>", "/// <summary>", "/// Specifies the server name or IP address of the secure FTP server.", "/// </summary>", "/// <summary>", "/// Specifies the port address for the secure FTP server on which the file transfer takes place.", "/// </summary>", "/// <remarks>", "/// It defaults to <c>22</c>.", "/// </remarks>", "/// <summary>", "/// Specifies the folder path on the secure FTP server from where the receive location can retrieve files.", "/// </summary>", "/// <summary>", "/// Specifies the file mask to use when retrieving files from a secure FTP server.", "/// </summary>" ]
[ { "param": "IInboundAdapter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "IInboundAdapter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "seealso", "docstring": "SFTP Adapter Frequently Asked Questions", "docstring_tokens": [ "SFTP", "Adapter", "Frequently", "Asked", "Questions" ] }, { "identifier": "seealso", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
16
986
101
d5b59c0f8ca5dba01f82d94504a068f37237df50
Maixiao/mai_commit-translator
RangeTree/RangeTreeAsync.cs
[ "MIT" ]
C#
RangeTreeAsync
/// <summary> /// The async range tree implementation. Keeps a root node and forwards all queries to it. Whenenver new items are added or items are removed, the tree goes "out of sync" and when the next query is started, the tree is being rebuilt in an async task. During the rebuild, queries are still done on the old tree plus on the items currently not part of the tree. If items were removed, these are filtered out. there is no need to wait for the rebuild to finish in order to return the query results. /// </summary> /// <typeparam name="TKey">The type of the range.</typeparam> /// <typeparam name="T">The type of the data items.</typeparam>
The async range tree implementation. Keeps a root node and forwards all queries to it. Whenenver new items are added or items are removed, the tree goes "out of sync" and when the next query is started, the tree is being rebuilt in an async task. During the rebuild, queries are still done on the old tree plus on the items currently not part of the tree. If items were removed, these are filtered out. there is no need to wait for the rebuild to finish in order to return the query results.
[ "The", "async", "range", "tree", "implementation", ".", "Keeps", "a", "root", "node", "and", "forwards", "all", "queries", "to", "it", ".", "Whenenver", "new", "items", "are", "added", "or", "items", "are", "removed", "the", "tree", "goes", "\"", "out", "of", "sync", "\"", "and", "when", "the", "next", "query", "is", "started", "the", "tree", "is", "being", "rebuilt", "in", "an", "async", "task", ".", "During", "the", "rebuild", "queries", "are", "still", "done", "on", "the", "old", "tree", "plus", "on", "the", "items", "currently", "not", "part", "of", "the", "tree", ".", "If", "items", "were", "removed", "these", "are", "filtered", "out", ".", "there", "is", "no", "need", "to", "wait", "for", "the", "rebuild", "to", "finish", "in", "order", "to", "return", "the", "query", "results", "." ]
public class RangeTreeAsync<TKey, T> : IRangeTree<TKey, T> where TKey : IComparable<TKey> where T : IRangeProvider<TKey> { private RangeTree<TKey, T> rangeTree; private List<T> addedItems = new List<T>(); private List<T> removedItems = new List<T>(); private List<T> addedItemsRebuilding = new List<T>(); private List<T> removedItemsRebuilding = new List<T>(); private IComparer<T> rangeComparer; private Task rebuildTask; private CancellationTokenSource rebuildTaskCancelSource; private bool isRebuilding; private object locker = new object(); public IEnumerable<T> Items { get { return this.rangeTree.Items.Concat(this.addedItemsRebuilding).Concat(this.addedItems); } } public int Count { get { return this.rangeTree.Count + this.addedItemsRebuilding.Count + this.addedItems.Count; } } public RangeTreeAsync(IComparer<T> rangeComparer) { this.rangeTree = new RangeTree<TKey, T>(rangeComparer) { AutoRebuild = false }; this.rangeComparer = rangeComparer; } public RangeTreeAsync(IEnumerable<T> items, IComparer<T> rangeComparer) { this.rangeTree = new RangeTree<TKey, T>(items, rangeComparer) { AutoRebuild = false }; this.rangeComparer = rangeComparer; } public List<T> Query(TKey value) { if (this.NeedsRebuild()) { this.RebuildTree(); } lock (this.locker) { var results = this.rangeTree.Query(value); results.AddRange(this.addedItemsRebuilding.Where(item => item.Range.Contains(value))); results.AddRange(this.addedItems.Where(item => item.Range.Contains(value))); return this.FilterResults(results); } } public List<T> Query(Range<TKey> range) { if (this.NeedsRebuild()) { this.RebuildTree(); } lock (this.locker) { var results = this.rangeTree.Query(range); results.AddRange(this.addedItemsRebuilding.Where(item => item.Range.Intersects(range))); results.AddRange(this.addedItems.Where(item => item.Range.Intersects(range))); return this.FilterResults(results); } } private List<T> FilterResults(List<T> results) { if (this.removedItemsRebuilding.Count > 0 || this.removedItems.Count > 0) { var hs = new HashSet<T>(results); foreach (var item in this.removedItemsRebuilding) { hs.Remove(item); } foreach (var item in this.removedItems) { hs.Remove(item); } results = hs.ToList(); } return results; } public void Add(T item) { lock (this.locker) { this.addedItems.Add(item); } } public void Add(IEnumerable<T> items) { lock (this.locker) { this.addedItems.AddRange(items); } } public void Remove(T item) { lock (this.locker) { this.removedItems.Add(item); } } public void Remove(IEnumerable<T> items) { lock (this.locker) { this.removedItems.AddRange(items); } } public void Clear() { lock (this.locker) { this.rangeTree.Clear(); this.addedItems = new List<T>(); this.removedItems = new List<T>(); this.addedItemsRebuilding = new List<T>(); this.removedItemsRebuilding = new List<T>(); if (this.rebuildTaskCancelSource != null) { this.rebuildTaskCancelSource.Cancel(); } } } public void Rebuild() { if (this.NeedsRebuild()) { this.RebuildTree(); } } private void RebuildTree() { lock (this.locker) { if (this.isRebuilding || this.addedItems.Count == 0) { return; } this.isRebuilding = true; } this.rebuildTaskCancelSource = new CancellationTokenSource(); this.rebuildTask = Task.Factory.StartNew( () => { lock (this.locker) { this.addedItemsRebuilding = this.addedItems.ToList(); this.addedItems.Clear(); this.removedItemsRebuilding = this.removedItemsRebuilding.ToList(); this.removedItems.Clear(); } var allItems = this.rangeTree.Items.ToList(); allItems.AddRange(this.addedItemsRebuilding); foreach (var item in this.removedItemsRebuilding) { allItems.Remove(item); } var newTree = new RangeTree<TKey, T>(allItems, this.rangeComparer) { AutoRebuild = false }; if (!this.rebuildTaskCancelSource.Token.IsCancellationRequested) { lock (this.locker) { this.rangeTree = newTree; this.addedItemsRebuilding.Clear(); this.removedItemsRebuilding.Clear(); } } else { } }, this.rebuildTaskCancelSource.Token) .ContinueWith(task => { this.isRebuilding = false; if (this.NeedsRebuild()) { this.RebuildTree(); } }); } private bool NeedsRebuild() { lock (this.locker) { return this.addedItems.Count > 100 || this.removedItems.Count > 100; } } }
[ "public", "class", "RangeTreeAsync", "<", "TKey", ",", "T", ">", ":", "IRangeTree", "<", "TKey", ",", "T", ">", "where", "TKey", ":", "IComparable", "<", "TKey", ">", "where", "T", ":", "IRangeProvider", "<", "TKey", ">", "{", "private", "RangeTree", "<", "TKey", ",", "T", ">", "rangeTree", ";", "private", "List", "<", "T", ">", "addedItems", "=", "new", "List", "<", "T", ">", "(", ")", ";", "private", "List", "<", "T", ">", "removedItems", "=", "new", "List", "<", "T", ">", "(", ")", ";", "private", "List", "<", "T", ">", "addedItemsRebuilding", "=", "new", "List", "<", "T", ">", "(", ")", ";", "private", "List", "<", "T", ">", "removedItemsRebuilding", "=", "new", "List", "<", "T", ">", "(", ")", ";", "private", "IComparer", "<", "T", ">", "rangeComparer", ";", "private", "Task", "rebuildTask", ";", "private", "CancellationTokenSource", "rebuildTaskCancelSource", ";", "private", "bool", "isRebuilding", ";", "private", "object", "locker", "=", "new", "object", "(", ")", ";", "public", "IEnumerable", "<", "T", ">", "Items", "{", "get", "{", "return", "this", ".", "rangeTree", ".", "Items", ".", "Concat", "(", "this", ".", "addedItemsRebuilding", ")", ".", "Concat", "(", "this", ".", "addedItems", ")", ";", "}", "}", "public", "int", "Count", "{", "get", "{", "return", "this", ".", "rangeTree", ".", "Count", "+", "this", ".", "addedItemsRebuilding", ".", "Count", "+", "this", ".", "addedItems", ".", "Count", ";", "}", "}", "public", "RangeTreeAsync", "(", "IComparer", "<", "T", ">", "rangeComparer", ")", "{", "this", ".", "rangeTree", "=", "new", "RangeTree", "<", "TKey", ",", "T", ">", "(", "rangeComparer", ")", "{", "AutoRebuild", "=", "false", "}", ";", "this", ".", "rangeComparer", "=", "rangeComparer", ";", "}", "public", "RangeTreeAsync", "(", "IEnumerable", "<", "T", ">", "items", ",", "IComparer", "<", "T", ">", "rangeComparer", ")", "{", "this", ".", "rangeTree", "=", "new", "RangeTree", "<", "TKey", ",", "T", ">", "(", "items", ",", "rangeComparer", ")", "{", "AutoRebuild", "=", "false", "}", ";", "this", ".", "rangeComparer", "=", "rangeComparer", ";", "}", "public", "List", "<", "T", ">", "Query", "(", "TKey", "value", ")", "{", "if", "(", "this", ".", "NeedsRebuild", "(", ")", ")", "{", "this", ".", "RebuildTree", "(", ")", ";", "}", "lock", "(", "this", ".", "locker", ")", "{", "var", "results", "=", "this", ".", "rangeTree", ".", "Query", "(", "value", ")", ";", "results", ".", "AddRange", "(", "this", ".", "addedItemsRebuilding", ".", "Where", "(", "item", "=>", "item", ".", "Range", ".", "Contains", "(", "value", ")", ")", ")", ";", "results", ".", "AddRange", "(", "this", ".", "addedItems", ".", "Where", "(", "item", "=>", "item", ".", "Range", ".", "Contains", "(", "value", ")", ")", ")", ";", "return", "this", ".", "FilterResults", "(", "results", ")", ";", "}", "}", "public", "List", "<", "T", ">", "Query", "(", "Range", "<", "TKey", ">", "range", ")", "{", "if", "(", "this", ".", "NeedsRebuild", "(", ")", ")", "{", "this", ".", "RebuildTree", "(", ")", ";", "}", "lock", "(", "this", ".", "locker", ")", "{", "var", "results", "=", "this", ".", "rangeTree", ".", "Query", "(", "range", ")", ";", "results", ".", "AddRange", "(", "this", ".", "addedItemsRebuilding", ".", "Where", "(", "item", "=>", "item", ".", "Range", ".", "Intersects", "(", "range", ")", ")", ")", ";", "results", ".", "AddRange", "(", "this", ".", "addedItems", ".", "Where", "(", "item", "=>", "item", ".", "Range", ".", "Intersects", "(", "range", ")", ")", ")", ";", "return", "this", ".", "FilterResults", "(", "results", ")", ";", "}", "}", "private", "List", "<", "T", ">", "FilterResults", "(", "List", "<", "T", ">", "results", ")", "{", "if", "(", "this", ".", "removedItemsRebuilding", ".", "Count", ">", "0", "||", "this", ".", "removedItems", ".", "Count", ">", "0", ")", "{", "var", "hs", "=", "new", "HashSet", "<", "T", ">", "(", "results", ")", ";", "foreach", "(", "var", "item", "in", "this", ".", "removedItemsRebuilding", ")", "{", "hs", ".", "Remove", "(", "item", ")", ";", "}", "foreach", "(", "var", "item", "in", "this", ".", "removedItems", ")", "{", "hs", ".", "Remove", "(", "item", ")", ";", "}", "results", "=", "hs", ".", "ToList", "(", ")", ";", "}", "return", "results", ";", "}", "public", "void", "Add", "(", "T", "item", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "addedItems", ".", "Add", "(", "item", ")", ";", "}", "}", "public", "void", "Add", "(", "IEnumerable", "<", "T", ">", "items", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "addedItems", ".", "AddRange", "(", "items", ")", ";", "}", "}", "public", "void", "Remove", "(", "T", "item", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "removedItems", ".", "Add", "(", "item", ")", ";", "}", "}", "public", "void", "Remove", "(", "IEnumerable", "<", "T", ">", "items", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "removedItems", ".", "AddRange", "(", "items", ")", ";", "}", "}", "public", "void", "Clear", "(", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "rangeTree", ".", "Clear", "(", ")", ";", "this", ".", "addedItems", "=", "new", "List", "<", "T", ">", "(", ")", ";", "this", ".", "removedItems", "=", "new", "List", "<", "T", ">", "(", ")", ";", "this", ".", "addedItemsRebuilding", "=", "new", "List", "<", "T", ">", "(", ")", ";", "this", ".", "removedItemsRebuilding", "=", "new", "List", "<", "T", ">", "(", ")", ";", "if", "(", "this", ".", "rebuildTaskCancelSource", "!=", "null", ")", "{", "this", ".", "rebuildTaskCancelSource", ".", "Cancel", "(", ")", ";", "}", "}", "}", "public", "void", "Rebuild", "(", ")", "{", "if", "(", "this", ".", "NeedsRebuild", "(", ")", ")", "{", "this", ".", "RebuildTree", "(", ")", ";", "}", "}", "private", "void", "RebuildTree", "(", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "if", "(", "this", ".", "isRebuilding", "||", "this", ".", "addedItems", ".", "Count", "==", "0", ")", "{", "return", ";", "}", "this", ".", "isRebuilding", "=", "true", ";", "}", "this", ".", "rebuildTaskCancelSource", "=", "new", "CancellationTokenSource", "(", ")", ";", "this", ".", "rebuildTask", "=", "Task", ".", "Factory", ".", "StartNew", "(", "(", ")", "=>", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "addedItemsRebuilding", "=", "this", ".", "addedItems", ".", "ToList", "(", ")", ";", "this", ".", "addedItems", ".", "Clear", "(", ")", ";", "this", ".", "removedItemsRebuilding", "=", "this", ".", "removedItemsRebuilding", ".", "ToList", "(", ")", ";", "this", ".", "removedItems", ".", "Clear", "(", ")", ";", "}", "var", "allItems", "=", "this", ".", "rangeTree", ".", "Items", ".", "ToList", "(", ")", ";", "allItems", ".", "AddRange", "(", "this", ".", "addedItemsRebuilding", ")", ";", "foreach", "(", "var", "item", "in", "this", ".", "removedItemsRebuilding", ")", "{", "allItems", ".", "Remove", "(", "item", ")", ";", "}", "var", "newTree", "=", "new", "RangeTree", "<", "TKey", ",", "T", ">", "(", "allItems", ",", "this", ".", "rangeComparer", ")", "{", "AutoRebuild", "=", "false", "}", ";", "if", "(", "!", "this", ".", "rebuildTaskCancelSource", ".", "Token", ".", "IsCancellationRequested", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "this", ".", "rangeTree", "=", "newTree", ";", "this", ".", "addedItemsRebuilding", ".", "Clear", "(", ")", ";", "this", ".", "removedItemsRebuilding", ".", "Clear", "(", ")", ";", "}", "}", "else", "{", "}", "}", ",", "this", ".", "rebuildTaskCancelSource", ".", "Token", ")", ".", "ContinueWith", "(", "task", "=>", "{", "this", ".", "isRebuilding", "=", "false", ";", "if", "(", "this", ".", "NeedsRebuild", "(", ")", ")", "{", "this", ".", "RebuildTree", "(", ")", ";", "}", "}", ")", ";", "}", "private", "bool", "NeedsRebuild", "(", ")", "{", "lock", "(", "this", ".", "locker", ")", "{", "return", "this", ".", "addedItems", ".", "Count", ">", "100", "||", "this", ".", "removedItems", ".", "Count", ">", "100", ";", "}", "}", "}" ]
The async range tree implementation.
[ "The", "async", "range", "tree", "implementation", "." ]
[ "/// <summary>", "/// Gets the items in the tree.", "/// </summary>", "/// <value>", "/// The items.", "/// </value>", "/// <summary>", "/// Gets the count of all items in the tree.", "/// </summary>", "/// <value>", "/// The count.", "/// </value>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"RangeTreeAsync{TKey, T}\"/> class.", "/// </summary>", "/// <param name=\"rangeComparer\">The range comparer.</param>", "/// <summary>", "/// Initializes a new instance of the <see cref=\"RangeTreeAsync{TKey, T}\"/> class.", "/// </summary>", "/// <param name=\"items\">The items.</param>", "/// <param name=\"rangeComparer\">The range comparer.</param>", "/// <summary>", "/// Performans a \"stab\" query with a single value. All items with overlapping ranges are returned.", "/// </summary>", "/// <param name=\"value\">The value.</param>", "/// <returns>The resulting <see cref=\"List{T}\"/></returns>", "// check if we need to start a rebuild task", "// query the tree (may be out of date)", "// add additional results", "/// <summary>", "/// Performans a range query. All items with overlapping ranges are returned.", "/// </summary>", "/// <param name=\"range\">The range.</param>", "/// <returns>The resulting <see cref=\"List{T}\"/></returns>", "// check if we need to start a rebuild task", "// query the tree (may be out of date)", "// add additional results", "/// <summary>", "/// Filter out results, if items were removed since the last rebuild.", "/// </summary>", "/// <param name=\"results\">The results.</param>", "/// <returns>The resulting <see cref=\"List{T}\"/></returns>", "/// <summary>", "/// Adds the specified item.", "/// </summary>", "/// <param name=\"item\">The item.</param>", "/// <summary>", "/// Adds the specified items.", "/// </summary>", "/// <param name=\"items\">The items.</param>", "/// <summary>", "/// Removes the specified item.", "/// </summary>", "/// <param name=\"item\">The item.</param>", "/// <summary>", "/// Removes the specified items.", "/// </summary>", "/// <param name=\"items\">The items.</param>", "/// <summary>", "/// Clears the tree (removes all items).", "/// </summary>", "/// <summary>", "/// Start the rebuild task if a rebuild is necessary.", "/// </summary>", "/// <summary>", "/// Rebuilds the tree by starting an async task.", "/// </summary>", "// if a rebuild is in progress return", "// store the items to be added, we need this if a query takes places", "// before we are finished rebuilding", "// store the items to be removed ...", "// all items of the tree", "// we may have to remove some", "// build the new tree", "// if task was not cancelled, set the new tree as the current one", "// nop", "// done with rebuilding, do we need to start again?", "/// <summary>", "/// Checks whether a rebuild is necessary.", "/// </summary>", "/// <returns>[true] is needs rebuild, otherwise [false]</returns>", "// only if count of added or removed items is > 100", "// otherwise, the sequential query is ok" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "typeparam", "docstring": "The type of the range.", "docstring_tokens": [ "The", "type", "of", "the", "range", "." ] }, { "identifier": "typeparam", "docstring": "The type of the data items.", "docstring_tokens": [ "The", "type", "of", "the", "data", "items", "." ] } ] }
false
22
1,216
148
5088f8c5d358aedffa51d91859249615e7a153e3
chiibis/rasn1
lib/rasn1/types/sequence.rb
[ "MIT" ]
Ruby
Sequence
# ASN.1 sequence # # A sequence is a collection of another ASN.1 types. # # To encode this ASN.1 example: # Record ::= SEQUENCE { # id INTEGER, # room [0] INTEGER OPTIONAL, # house [1] IMPLICIT INTEGER DEFAULT 0 # } # do: # seq = RASN1::Types::Sequence.new # seq.value = [ # RASN1::Types::Integer.new # RASN1::Types::Integer.new(explicit: 0, optional: true), # RASN1::Types::Integer.new(implicit: 1, default: 0) # ] # # A sequence may also be used without value to not parse sequence content: # seq = RASN1::Types::Sequence.new(:seq) # seq.parse!(der_string) # seq.value # => String # @author Sylvain Daubert
ASN.1 sequence A sequence is a collection of another ASN.1 types.
[ "ASN", ".", "1", "sequence", "A", "sequence", "is", "a", "collection", "of", "another", "ASN", ".", "1", "types", "." ]
class Sequence < Constructed TAG = 0x10 # @see Base#initialize def initialize(value_or_options={}, options={}) super @value ||= [] end def initialize_copy(other) super @value = @value.map { |v| v.dup } end private def value_to_der case @value when Array @value.map { |element| element.to_der }.join else @value.to_s end end def der_to_value(der, ber:false) if @value.is_a?(Array) and [email protected]? nb_bytes = 0 @value.each do |element| nb_bytes += element.parse!(der[nb_bytes..-1]) end else @value = der der.length end end end
[ "class", "Sequence", "<", "Constructed", "TAG", "=", "0x10", "def", "initialize", "(", "value_or_options", "=", "{", "}", ",", "options", "=", "{", "}", ")", "super", "@value", "||=", "[", "]", "end", "def", "initialize_copy", "(", "other", ")", "super", "@value", "=", "@value", ".", "map", "{", "|", "v", "|", "v", ".", "dup", "}", "end", "private", "def", "value_to_der", "case", "@value", "when", "Array", "@value", ".", "map", "{", "|", "element", "|", "element", ".", "to_der", "}", ".", "join", "else", "@value", ".", "to_s", "end", "end", "def", "der_to_value", "(", "der", ",", "ber", ":", "false", ")", "if", "@value", ".", "is_a?", "(", "Array", ")", "and", "!", "@value", ".", "empty?", "nb_bytes", "=", "0", "@value", ".", "each", "do", "|", "element", "|", "nb_bytes", "+=", "element", ".", "parse!", "(", "der", "[", "nb_bytes", "..", "-", "1", "]", ")", "end", "else", "@value", "=", "der", "der", ".", "length", "end", "end", "end" ]
ASN.1 sequence A sequence is a collection of another ASN.1 types.
[ "ASN", ".", "1", "sequence", "A", "sequence", "is", "a", "collection", "of", "another", "ASN", ".", "1", "types", "." ]
[ "# @see Base#initialize" ]
[ { "param": "Constructed", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Constructed", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [ { "identifier": "author", "docstring": null, "docstring_tokens": [ "None" ] } ] }
false
16
197
202
1ef35667bcb6c4bc5a89c12eedf06627bd2d49b6
hasibaasma/alfpy
alfpy/word_vector.py
[ "MIT" ]
Python
WordModel
Variance of frequencies of words (k-mers) based on their overlap capabilities. References: 1. Hohl and Ragan. (2007) Systematic Biology. 56. 2007. p. 206-221 doi: 10.1080/10635150701294741. 2. Hohl, Rigoutsos, Ragan (2006) Evol Bioinform Online 2: 359-375. doi: 10.1080/10635150701294741. 3. Gentleman and Mullin, Biometrics (1989): 45(1), p.35-52. doi: 10.2307/2532033
Variance of frequencies of words (k-mers) based on their overlap capabilities. 1. Hohl and Ragan. (2007) Systematic Biology. 56. 2007. p.
[ "Variance", "of", "frequencies", "of", "words", "(", "k", "-", "mers", ")", "based", "on", "their", "overlap", "capabilities", ".", "1", ".", "Hohl", "and", "Ragan", ".", "(", "2007", ")", "Systematic", "Biology", ".", "56", ".", "2007", ".", "p", "." ]
class WordModel: """Variance of frequencies of words (k-mers) based on their overlap capabilities. References: 1. Hohl and Ragan. (2007) Systematic Biology. 56. 2007. p. 206-221 doi: 10.1080/10635150701294741. 2. Hohl, Rigoutsos, Ragan (2006) Evol Bioinform Online 2: 359-375. doi: 10.1080/10635150701294741. 3. Gentleman and Mullin, Biometrics (1989): 45(1), p.35-52. doi: 10.2307/2532033 """ def probabilities(self, word): """Calculate P_L, the probability of a word, and all probabilities P_k of its prefixes. Needs to be implemented by subclasses """ raise NotImplementedError def overlap_capability(self, word): """Calculate overlap capability of a given word. Overlap capability indicates to what extent the prefix and suffix of a word are equal (i.e. if the word beginning is the same as the ending). In other words, it indicates periodicity in the word, which leads to higher probability of co-occurence of words sharing the repeated motifs. For example, the word AAAA can occur between 0 and 17 times within a sequence of length 20. The word ACAC cannot occur more than 9 tiummes within a sequence of length 20 because it has less overlap capability. The word ACGT jas no overlap capability. Args: word (str): k-mer to get the overlap capability Returns: A list of binary values. For example, the word ACAC gives overlap capability of [0,1,0,1] and the word AAAC has overlap capability [0,0,0,1] """ value = [] length = len(word) for i in range(1, length): v = 1 if word[0:i] == word[length - i:length] else 0 value.append(v) # i == len(word) - overlap capability is 1 (word overlaps itself) value.append(1) return value def var(self, word, seq_len, word_len=None, overlap_capability=None, word_probs=None): """Calculate the variance of word frequencies. The variance depends on overlap capability and is larger for words with a high level of overlap capability. Original formula (LaTeX): var(X) = np(1-np)+p^{2}(n-L)(n-L+1)+2p\sum_{k=1}^{min(L-1,n-1)} (n-k)Q_{L-k}(\frac{1}{4})^{k} where X: frequency of occurrence of subsequence, i.e. word Q: overlap capability of word L: length of word M: length of sequence n = M-L+1 (maximum possible number of words) p = (1/4)^L assuming DNA sequence, alphabet size = 4 In this implementation, the alphabet size is not assumed to be 4. For arbitrary symbol frequencies, substitute in original formula: P_L for p P_k for (1/4)^k Args: seq_len (int): length of sequence in which word occurs word_len (int): length of word (may be pre-computed) overlap_capability (list): may be pre-computed word_probs (list): may be pre-computed Returns: variance (float) of word's frequency """ # compute only if necessary if word_len is None: word_len = len(word) if overlap_capability is None: overlap_capability = self.overlap_capability(word) if word_probs is None: word_probs = self.probabilities(word) # p = P_L == last element p = word_probs[-1] max_num = seq_len - word_len + 1 # should be: min_term = min(word_len-1, max_num-1) # but: sum_term uses range() which stops at min_term-1 min_term = min(word_len, max_num) # should be: overlap_capability[word_len-k] == Q_{L-k} # but: overlap_capability starts at 0, Q at 1 # should be: word_probs[k] == P_k # but: word_probs starts at 0, P_k at 1 sum_term = [(max_num - k) * overlap_capability[word_len - k - 1] * word_probs[k - 1] for k in range(1, min_term)] np = max_num * p n_L = max_num - word_len value = np * (1 - np) + pow(p, 2) * (n_L) * \ (n_L + 1) + 2 * p * sum(sum_term) return value
[ "class", "WordModel", ":", "def", "probabilities", "(", "self", ",", "word", ")", ":", "\"\"\"Calculate P_L, the probability of a word,\n and all probabilities P_k of its prefixes.\n\n Needs to be implemented by subclasses\n \"\"\"", "raise", "NotImplementedError", "def", "overlap_capability", "(", "self", ",", "word", ")", ":", "\"\"\"Calculate overlap capability of a given word.\n\n Overlap capability indicates to what extent the prefix and suffix\n of a word are equal (i.e. if the word beginning is the same as the\n ending).\n\n In other words, it indicates periodicity in the word, which leads\n to higher probability of co-occurence of words sharing the repeated\n motifs.\n\n For example, the word AAAA can occur between 0 and 17 times within\n a sequence of length 20. The word ACAC cannot occur more than 9\n tiummes within a sequence of length 20 because it has less overlap\n capability. The word ACGT jas no overlap capability.\n\n Args:\n word (str): k-mer to get the overlap capability\n Returns:\n A list of binary values. For example, the word ACAC gives overlap\n capability of [0,1,0,1] and the word AAAC has overlap capability\n [0,0,0,1]\n\n \"\"\"", "value", "=", "[", "]", "length", "=", "len", "(", "word", ")", "for", "i", "in", "range", "(", "1", ",", "length", ")", ":", "v", "=", "1", "if", "word", "[", "0", ":", "i", "]", "==", "word", "[", "length", "-", "i", ":", "length", "]", "else", "0", "value", ".", "append", "(", "v", ")", "value", ".", "append", "(", "1", ")", "return", "value", "def", "var", "(", "self", ",", "word", ",", "seq_len", ",", "word_len", "=", "None", ",", "overlap_capability", "=", "None", ",", "word_probs", "=", "None", ")", ":", "\"\"\"Calculate the variance of word frequencies.\n\n The variance depends on overlap capability and is larger for\n words with a high level of overlap capability.\n\n Original formula (LaTeX):\n var(X) = np(1-np)+p^{2}(n-L)(n-L+1)+2p\\sum_{k=1}^{min(L-1,n-1)}\n (n-k)Q_{L-k}(\\frac{1}{4})^{k}\n\n where X: frequency of occurrence of subsequence, i.e. word\n Q: overlap capability of word\n L: length of word\n M: length of sequence\n n = M-L+1 (maximum possible number of words)\n p = (1/4)^L\n assuming DNA sequence, alphabet size = 4\n\n In this implementation, the alphabet size is not assumed to be 4.\n\n For arbitrary symbol frequencies, substitute in original formula:\n P_L for p\n P_k for (1/4)^k\n\n Args:\n seq_len (int): length of sequence in which word occurs\n word_len (int): length of word (may be pre-computed)\n overlap_capability (list): may be pre-computed\n word_probs (list): may be pre-computed\n Returns:\n variance (float) of word's frequency\n \"\"\"", "if", "word_len", "is", "None", ":", "word_len", "=", "len", "(", "word", ")", "if", "overlap_capability", "is", "None", ":", "overlap_capability", "=", "self", ".", "overlap_capability", "(", "word", ")", "if", "word_probs", "is", "None", ":", "word_probs", "=", "self", ".", "probabilities", "(", "word", ")", "p", "=", "word_probs", "[", "-", "1", "]", "max_num", "=", "seq_len", "-", "word_len", "+", "1", "min_term", "=", "min", "(", "word_len", ",", "max_num", ")", "sum_term", "=", "[", "(", "max_num", "-", "k", ")", "*", "overlap_capability", "[", "word_len", "-", "k", "-", "1", "]", "*", "word_probs", "[", "k", "-", "1", "]", "for", "k", "in", "range", "(", "1", ",", "min_term", ")", "]", "np", "=", "max_num", "*", "p", "n_L", "=", "max_num", "-", "word_len", "value", "=", "np", "*", "(", "1", "-", "np", ")", "+", "pow", "(", "p", ",", "2", ")", "*", "(", "n_L", ")", "*", "(", "n_L", "+", "1", ")", "+", "2", "*", "p", "*", "sum", "(", "sum_term", ")", "return", "value" ]
Variance of frequencies of words (k-mers) based on their overlap capabilities.
[ "Variance", "of", "frequencies", "of", "words", "(", "k", "-", "mers", ")", "based", "on", "their", "overlap", "capabilities", "." ]
[ "\"\"\"Variance of frequencies of words (k-mers) based on their overlap\n capabilities.\n\n References:\n 1. Hohl and Ragan. (2007) Systematic Biology. 56. 2007. p. 206-221\n doi: 10.1080/10635150701294741.\n 2. Hohl, Rigoutsos, Ragan (2006) Evol Bioinform Online 2: 359-375.\n doi: 10.1080/10635150701294741.\n 3. Gentleman and Mullin, Biometrics (1989): 45(1), p.35-52.\n doi: 10.2307/2532033\n\n \"\"\"", "\"\"\"Calculate P_L, the probability of a word,\n and all probabilities P_k of its prefixes.\n\n Needs to be implemented by subclasses\n \"\"\"", "\"\"\"Calculate overlap capability of a given word.\n\n Overlap capability indicates to what extent the prefix and suffix\n of a word are equal (i.e. if the word beginning is the same as the\n ending).\n\n In other words, it indicates periodicity in the word, which leads\n to higher probability of co-occurence of words sharing the repeated\n motifs.\n\n For example, the word AAAA can occur between 0 and 17 times within\n a sequence of length 20. The word ACAC cannot occur more than 9\n tiummes within a sequence of length 20 because it has less overlap\n capability. The word ACGT jas no overlap capability.\n\n Args:\n word (str): k-mer to get the overlap capability\n Returns:\n A list of binary values. For example, the word ACAC gives overlap\n capability of [0,1,0,1] and the word AAAC has overlap capability\n [0,0,0,1]\n\n \"\"\"", "# i == len(word) - overlap capability is 1 (word overlaps itself)", "\"\"\"Calculate the variance of word frequencies.\n\n The variance depends on overlap capability and is larger for\n words with a high level of overlap capability.\n\n Original formula (LaTeX):\n var(X) = np(1-np)+p^{2}(n-L)(n-L+1)+2p\\sum_{k=1}^{min(L-1,n-1)}\n (n-k)Q_{L-k}(\\frac{1}{4})^{k}\n\n where X: frequency of occurrence of subsequence, i.e. word\n Q: overlap capability of word\n L: length of word\n M: length of sequence\n n = M-L+1 (maximum possible number of words)\n p = (1/4)^L\n assuming DNA sequence, alphabet size = 4\n\n In this implementation, the alphabet size is not assumed to be 4.\n\n For arbitrary symbol frequencies, substitute in original formula:\n P_L for p\n P_k for (1/4)^k\n\n Args:\n seq_len (int): length of sequence in which word occurs\n word_len (int): length of word (may be pre-computed)\n overlap_capability (list): may be pre-computed\n word_probs (list): may be pre-computed\n Returns:\n variance (float) of word's frequency\n \"\"\"", "# compute only if necessary", "# p = P_L == last element", "# should be: min_term = min(word_len-1, max_num-1)", "# but: sum_term uses range() which stops at min_term-1", "# should be: overlap_capability[word_len-k] == Q_{L-k}", "# but: overlap_capability starts at 0, Q at 1", "# should be: word_probs[k] == P_k", "# but: word_probs starts at 0, P_k at 1" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
14
1,179
212
0b416779155be17d2cb38b99cb2da0059183cb83
wtfacoconut/fcli
src/main/java/com/fortify/cli/app/FortifyCLILogHelper.java
[ "MIT" ]
Java
FortifyCLILogHelper
/** * This class is responsible for setting up logging. It simply sets up a * small {@link CommandLine} instance with a single {@link SetupLoggingCommand} * that looks for logging parameters as defined in {@link LoggingMixin} * while ignoring everything else (including any sub-commands) on the command * line; this essentially means that this command will always run. Upon execution, * the {@link SetupLoggingCommand} will simply invoke {@link LoggingMixin#configureLogging()} * to actually configure the logging. All output from this small {@link CommandLine} * implementation will be suppressed by sending the output to a dummy {@link PrintWriter}. * * @author Ruud Senden */
This class is responsible for setting up logging. It simply sets up a small CommandLine instance with a single SetupLoggingCommand that looks for logging parameters as defined in LoggingMixin while ignoring everything else (including any sub-commands) on the command line; this essentially means that this command will always run. Upon execution, the SetupLoggingCommand will simply invoke LoggingMixin#configureLogging() to actually configure the logging. All output from this small CommandLine implementation will be suppressed by sending the output to a dummy PrintWriter. @author Ruud Senden
[ "This", "class", "is", "responsible", "for", "setting", "up", "logging", ".", "It", "simply", "sets", "up", "a", "small", "CommandLine", "instance", "with", "a", "single", "SetupLoggingCommand", "that", "looks", "for", "logging", "parameters", "as", "defined", "in", "LoggingMixin", "while", "ignoring", "everything", "else", "(", "including", "any", "sub", "-", "commands", ")", "on", "the", "command", "line", ";", "this", "essentially", "means", "that", "this", "command", "will", "always", "run", ".", "Upon", "execution", "the", "SetupLoggingCommand", "will", "simply", "invoke", "LoggingMixin#configureLogging", "()", "to", "actually", "configure", "the", "logging", ".", "All", "output", "from", "this", "small", "CommandLine", "implementation", "will", "be", "suppressed", "by", "sending", "the", "output", "to", "a", "dummy", "PrintWriter", ".", "@author", "Ruud", "Senden" ]
public class FortifyCLILogHelper { private static final PrintWriter DUMMY_WRITER = new PrintWriter(new StringWriter()); /** * Configure logging based on the provided command line arguments. * @param args Arguments passed on the command line */ public static final void configureLogging(String[] args) { CommandLine commandLine = new CommandLine(SetupLoggingCommand.class) .setOut(DUMMY_WRITER) .setErr(DUMMY_WRITER) .setUnmatchedArgumentsAllowed(true) .setUnmatchedOptionsArePositionalParams(true) .setDefaultValueProvider(new DefaultValueProvider()) .setExpandAtFiles(true); commandLine.execute(args); } /** * {@link Command} implementation for setting up logging, based on the * options and functionality provided by {@link LoggingMixin}. * * @author Ruud Senden */ @Command() public static final class SetupLoggingCommand implements Runnable { @Mixin LoggingMixin loggingMixin; /** * Configure logging by calling the {@link LoggingMixin#configureLogging()} * method. */ @Override public void run() { loggingMixin.configureLogging(); } } }
[ "public", "class", "FortifyCLILogHelper", "{", "private", "static", "final", "PrintWriter", "DUMMY_WRITER", "=", "new", "PrintWriter", "(", "new", "StringWriter", "(", ")", ")", ";", "/**\n\t * Configure logging based on the provided command line arguments.\n\t * @param args Arguments passed on the command line\n\t */", "public", "static", "final", "void", "configureLogging", "(", "String", "[", "]", "args", ")", "{", "CommandLine", "commandLine", "=", "new", "CommandLine", "(", "SetupLoggingCommand", ".", "class", ")", ".", "setOut", "(", "DUMMY_WRITER", ")", ".", "setErr", "(", "DUMMY_WRITER", ")", ".", "setUnmatchedArgumentsAllowed", "(", "true", ")", ".", "setUnmatchedOptionsArePositionalParams", "(", "true", ")", ".", "setDefaultValueProvider", "(", "new", "DefaultValueProvider", "(", ")", ")", ".", "setExpandAtFiles", "(", "true", ")", ";", "commandLine", ".", "execute", "(", "args", ")", ";", "}", "/**\n\t * {@link Command} implementation for setting up logging, based on the\n\t * options and functionality provided by {@link LoggingMixin}.\n\t * \n\t * @author Ruud Senden\n\t */", "@", "Command", "(", ")", "public", "static", "final", "class", "SetupLoggingCommand", "implements", "Runnable", "{", "@", "Mixin", "LoggingMixin", "loggingMixin", ";", "/**\n\t\t * Configure logging by calling the {@link LoggingMixin#configureLogging()}\n\t\t * method.\n\t\t */", "@", "Override", "public", "void", "run", "(", ")", "{", "loggingMixin", ".", "configureLogging", "(", ")", ";", "}", "}", "}" ]
This class is responsible for setting up logging.
[ "This", "class", "is", "responsible", "for", "setting", "up", "logging", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
255
142
b07a924a4e3f377f906045e4fb75c65201a3353a
PJB2TY/hbase
hbase-common/src/test/java/org/apache/hadoop/hbase/util/RandomDistribution.java
[ "Apache-2.0" ]
Java
RandomDistribution
/** * A class that generates random numbers that follow some distribution. * <p> * Copied from <a href="https://issues.apache.org/jira/browse/HADOOP-3315">hadoop-3315 tfile</a>. * Remove after tfile is committed and use the tfile version of this class instead. * </p> */
A class that generates random numbers that follow some distribution. Copied from hadoop-3315 tfile. Remove after tfile is committed and use the tfile version of this class instead.
[ "A", "class", "that", "generates", "random", "numbers", "that", "follow", "some", "distribution", ".", "Copied", "from", "hadoop", "-", "3315", "tfile", ".", "Remove", "after", "tfile", "is", "committed", "and", "use", "the", "tfile", "version", "of", "this", "class", "instead", "." ]
public class RandomDistribution { /** * Interface for discrete (integer) random distributions. */ public interface DiscreteRNG { /** * Get the next random number * @return the next random number. */ int nextInt(); } /** * P(i)=1/(max-min) */ public static final class Flat implements DiscreteRNG { private final Random random; private final int min; private final int max; /** * Generate random integers from min (inclusive) to max (exclusive) following even distribution. * n * The basic random number generator. n * Minimum integer n * maximum integer (exclusive). */ public Flat(Random random, int min, int max) { if (min >= max) { throw new IllegalArgumentException("Invalid range"); } this.random = random; this.min = min; this.max = max; } /** * @see DiscreteRNG#nextInt() */ @Override public int nextInt() { return random.nextInt(max - min) + min; } } /** * Zipf distribution. The ratio of the probabilities of integer i and j is defined as follows: * P(i)/P(j)=((j-min+1)/(i-min+1))^sigma. */ public static final class Zipf implements DiscreteRNG { private static final double DEFAULT_EPSILON = 0.001; private final Random random; private final ArrayList<Integer> k; private final ArrayList<Double> v; /** * Constructor n * The random number generator. n * minimum integer (inclusvie) n * maximum * integer (exclusive) n * parameter sigma. (sigma > 1.0) */ public Zipf(Random r, int min, int max, double sigma) { this(r, min, max, sigma, DEFAULT_EPSILON); } /** * Constructor. n * The random number generator. n * minimum integer (inclusvie) n * maximum * integer (exclusive) n * parameter sigma. (sigma > 1.0) n * Allowable error percentage (0 < * epsilon < 1.0). */ public Zipf(Random r, int min, int max, double sigma, double epsilon) { if ((max <= min) || (sigma <= 1) || (epsilon <= 0) || (epsilon >= 0.5)) { throw new IllegalArgumentException("Invalid arguments"); } random = r; k = new ArrayList<>(); v = new ArrayList<>(); double sum = 0; int last = -1; for (int i = min; i < max; ++i) { sum += Math.exp(-sigma * Math.log(i - min + 1)); if ((last == -1) || i * (1 - epsilon) > last) { k.add(i); v.add(sum); last = i; } } if (last != max - 1) { k.add(max - 1); v.add(sum); } v.set(v.size() - 1, 1.0); for (int i = v.size() - 2; i >= 0; --i) { v.set(i, v.get(i) / sum); } } /** * @see DiscreteRNG#nextInt() */ @Override public int nextInt() { double d = random.nextDouble(); int idx = Collections.binarySearch(v, d); if (idx > 0) { ++idx; } else { idx = -(idx + 1); } if (idx >= v.size()) { idx = v.size() - 1; } if (idx == 0) { return k.get(0); } int ceiling = k.get(idx); int lower = k.get(idx - 1); return ceiling - random.nextInt(ceiling - lower); } } /** * Binomial distribution. P(k)=select(n, k)*p^k*(1-p)^(n-k) (k = 0, 1, ..., n) * P(k)=select(max-min-1, k-min)*p^(k-min)*(1-p)^(k-min)*(1-p)^(max-k-1) */ public static final class Binomial implements DiscreteRNG { private final Random random; private final int min; private final int n; private final double[] v; private static double select(int n, int k) { double ret = 1.0; for (int i = k + 1; i <= n; ++i) { ret *= (double) i / (i - k); } return ret; } private static double power(double p, int k) { return Math.exp(k * Math.log(p)); } /** * Generate random integers from min (inclusive) to max (exclusive) following Binomial * distribution. n * The basic random number generator. n * Minimum integer n * maximum integer * (exclusive). n * parameter. */ public Binomial(Random random, int min, int max, double p) { if (min >= max) { throw new IllegalArgumentException("Invalid range"); } this.random = random; this.min = min; this.n = max - min - 1; if (n > 0) { v = new double[n + 1]; double sum = 0.0; for (int i = 0; i <= n; ++i) { sum += select(n, i) * power(p, i) * power(1 - p, n - i); v[i] = sum; } for (int i = 0; i <= n; ++i) { v[i] /= sum; } } else { v = null; } } /** * @see DiscreteRNG#nextInt() */ @Override public int nextInt() { if (v == null) { return min; } double d = random.nextDouble(); int idx = Arrays.binarySearch(v, d); if (idx > 0) { ++idx; } else { idx = -(idx + 1); } if (idx >= v.length) { idx = v.length - 1; } return idx + min; } } }
[ "public", "class", "RandomDistribution", "{", "/**\n * Interface for discrete (integer) random distributions.\n */", "public", "interface", "DiscreteRNG", "{", "/**\n * Get the next random number\n * @return the next random number.\n */", "int", "nextInt", "(", ")", ";", "}", "/**\n * P(i)=1/(max-min)\n */", "public", "static", "final", "class", "Flat", "implements", "DiscreteRNG", "{", "private", "final", "Random", "random", ";", "private", "final", "int", "min", ";", "private", "final", "int", "max", ";", "/**\n * Generate random integers from min (inclusive) to max (exclusive) following even distribution.\n * n * The basic random number generator. n * Minimum integer n * maximum integer (exclusive).\n */", "public", "Flat", "(", "Random", "random", ",", "int", "min", ",", "int", "max", ")", "{", "if", "(", "min", ">=", "max", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Invalid range", "\"", ")", ";", "}", "this", ".", "random", "=", "random", ";", "this", ".", "min", "=", "min", ";", "this", ".", "max", "=", "max", ";", "}", "/**\n * @see DiscreteRNG#nextInt()\n */", "@", "Override", "public", "int", "nextInt", "(", ")", "{", "return", "random", ".", "nextInt", "(", "max", "-", "min", ")", "+", "min", ";", "}", "}", "/**\n * Zipf distribution. The ratio of the probabilities of integer i and j is defined as follows:\n * P(i)/P(j)=((j-min+1)/(i-min+1))^sigma.\n */", "public", "static", "final", "class", "Zipf", "implements", "DiscreteRNG", "{", "private", "static", "final", "double", "DEFAULT_EPSILON", "=", "0.001", ";", "private", "final", "Random", "random", ";", "private", "final", "ArrayList", "<", "Integer", ">", "k", ";", "private", "final", "ArrayList", "<", "Double", ">", "v", ";", "/**\n * Constructor n * The random number generator. n * minimum integer (inclusvie) n * maximum\n * integer (exclusive) n * parameter sigma. (sigma > 1.0)\n */", "public", "Zipf", "(", "Random", "r", ",", "int", "min", ",", "int", "max", ",", "double", "sigma", ")", "{", "this", "(", "r", ",", "min", ",", "max", ",", "sigma", ",", "DEFAULT_EPSILON", ")", ";", "}", "/**\n * Constructor. n * The random number generator. n * minimum integer (inclusvie) n * maximum\n * integer (exclusive) n * parameter sigma. (sigma > 1.0) n * Allowable error percentage (0 <\n * epsilon < 1.0).\n */", "public", "Zipf", "(", "Random", "r", ",", "int", "min", ",", "int", "max", ",", "double", "sigma", ",", "double", "epsilon", ")", "{", "if", "(", "(", "max", "<=", "min", ")", "||", "(", "sigma", "<=", "1", ")", "||", "(", "epsilon", "<=", "0", ")", "||", "(", "epsilon", ">=", "0.5", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Invalid arguments", "\"", ")", ";", "}", "random", "=", "r", ";", "k", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "v", "=", "new", "ArrayList", "<", ">", "(", ")", ";", "double", "sum", "=", "0", ";", "int", "last", "=", "-", "1", ";", "for", "(", "int", "i", "=", "min", ";", "i", "<", "max", ";", "++", "i", ")", "{", "sum", "+=", "Math", ".", "exp", "(", "-", "sigma", "*", "Math", ".", "log", "(", "i", "-", "min", "+", "1", ")", ")", ";", "if", "(", "(", "last", "==", "-", "1", ")", "||", "i", "*", "(", "1", "-", "epsilon", ")", ">", "last", ")", "{", "k", ".", "add", "(", "i", ")", ";", "v", ".", "add", "(", "sum", ")", ";", "last", "=", "i", ";", "}", "}", "if", "(", "last", "!=", "max", "-", "1", ")", "{", "k", ".", "add", "(", "max", "-", "1", ")", ";", "v", ".", "add", "(", "sum", ")", ";", "}", "v", ".", "set", "(", "v", ".", "size", "(", ")", "-", "1", ",", "1.0", ")", ";", "for", "(", "int", "i", "=", "v", ".", "size", "(", ")", "-", "2", ";", "i", ">=", "0", ";", "--", "i", ")", "{", "v", ".", "set", "(", "i", ",", "v", ".", "get", "(", "i", ")", "/", "sum", ")", ";", "}", "}", "/**\n * @see DiscreteRNG#nextInt()\n */", "@", "Override", "public", "int", "nextInt", "(", ")", "{", "double", "d", "=", "random", ".", "nextDouble", "(", ")", ";", "int", "idx", "=", "Collections", ".", "binarySearch", "(", "v", ",", "d", ")", ";", "if", "(", "idx", ">", "0", ")", "{", "++", "idx", ";", "}", "else", "{", "idx", "=", "-", "(", "idx", "+", "1", ")", ";", "}", "if", "(", "idx", ">=", "v", ".", "size", "(", ")", ")", "{", "idx", "=", "v", ".", "size", "(", ")", "-", "1", ";", "}", "if", "(", "idx", "==", "0", ")", "{", "return", "k", ".", "get", "(", "0", ")", ";", "}", "int", "ceiling", "=", "k", ".", "get", "(", "idx", ")", ";", "int", "lower", "=", "k", ".", "get", "(", "idx", "-", "1", ")", ";", "return", "ceiling", "-", "random", ".", "nextInt", "(", "ceiling", "-", "lower", ")", ";", "}", "}", "/**\n * Binomial distribution. P(k)=select(n, k)*p^k*(1-p)^(n-k) (k = 0, 1, ..., n)\n * P(k)=select(max-min-1, k-min)*p^(k-min)*(1-p)^(k-min)*(1-p)^(max-k-1)\n */", "public", "static", "final", "class", "Binomial", "implements", "DiscreteRNG", "{", "private", "final", "Random", "random", ";", "private", "final", "int", "min", ";", "private", "final", "int", "n", ";", "private", "final", "double", "[", "]", "v", ";", "private", "static", "double", "select", "(", "int", "n", ",", "int", "k", ")", "{", "double", "ret", "=", "1.0", ";", "for", "(", "int", "i", "=", "k", "+", "1", ";", "i", "<=", "n", ";", "++", "i", ")", "{", "ret", "*=", "(", "double", ")", "i", "/", "(", "i", "-", "k", ")", ";", "}", "return", "ret", ";", "}", "private", "static", "double", "power", "(", "double", "p", ",", "int", "k", ")", "{", "return", "Math", ".", "exp", "(", "k", "*", "Math", ".", "log", "(", "p", ")", ")", ";", "}", "/**\n * Generate random integers from min (inclusive) to max (exclusive) following Binomial\n * distribution. n * The basic random number generator. n * Minimum integer n * maximum integer\n * (exclusive). n * parameter.\n */", "public", "Binomial", "(", "Random", "random", ",", "int", "min", ",", "int", "max", ",", "double", "p", ")", "{", "if", "(", "min", ">=", "max", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "Invalid range", "\"", ")", ";", "}", "this", ".", "random", "=", "random", ";", "this", ".", "min", "=", "min", ";", "this", ".", "n", "=", "max", "-", "min", "-", "1", ";", "if", "(", "n", ">", "0", ")", "{", "v", "=", "new", "double", "[", "n", "+", "1", "]", ";", "double", "sum", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "n", ";", "++", "i", ")", "{", "sum", "+=", "select", "(", "n", ",", "i", ")", "*", "power", "(", "p", ",", "i", ")", "*", "power", "(", "1", "-", "p", ",", "n", "-", "i", ")", ";", "v", "[", "i", "]", "=", "sum", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "n", ";", "++", "i", ")", "{", "v", "[", "i", "]", "/=", "sum", ";", "}", "}", "else", "{", "v", "=", "null", ";", "}", "}", "/**\n * @see DiscreteRNG#nextInt()\n */", "@", "Override", "public", "int", "nextInt", "(", ")", "{", "if", "(", "v", "==", "null", ")", "{", "return", "min", ";", "}", "double", "d", "=", "random", ".", "nextDouble", "(", ")", ";", "int", "idx", "=", "Arrays", ".", "binarySearch", "(", "v", ",", "d", ")", ";", "if", "(", "idx", ">", "0", ")", "{", "++", "idx", ";", "}", "else", "{", "idx", "=", "-", "(", "idx", "+", "1", ")", ";", "}", "if", "(", "idx", ">=", "v", ".", "length", ")", "{", "idx", "=", "v", ".", "length", "-", "1", ";", "}", "return", "idx", "+", "min", ";", "}", "}", "}" ]
A class that generates random numbers that follow some distribution.
[ "A", "class", "that", "generates", "random", "numbers", "that", "follow", "some", "distribution", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
18
1,411
77
e94f799ad42b977f398446cff879a6ba742e948a
tomdeborst/aws-bookstore-demo-app
assets/node_modules/@aws-sdk/client-rekognition/dist/cjs/commands/GetTextDetectionCommand.js
[ "MIT-0" ]
JavaScript
GetTextDetectionCommand
/** * <p>Gets the text detection results of a Amazon Rekognition Video analysis started by <a>StartTextDetection</a>.</p> * <p>Text detection with Amazon Rekognition Video is an asynchronous operation. You start text detection by * calling <a>StartTextDetection</a> which returns a job identifier (<code>JobId</code>) * When the text detection operation finishes, Amazon Rekognition publishes a completion status to the Amazon Simple Notification Service * topic registered in the initial call to <code>StartTextDetection</code>. To get the results * of the text detection operation, first check that the status value published to the Amazon SNS topic is <code>SUCCEEDED</code>. * if so, call <code>GetTextDetection</code> and pass the job identifier (<code>JobId</code>) from the initial call * of <code>StartLabelDetection</code>.</p> * <p> * <code>GetTextDetection</code> returns an array of detected text (<code>TextDetections</code>) sorted by * the time the text was detected, up to 50 words per frame of video.</p> * <p>Each element of the array includes the detected text, the precentage confidence in the acuracy * of the detected text, the time the text was detected, bounding box information for where the text * was located, and unique identifiers for words and their lines.</p> * <p>Use MaxResults parameter to limit the number of text detections returned. If there are more results than * specified in <code>MaxResults</code>, the value of <code>NextToken</code> in the operation response contains * a pagination token for getting the next set of results. To get the next page of results, call <code>GetTextDetection</code> * and populate the <code>NextToken</code> request parameter with the token value returned from the previous * call to <code>GetTextDetection</code>.</p> */
Gets the text detection results of a Amazon Rekognition Video analysis started by StartTextDetection. Text detection with Amazon Rekognition Video is an asynchronous operation. You start text detection by calling StartTextDetection which returns a job identifier (JobId) When the text detection operation finishes, Amazon Rekognition publishes a completion status to the Amazon Simple Notification Service topic registered in the initial call to StartTextDetection. To get the results of the text detection operation, first check that the status value published to the Amazon SNS topic is SUCCEEDED. if so, call GetTextDetection and pass the job identifier (JobId) from the initial call of StartLabelDetection. GetTextDetection returns an array of detected text (TextDetections) sorted by the time the text was detected, up to 50 words per frame of video. Each element of the array includes the detected text, the precentage confidence in the acuracy of the detected text, the time the text was detected, bounding box information for where the text was located, and unique identifiers for words and their lines. Use MaxResults parameter to limit the number of text detections returned. If there are more results than specified in MaxResults, the value of NextToken in the operation response contains a pagination token for getting the next set of results. To get the next page of results, call GetTextDetection and populate the NextToken request parameter with the token value returned from the previous call to GetTextDetection.
[ "Gets", "the", "text", "detection", "results", "of", "a", "Amazon", "Rekognition", "Video", "analysis", "started", "by", "StartTextDetection", ".", "Text", "detection", "with", "Amazon", "Rekognition", "Video", "is", "an", "asynchronous", "operation", ".", "You", "start", "text", "detection", "by", "calling", "StartTextDetection", "which", "returns", "a", "job", "identifier", "(", "JobId", ")", "When", "the", "text", "detection", "operation", "finishes", "Amazon", "Rekognition", "publishes", "a", "completion", "status", "to", "the", "Amazon", "Simple", "Notification", "Service", "topic", "registered", "in", "the", "initial", "call", "to", "StartTextDetection", ".", "To", "get", "the", "results", "of", "the", "text", "detection", "operation", "first", "check", "that", "the", "status", "value", "published", "to", "the", "Amazon", "SNS", "topic", "is", "SUCCEEDED", ".", "if", "so", "call", "GetTextDetection", "and", "pass", "the", "job", "identifier", "(", "JobId", ")", "from", "the", "initial", "call", "of", "StartLabelDetection", ".", "GetTextDetection", "returns", "an", "array", "of", "detected", "text", "(", "TextDetections", ")", "sorted", "by", "the", "time", "the", "text", "was", "detected", "up", "to", "50", "words", "per", "frame", "of", "video", ".", "Each", "element", "of", "the", "array", "includes", "the", "detected", "text", "the", "precentage", "confidence", "in", "the", "acuracy", "of", "the", "detected", "text", "the", "time", "the", "text", "was", "detected", "bounding", "box", "information", "for", "where", "the", "text", "was", "located", "and", "unique", "identifiers", "for", "words", "and", "their", "lines", ".", "Use", "MaxResults", "parameter", "to", "limit", "the", "number", "of", "text", "detections", "returned", ".", "If", "there", "are", "more", "results", "than", "specified", "in", "MaxResults", "the", "value", "of", "NextToken", "in", "the", "operation", "response", "contains", "a", "pagination", "token", "for", "getting", "the", "next", "set", "of", "results", ".", "To", "get", "the", "next", "page", "of", "results", "call", "GetTextDetection", "and", "populate", "the", "NextToken", "request", "parameter", "with", "the", "token", "value", "returned", "from", "the", "previous", "call", "to", "GetTextDetection", "." ]
class GetTextDetectionCommand extends smithy_client_1.Command { // Start section: command_properties // End section: command_properties constructor(input) { // Start section: command_constructor super(); this.input = input; // End section: command_constructor } /** * @internal */ resolveMiddleware(clientStack, configuration, options) { this.middlewareStack.use(middleware_serde_1.getSerdePlugin(configuration, this.serialize, this.deserialize)); const stack = clientStack.concat(this.middlewareStack); const { logger } = configuration; const clientName = "RekognitionClient"; const commandName = "GetTextDetectionCommand"; const handlerExecutionContext = { logger, clientName, commandName, inputFilterSensitiveLog: models_0_1.GetTextDetectionRequest.filterSensitiveLog, outputFilterSensitiveLog: models_0_1.GetTextDetectionResponse.filterSensitiveLog, }; const { requestHandler } = configuration; return stack.resolve((request) => requestHandler.handle(request.request, options || {}), handlerExecutionContext); } serialize(input, context) { return Aws_json1_1_1.serializeAws_json1_1GetTextDetectionCommand(input, context); } deserialize(output, context) { return Aws_json1_1_1.deserializeAws_json1_1GetTextDetectionCommand(output, context); } }
[ "class", "GetTextDetectionCommand", "extends", "smithy_client_1", ".", "Command", "{", "constructor", "(", "input", ")", "{", "super", "(", ")", ";", "this", ".", "input", "=", "input", ";", "}", "resolveMiddleware", "(", "clientStack", ",", "configuration", ",", "options", ")", "{", "this", ".", "middlewareStack", ".", "use", "(", "middleware_serde_1", ".", "getSerdePlugin", "(", "configuration", ",", "this", ".", "serialize", ",", "this", ".", "deserialize", ")", ")", ";", "const", "stack", "=", "clientStack", ".", "concat", "(", "this", ".", "middlewareStack", ")", ";", "const", "{", "logger", "}", "=", "configuration", ";", "const", "clientName", "=", "\"RekognitionClient\"", ";", "const", "commandName", "=", "\"GetTextDetectionCommand\"", ";", "const", "handlerExecutionContext", "=", "{", "logger", ",", "clientName", ",", "commandName", ",", "inputFilterSensitiveLog", ":", "models_0_1", ".", "GetTextDetectionRequest", ".", "filterSensitiveLog", ",", "outputFilterSensitiveLog", ":", "models_0_1", ".", "GetTextDetectionResponse", ".", "filterSensitiveLog", ",", "}", ";", "const", "{", "requestHandler", "}", "=", "configuration", ";", "return", "stack", ".", "resolve", "(", "(", "request", ")", "=>", "requestHandler", ".", "handle", "(", "request", ".", "request", ",", "options", "||", "{", "}", ")", ",", "handlerExecutionContext", ")", ";", "}", "serialize", "(", "input", ",", "context", ")", "{", "return", "Aws_json1_1_1", ".", "serializeAws_json1_1GetTextDetectionCommand", "(", "input", ",", "context", ")", ";", "}", "deserialize", "(", "output", ",", "context", ")", "{", "return", "Aws_json1_1_1", ".", "deserializeAws_json1_1GetTextDetectionCommand", "(", "output", ",", "context", ")", ";", "}", "}" ]
<p>Gets the text detection results of a Amazon Rekognition Video analysis started by <a>StartTextDetection</a>.</p> <p>Text detection with Amazon Rekognition Video is an asynchronous operation.
[ "<p", ">", "Gets", "the", "text", "detection", "results", "of", "a", "Amazon", "Rekognition", "Video", "analysis", "started", "by", "<a", ">", "StartTextDetection<", "/", "a", ">", ".", "<", "/", "p", ">", "<p", ">", "Text", "detection", "with", "Amazon", "Rekognition", "Video", "is", "an", "asynchronous", "operation", "." ]
[ "// Start section: command_properties", "// End section: command_properties", "// Start section: command_constructor", "// End section: command_constructor", "/**\n * @internal\n */" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
297
446
55d70c5a5061586f57ddd9a83bf9311d0e274daf
ArthurBarelli/isle-editor
app/components/input/proportions/index.js
[ "Apache-2.0" ]
JavaScript
ProportionInput
/** * A proportions input component. Can be used as part of an ISLE dashboard or standalone. In the latter case, you want to handle changes via the `onChange` attribute or bind the value to a global variable via the `bind` attribute. * * @property {number} nElements - number of elements * @property {Array} legends - group labels * @property {boolean} disabled - controls whether the input field is deactivated * @property {number} precision - displayed precision of proportion values * @property {number} step - the step of the arrows seen when hovering the cursor above the input box * @property {Array} colors - array of colors for the pie chart components. If not defined, a custom color scale will be used * @property {number} height - proportions input height (in px) * @property {number} innerRadius - inner radius of proportions pie chart (in px) * @property {number} margin - proportion input margin (in px) * @property {Function} onChange - callback function to be invoked when a choice is made */
A proportions input component. Can be used as part of an ISLE dashboard or standalone. In the latter case, you want to handle changes via the `onChange` attribute or bind the value to a global variable via the `bind` attribute.
[ "A", "proportions", "input", "component", ".", "Can", "be", "used", "as", "part", "of", "an", "ISLE", "dashboard", "or", "standalone", ".", "In", "the", "latter", "case", "you", "want", "to", "handle", "changes", "via", "the", "`", "onChange", "`", "attribute", "or", "bind", "the", "value", "to", "a", "global", "variable", "via", "the", "`", "bind", "`", "attribute", "." ]
class ProportionInput extends Input { constructor( props ) { super( props ); this.legends = this.checkLegends(); let values = null; if ( this.props.values ) { values = this.props.values; } else { values = this.setValues(); } this.state = { values: values, visualData: this.pieData( values ), colors: this.setColors() }; this.checkPercentage.bind( this ); } componentWillReceiveProps( nextProps ) { if ( nextProps.values !== this.props.values ) { this.setState({ values: nextProps.values, visualData: this.pieData( nextProps.values ) }); } if ( nextProps.legends !== this.props.legends ) { this.legends = this.checkLegends(); } } setValues() { var no = this.props.nElements; var values = new Array( no ); var initial = 100 / no; for ( var i = 0; i < no; i++ ) { values[ i ] = initial; } return values; } setColors() { var no = this.props.nElements; var c = this.props.colors.slice( 0, no ); c.push( 'transparent' ); return c; } checkLegends() { const list = []; const no = this.props.nElements; if ( isArray( this.props.legends ) ) { return this.props.legends; } for ( let i = 0; i < no; i++ ) { list.push( 'EL ' + i ); } return list; } checkPercentage( ndx, value ) { const copy = this.state.values.slice(); copy[ ndx ] = value; this.props.onChange( copy ); this.setState({ values: copy, visualData: this.pieData( copy ) }); } getNumber( ndx ) { const style = { float: 'left', width: '120px', textAlign: 'center' }; const free = 100.0 - sum( this.state.values ); let maxValue = this.state.values[ ndx ] + free; maxValue = Number( maxValue.toFixed( this.props.precision ) ); return ( <div style={style} key={ndx} > <NumberInput key={ndx} legend={this.legends[ ndx ]} onChange={( event ) => this.checkPercentage( ndx, event )} min={0} max={maxValue} step={this.props.step} disabled={this.props.disabled} defaultValue={this.state.values[ ndx ]} /> </div> ); } renderInputs() { var list = []; let n = this.props.nElements; for ( var i = 0; i < n; i++ ) { list.push( this.getNumber( i ) ); } return list; } renderPie() { return ( <VictoryPie colorScale={this.state.colors} data={this.state.visualData} height={this.props.height} innerRadius={this.props.innerRadius} /> ); } pieData( arr ) { var list = []; var total = sum( arr ); var no = this.props.nElements + 1; for ( let i = 0; i < no; i++ ) { if ( i < no -1 ) { let o = { x: this.props.legends[ i ], y: arr[ i ] }; list.push( o ); } else { let o = { x: ' ', y: 100 - sum( arr ) }; if ( total !== 100 ) { list.push( o ); } } } return list; } render() { var pos = { marginLeft: this.props.margin }; return ( <div className="input" > { this.renderPie() } <div style={pos}> { this.renderInputs() } </div> </div> ); } }
[ "class", "ProportionInput", "extends", "Input", "{", "constructor", "(", "props", ")", "{", "super", "(", "props", ")", ";", "this", ".", "legends", "=", "this", ".", "checkLegends", "(", ")", ";", "let", "values", "=", "null", ";", "if", "(", "this", ".", "props", ".", "values", ")", "{", "values", "=", "this", ".", "props", ".", "values", ";", "}", "else", "{", "values", "=", "this", ".", "setValues", "(", ")", ";", "}", "this", ".", "state", "=", "{", "values", ":", "values", ",", "visualData", ":", "this", ".", "pieData", "(", "values", ")", ",", "colors", ":", "this", ".", "setColors", "(", ")", "}", ";", "this", ".", "checkPercentage", ".", "bind", "(", "this", ")", ";", "}", "componentWillReceiveProps", "(", "nextProps", ")", "{", "if", "(", "nextProps", ".", "values", "!==", "this", ".", "props", ".", "values", ")", "{", "this", ".", "setState", "(", "{", "values", ":", "nextProps", ".", "values", ",", "visualData", ":", "this", ".", "pieData", "(", "nextProps", ".", "values", ")", "}", ")", ";", "}", "if", "(", "nextProps", ".", "legends", "!==", "this", ".", "props", ".", "legends", ")", "{", "this", ".", "legends", "=", "this", ".", "checkLegends", "(", ")", ";", "}", "}", "setValues", "(", ")", "{", "var", "no", "=", "this", ".", "props", ".", "nElements", ";", "var", "values", "=", "new", "Array", "(", "no", ")", ";", "var", "initial", "=", "100", "/", "no", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "no", ";", "i", "++", ")", "{", "values", "[", "i", "]", "=", "initial", ";", "}", "return", "values", ";", "}", "setColors", "(", ")", "{", "var", "no", "=", "this", ".", "props", ".", "nElements", ";", "var", "c", "=", "this", ".", "props", ".", "colors", ".", "slice", "(", "0", ",", "no", ")", ";", "c", ".", "push", "(", "'transparent'", ")", ";", "return", "c", ";", "}", "checkLegends", "(", ")", "{", "const", "list", "=", "[", "]", ";", "const", "no", "=", "this", ".", "props", ".", "nElements", ";", "if", "(", "isArray", "(", "this", ".", "props", ".", "legends", ")", ")", "{", "return", "this", ".", "props", ".", "legends", ";", "}", "for", "(", "let", "i", "=", "0", ";", "i", "<", "no", ";", "i", "++", ")", "{", "list", ".", "push", "(", "'EL '", "+", "i", ")", ";", "}", "return", "list", ";", "}", "checkPercentage", "(", "ndx", ",", "value", ")", "{", "const", "copy", "=", "this", ".", "state", ".", "values", ".", "slice", "(", ")", ";", "copy", "[", "ndx", "]", "=", "value", ";", "this", ".", "props", ".", "onChange", "(", "copy", ")", ";", "this", ".", "setState", "(", "{", "values", ":", "copy", ",", "visualData", ":", "this", ".", "pieData", "(", "copy", ")", "}", ")", ";", "}", "getNumber", "(", "ndx", ")", "{", "const", "style", "=", "{", "float", ":", "'left'", ",", "width", ":", "'120px'", ",", "textAlign", ":", "'center'", "}", ";", "const", "free", "=", "100.0", "-", "sum", "(", "this", ".", "state", ".", "values", ")", ";", "let", "maxValue", "=", "this", ".", "state", ".", "values", "[", "ndx", "]", "+", "free", ";", "maxValue", "=", "Number", "(", "maxValue", ".", "toFixed", "(", "this", ".", "props", ".", "precision", ")", ")", ";", "return", "(", "<", "div", "style", "=", "{", "style", "}", "key", "=", "{", "ndx", "}", ">", "\n\t\t\t\t", "<", "NumberInput", "key", "=", "{", "ndx", "}", "legend", "=", "{", "this", ".", "legends", "[", "ndx", "]", "}", "onChange", "=", "{", "(", "event", ")", "=>", "this", ".", "checkPercentage", "(", "ndx", ",", "event", ")", "}", "min", "=", "{", "0", "}", "max", "=", "{", "maxValue", "}", "step", "=", "{", "this", ".", "props", ".", "step", "}", "disabled", "=", "{", "this", ".", "props", ".", "disabled", "}", "defaultValue", "=", "{", "this", ".", "state", ".", "values", "[", "ndx", "]", "}", "/", ">", "\n\t\t\t", "<", "/", "div", ">", ")", ";", "}", "renderInputs", "(", ")", "{", "var", "list", "=", "[", "]", ";", "let", "n", "=", "this", ".", "props", ".", "nElements", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "list", ".", "push", "(", "this", ".", "getNumber", "(", "i", ")", ")", ";", "}", "return", "list", ";", "}", "renderPie", "(", ")", "{", "return", "(", "<", "VictoryPie", "colorScale", "=", "{", "this", ".", "state", ".", "colors", "}", "data", "=", "{", "this", ".", "state", ".", "visualData", "}", "height", "=", "{", "this", ".", "props", ".", "height", "}", "innerRadius", "=", "{", "this", ".", "props", ".", "innerRadius", "}", "/", ">", ")", ";", "}", "pieData", "(", "arr", ")", "{", "var", "list", "=", "[", "]", ";", "var", "total", "=", "sum", "(", "arr", ")", ";", "var", "no", "=", "this", ".", "props", ".", "nElements", "+", "1", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "no", ";", "i", "++", ")", "{", "if", "(", "i", "<", "no", "-", "1", ")", "{", "let", "o", "=", "{", "x", ":", "this", ".", "props", ".", "legends", "[", "i", "]", ",", "y", ":", "arr", "[", "i", "]", "}", ";", "list", ".", "push", "(", "o", ")", ";", "}", "else", "{", "let", "o", "=", "{", "x", ":", "' '", ",", "y", ":", "100", "-", "sum", "(", "arr", ")", "}", ";", "if", "(", "total", "!==", "100", ")", "{", "list", ".", "push", "(", "o", ")", ";", "}", "}", "}", "return", "list", ";", "}", "render", "(", ")", "{", "var", "pos", "=", "{", "marginLeft", ":", "this", ".", "props", ".", "margin", "}", ";", "return", "(", "<", "div", "className", "=", "\"input\"", ">", "\n\t\t\t\t", "{", "this", ".", "renderPie", "(", ")", "}", "\n\t\t\t\t", "<", "div", "style", "=", "{", "pos", "}", ">", "\n\t\t\t\t\t", "{", "this", ".", "renderInputs", "(", ")", "}", "\n\t\t\t\t", "<", "/", "div", ">", "\n\t\t\t", "<", "/", "div", ">", ")", ";", "}", "}" ]
A proportions input component.
[ "A", "proportions", "input", "component", "." ]
[]
[ { "param": "Input", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Input", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [ { "identifier": "nElements", "type": null, "docstring": "number of elements", "docstring_tokens": [ "number", "of", "elements" ], "default": null, "is_optional": null }, { "identifier": "legends", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null }, { "identifier": "disabled", "type": null, "docstring": "controls whether the input field is deactivated", "docstring_tokens": [ "controls", "whether", "the", "input", "field", "is", "deactivated" ], "default": null, "is_optional": null }, { "identifier": "precision", "type": null, "docstring": "displayed precision of proportion values", "docstring_tokens": [ "displayed", "precision", "of", "proportion", "values" ], "default": null, "is_optional": null }, { "identifier": "step", "type": null, "docstring": "the step of the arrows seen when hovering the cursor above the input box", "docstring_tokens": [ "the", "step", "of", "the", "arrows", "seen", "when", "hovering", "the", "cursor", "above", "the", "input", "box" ], "default": null, "is_optional": null }, { "identifier": "colors", "type": null, "docstring": "array of colors for the pie chart components. If not defined, a custom color scale will be used", "docstring_tokens": [ "array", "of", "colors", "for", "the", "pie", "chart", "components", ".", "If", "not", "defined", "a", "custom", "color", "scale", "will", "be", "used" ], "default": null, "is_optional": null }, { "identifier": "height", "type": null, "docstring": "proportions input height (in px)", "docstring_tokens": [ "proportions", "input", "height", "(", "in", "px", ")" ], "default": null, "is_optional": null }, { "identifier": "innerRadius", "type": null, "docstring": "inner radius of proportions pie chart (in px)", "docstring_tokens": [ "inner", "radius", "of", "proportions", "pie", "chart", "(", "in", "px", ")" ], "default": null, "is_optional": null }, { "identifier": "margin", "type": null, "docstring": "proportion input margin (in px)", "docstring_tokens": [ "proportion", "input", "margin", "(", "in", "px", ")" ], "default": null, "is_optional": null }, { "identifier": "onChange", "type": null, "docstring": "callback function to be invoked when a choice is made", "docstring_tokens": [ "callback", "function", "to", "be", "invoked", "when", "a", "choice", "is", "made" ], "default": null, "is_optional": null } ], "others": [] }
false
17
952
227
15abf4c5cfaba422f24526cd55d434379b1614e3
simokhov/schemas44
src/main/java/ru/gov/zakupki/oos/types/_1/ZfcsLotI111Type.java
[ "MIT" ]
Java
OKPD2
/** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://zakupki.gov.ru/oos/types/1}zfcs_OKPDRef"> * &lt;sequence> * &lt;element name="characteristics" minOccurs="0"> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="characteristicsUsingTextForm" type="{http://zakupki.gov.ru/oos/types/1}zfcs_tenderPlan2017ManualKtruCharacteristicType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * &lt;element name="addCharacteristics" type="{http://zakupki.gov.ru/oos/types/1}zfcs_longText4000MinType" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */
Java class for anonymous complex type. The following schema fragment specifies the expected content contained within this class.
[ "Java", "class", "for", "anonymous", "complex", "type", ".", "The", "following", "schema", "fragment", "specifies", "the", "expected", "content", "contained", "within", "this", "class", "." ]
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "characteristics", "addCharacteristics" }) public static class OKPD2 extends ZfcsOKPDRef { protected ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics characteristics; protected String addCharacteristics; /** * Gets the value of the characteristics property. * * @return * possible object is * {@link ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics } * */ public ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics getCharacteristics() { return characteristics; } /** * Sets the value of the characteristics property. * * @param value * allowed object is * {@link ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics } * */ public void setCharacteristics(ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics value) { this.characteristics = value; } /** * Gets the value of the addCharacteristics property. * * @return * possible object is * {@link String } * */ public String getAddCharacteristics() { return addCharacteristics; } /** * Sets the value of the addCharacteristics property. * * @param value * allowed object is * {@link String } * */ public void setAddCharacteristics(String value) { this.addCharacteristics = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="characteristicsUsingTextForm" type="{http://zakupki.gov.ru/oos/types/1}zfcs_tenderPlan2017ManualKtruCharacteristicType" maxOccurs="unbounded"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "characteristicsUsingTextForm" }) public static class Characteristics { @XmlElement(required = true) protected List<ZfcsTenderPlan2017ManualKtruCharacteristicType> characteristicsUsingTextForm; /** * Gets the value of the characteristicsUsingTextForm property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the characteristicsUsingTextForm property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCharacteristicsUsingTextForm().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ZfcsTenderPlan2017ManualKtruCharacteristicType } * * */ public List<ZfcsTenderPlan2017ManualKtruCharacteristicType> getCharacteristicsUsingTextForm() { if (characteristicsUsingTextForm == null) { characteristicsUsingTextForm = new ArrayList<ZfcsTenderPlan2017ManualKtruCharacteristicType>(); } return this.characteristicsUsingTextForm; } } }
[ "@", "XmlAccessorType", "(", "XmlAccessType", ".", "FIELD", ")", "@", "XmlType", "(", "name", "=", "\"", "\"", ",", "propOrder", "=", "{", "\"", "characteristics", "\"", ",", "\"", "addCharacteristics", "\"", "}", ")", "public", "static", "class", "OKPD2", "extends", "ZfcsOKPDRef", "{", "protected", "ZfcsLotI111Type", ".", "PurchaseObjects", ".", "PurchaseObject", ".", "OKPD2", ".", "Characteristics", "characteristics", ";", "protected", "String", "addCharacteristics", ";", "/**\n * Gets the value of the characteristics property.\n * \n * @return\n * possible object is\n * {@link ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics }\n * \n */", "public", "ZfcsLotI111Type", ".", "PurchaseObjects", ".", "PurchaseObject", ".", "OKPD2", ".", "Characteristics", "getCharacteristics", "(", ")", "{", "return", "characteristics", ";", "}", "/**\n * Sets the value of the characteristics property.\n * \n * @param value\n * allowed object is\n * {@link ZfcsLotI111Type.PurchaseObjects.PurchaseObject.OKPD2 .Characteristics }\n * \n */", "public", "void", "setCharacteristics", "(", "ZfcsLotI111Type", ".", "PurchaseObjects", ".", "PurchaseObject", ".", "OKPD2", ".", "Characteristics", "value", ")", "{", "this", ".", "characteristics", "=", "value", ";", "}", "/**\n * Gets the value of the addCharacteristics property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */", "public", "String", "getAddCharacteristics", "(", ")", "{", "return", "addCharacteristics", ";", "}", "/**\n * Sets the value of the addCharacteristics property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */", "public", "void", "setAddCharacteristics", "(", "String", "value", ")", "{", "this", ".", "addCharacteristics", "=", "value", ";", "}", "/**\n * <p>Java class for anonymous complex type.\n * \n * <p>The following schema fragment specifies the expected content contained within this class.\n * \n * <pre>\n * &lt;complexType>\n * &lt;complexContent>\n * &lt;restriction base=\"{http://www.w3.org/2001/XMLSchema}anyType\">\n * &lt;sequence>\n * &lt;element name=\"characteristicsUsingTextForm\" type=\"{http://zakupki.gov.ru/oos/types/1}zfcs_tenderPlan2017ManualKtruCharacteristicType\" maxOccurs=\"unbounded\"/>\n * &lt;/sequence>\n * &lt;/restriction>\n * &lt;/complexContent>\n * &lt;/complexType>\n * </pre>\n * \n * \n */", "@", "XmlAccessorType", "(", "XmlAccessType", ".", "FIELD", ")", "@", "XmlType", "(", "name", "=", "\"", "\"", ",", "propOrder", "=", "{", "\"", "characteristicsUsingTextForm", "\"", "}", ")", "public", "static", "class", "Characteristics", "{", "@", "XmlElement", "(", "required", "=", "true", ")", "protected", "List", "<", "ZfcsTenderPlan2017ManualKtruCharacteristicType", ">", "characteristicsUsingTextForm", ";", "/**\n * Gets the value of the characteristicsUsingTextForm property.\n * \n * <p>\n * This accessor method returns a reference to the live list,\n * not a snapshot. Therefore any modification you make to the\n * returned list will be present inside the JAXB object.\n * This is why there is not a <CODE>set</CODE> method for the characteristicsUsingTextForm property.\n * \n * <p>\n * For example, to add a new item, do as follows:\n * <pre>\n * getCharacteristicsUsingTextForm().add(newItem);\n * </pre>\n * \n * \n * <p>\n * Objects of the following type(s) are allowed in the list\n * {@link ZfcsTenderPlan2017ManualKtruCharacteristicType }\n * \n * \n */", "public", "List", "<", "ZfcsTenderPlan2017ManualKtruCharacteristicType", ">", "getCharacteristicsUsingTextForm", "(", ")", "{", "if", "(", "characteristicsUsingTextForm", "==", "null", ")", "{", "characteristicsUsingTextForm", "=", "new", "ArrayList", "<", "ZfcsTenderPlan2017ManualKtruCharacteristicType", ">", "(", ")", ";", "}", "return", "this", ".", "characteristicsUsingTextForm", ";", "}", "}", "}" ]
<p>Java class for anonymous complex type.
[ "<p", ">", "Java", "class", "for", "anonymous", "complex", "type", "." ]
[]
[ { "param": "ZfcsOKPDRef", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ZfcsOKPDRef", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
916
335
600d9b12e00b5433c04cc683fa2b102d1e4ce2f7
Kynake/com.unity.netcode.gameobjects
com.unity.netcode.gameobjects/Tests/Runtime/NetworkPrefabHandlerTests.cs
[ "MIT" ]
C#
NetworkPrefabHandlerTests
/// <summary> /// The NetworkPrefabHandler unit tests validates: /// Registering with GameObject, NetworkObject, or GlobalObjectIdHash /// Newly assigned rotation or position values for newly spawned NetworkObject instances are valid /// Destroying a newly spawned NetworkObject instance works /// Removing a INetworkPrefabInstanceHandler is removed and can be verified (very last check) /// </summary>
The NetworkPrefabHandler unit tests validates: Registering with GameObject, NetworkObject, or GlobalObjectIdHash Newly assigned rotation or position values for newly spawned NetworkObject instances are valid Destroying a newly spawned NetworkObject instance works Removing a INetworkPrefabInstanceHandler is removed and can be verified (very last check)
[ "The", "NetworkPrefabHandler", "unit", "tests", "validates", ":", "Registering", "with", "GameObject", "NetworkObject", "or", "GlobalObjectIdHash", "Newly", "assigned", "rotation", "or", "position", "values", "for", "newly", "spawned", "NetworkObject", "instances", "are", "valid", "Destroying", "a", "newly", "spawned", "NetworkObject", "instance", "works", "Removing", "a", "INetworkPrefabInstanceHandler", "is", "removed", "and", "can", "be", "verified", "(", "very", "last", "check", ")" ]
public class NetworkPrefabHandlerTests { private const string k_TestPrefabObjectName = "NetworkPrefabTestObject"; private uint m_ObjectId = 1; private GameObject MakeValidNetworkPrefab() { Guid baseObjectID = NetworkManagerHelper.AddGameNetworkObject(k_TestPrefabObjectName + m_ObjectId.ToString()); NetworkObject validPrefab = NetworkManagerHelper.InstantiatedNetworkObjects[baseObjectID]; NetcodeIntegrationTestHelpers.MakeNetworkObjectTestPrefab(validPrefab); m_ObjectId++; return validPrefab.gameObject; } [Test] public void NetworkConfigInvalidNetworkPrefabTest() { NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(null); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab()); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Hash, SourceHashToOverride = 0 }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Hash, SourceHashToOverride = 654321, OverridingTargetPrefab = null }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Prefab, SourceHashToOverride = 654321, OverridingTargetPrefab = null }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Prefab, SourcePrefabToOverride = null }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Prefab, SourcePrefabToOverride = MakeValidNetworkPrefab(), OverridingTargetPrefab = null }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Prefab = MakeValidNetworkPrefab() }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Hash, SourceHashToOverride = 11111111, OverridingTargetPrefab = MakeValidNetworkPrefab() }); NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabs.Add(new NetworkPrefab() { Override = NetworkPrefabOverride.Prefab, SourcePrefabToOverride = MakeValidNetworkPrefab(), OverridingTargetPrefab = MakeValidNetworkPrefab() }); var exceptionOccurred = false; try { NetworkManagerHelper.NetworkManagerObject.StartHost(); } catch { exceptionOccurred = true; } Assert.False(exceptionOccurred); Assert.True(NetworkManagerHelper.NetworkManagerObject.NetworkConfig.NetworkPrefabOverrideLinks.Count == 3); } private const string k_PrefabObjectName = "NetworkPrefabHandlerTestObject"; [Test] public void NetworkPrefabHandlerClass() { Assert.IsTrue(NetworkManagerHelper.StartNetworkManager(out _)); var testPrefabObjectName = k_PrefabObjectName; Guid baseObjectID = NetworkManagerHelper.AddGameNetworkObject(testPrefabObjectName); NetworkObject baseObject = NetworkManagerHelper.InstantiatedNetworkObjects[baseObjectID]; var networkPrefabHandler = new NetworkPrefabHandler(); var networkPrefaInstanceHandler = new NetworkPrefaInstanceHandler(baseObject); var prefabPosition = new Vector3(1.0f, 5.0f, 3.0f); var prefabRotation = new Quaternion(1.0f, 0.5f, 0.4f, 0.1f); var gameObjectRegistered = networkPrefabHandler.AddHandler(baseObject.gameObject, networkPrefaInstanceHandler); Assert.True(gameObjectRegistered); var spawnedObject = networkPrefabHandler.HandleNetworkPrefabSpawn(baseObject.GlobalObjectIdHash, 0, prefabPosition, prefabRotation); Assert.NotNull(spawnedObject); Assert.True(spawnedObject.name.Contains(testPrefabObjectName)); Assert.True(prefabPosition == spawnedObject.transform.position); Assert.True(prefabRotation == spawnedObject.transform.rotation); networkPrefabHandler.HandleNetworkPrefabDestroy(spawnedObject); networkPrefabHandler.RemoveHandler(baseObject); gameObjectRegistered = networkPrefabHandler.AddHandler(baseObject, networkPrefaInstanceHandler); Assert.True(gameObjectRegistered); prefabPosition = new Vector3(2.0f, 1.0f, 5.0f); prefabRotation = new Quaternion(4.0f, 1.5f, 5.4f, 5.1f); spawnedObject = networkPrefabHandler.HandleNetworkPrefabSpawn(baseObject.GlobalObjectIdHash, 0, prefabPosition, prefabRotation); Assert.NotNull(spawnedObject); Assert.True(spawnedObject.name.Contains(testPrefabObjectName)); Assert.True(prefabPosition == spawnedObject.transform.position); Assert.True(prefabRotation == spawnedObject.transform.rotation); networkPrefabHandler.HandleNetworkPrefabDestroy(spawnedObject); networkPrefabHandler.RemoveHandler(baseObject); gameObjectRegistered = networkPrefabHandler.AddHandler(baseObject.GlobalObjectIdHash, networkPrefaInstanceHandler); Assert.True(gameObjectRegistered); prefabPosition = new Vector3(6.0f, 4.0f, 1.0f); prefabRotation = new Quaternion(3f, 2f, 4f, 1f); spawnedObject = networkPrefabHandler.HandleNetworkPrefabSpawn(baseObject.GlobalObjectIdHash, 0, prefabPosition, prefabRotation); Assert.NotNull(spawnedObject); Assert.True(spawnedObject.name.Contains(testPrefabObjectName)); Assert.True(prefabPosition == spawnedObject.transform.position); Assert.True(prefabRotation == spawnedObject.transform.rotation); networkPrefabHandler.HandleNetworkPrefabDestroy(spawnedObject); networkPrefabHandler.RemoveHandler(baseObject); Assert.False(networkPrefaInstanceHandler.StillHasInstances()); } [SetUp] public void Setup() { NetworkManagerHelper.StartNetworkManager(out _, NetworkManagerHelper.NetworkManagerOperatingMode.None); } [TearDown] public void TearDown() { NetworkManagerHelper.ShutdownNetworkManager(); var networkObjects = UnityEngine.Object.FindObjectsOfType<NetworkObject>().ToList(); var networkObjectsList = networkObjects.Where(c => c.name.Contains(k_PrefabObjectName)); foreach (var networkObject in networkObjectsList) { UnityEngine.Object.DestroyImmediate(networkObject); } } }
[ "public", "class", "NetworkPrefabHandlerTests", "{", "private", "const", "string", "k_TestPrefabObjectName", "=", "\"", "NetworkPrefabTestObject", "\"", ";", "private", "uint", "m_ObjectId", "=", "1", ";", "private", "GameObject", "MakeValidNetworkPrefab", "(", ")", "{", "Guid", "baseObjectID", "=", "NetworkManagerHelper", ".", "AddGameNetworkObject", "(", "k_TestPrefabObjectName", "+", "m_ObjectId", ".", "ToString", "(", ")", ")", ";", "NetworkObject", "validPrefab", "=", "NetworkManagerHelper", ".", "InstantiatedNetworkObjects", "[", "baseObjectID", "]", ";", "NetcodeIntegrationTestHelpers", ".", "MakeNetworkObjectTestPrefab", "(", "validPrefab", ")", ";", "m_ObjectId", "++", ";", "return", "validPrefab", ".", "gameObject", ";", "}", "[", "Test", "]", "public", "void", "NetworkConfigInvalidNetworkPrefabTest", "(", ")", "{", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "null", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Hash", ",", "SourceHashToOverride", "=", "0", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Hash", ",", "SourceHashToOverride", "=", "654321", ",", "OverridingTargetPrefab", "=", "null", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Prefab", ",", "SourceHashToOverride", "=", "654321", ",", "OverridingTargetPrefab", "=", "null", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Prefab", ",", "SourcePrefabToOverride", "=", "null", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Prefab", ",", "SourcePrefabToOverride", "=", "MakeValidNetworkPrefab", "(", ")", ",", "OverridingTargetPrefab", "=", "null", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Prefab", "=", "MakeValidNetworkPrefab", "(", ")", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Hash", ",", "SourceHashToOverride", "=", "11111111", ",", "OverridingTargetPrefab", "=", "MakeValidNetworkPrefab", "(", ")", "}", ")", ";", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabs", ".", "Add", "(", "new", "NetworkPrefab", "(", ")", "{", "Override", "=", "NetworkPrefabOverride", ".", "Prefab", ",", "SourcePrefabToOverride", "=", "MakeValidNetworkPrefab", "(", ")", ",", "OverridingTargetPrefab", "=", "MakeValidNetworkPrefab", "(", ")", "}", ")", ";", "var", "exceptionOccurred", "=", "false", ";", "try", "{", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "StartHost", "(", ")", ";", "}", "catch", "{", "exceptionOccurred", "=", "true", ";", "}", "Assert", ".", "False", "(", "exceptionOccurred", ")", ";", "Assert", ".", "True", "(", "NetworkManagerHelper", ".", "NetworkManagerObject", ".", "NetworkConfig", ".", "NetworkPrefabOverrideLinks", ".", "Count", "==", "3", ")", ";", "}", "private", "const", "string", "k_PrefabObjectName", "=", "\"", "NetworkPrefabHandlerTestObject", "\"", ";", "[", "Test", "]", "public", "void", "NetworkPrefabHandlerClass", "(", ")", "{", "Assert", ".", "IsTrue", "(", "NetworkManagerHelper", ".", "StartNetworkManager", "(", "out", "_", ")", ")", ";", "var", "testPrefabObjectName", "=", "k_PrefabObjectName", ";", "Guid", "baseObjectID", "=", "NetworkManagerHelper", ".", "AddGameNetworkObject", "(", "testPrefabObjectName", ")", ";", "NetworkObject", "baseObject", "=", "NetworkManagerHelper", ".", "InstantiatedNetworkObjects", "[", "baseObjectID", "]", ";", "var", "networkPrefabHandler", "=", "new", "NetworkPrefabHandler", "(", ")", ";", "var", "networkPrefaInstanceHandler", "=", "new", "NetworkPrefaInstanceHandler", "(", "baseObject", ")", ";", "var", "prefabPosition", "=", "new", "Vector3", "(", "1.0f", ",", "5.0f", ",", "3.0f", ")", ";", "var", "prefabRotation", "=", "new", "Quaternion", "(", "1.0f", ",", "0.5f", ",", "0.4f", ",", "0.1f", ")", ";", "var", "gameObjectRegistered", "=", "networkPrefabHandler", ".", "AddHandler", "(", "baseObject", ".", "gameObject", ",", "networkPrefaInstanceHandler", ")", ";", "Assert", ".", "True", "(", "gameObjectRegistered", ")", ";", "var", "spawnedObject", "=", "networkPrefabHandler", ".", "HandleNetworkPrefabSpawn", "(", "baseObject", ".", "GlobalObjectIdHash", ",", "0", ",", "prefabPosition", ",", "prefabRotation", ")", ";", "Assert", ".", "NotNull", "(", "spawnedObject", ")", ";", "Assert", ".", "True", "(", "spawnedObject", ".", "name", ".", "Contains", "(", "testPrefabObjectName", ")", ")", ";", "Assert", ".", "True", "(", "prefabPosition", "==", "spawnedObject", ".", "transform", ".", "position", ")", ";", "Assert", ".", "True", "(", "prefabRotation", "==", "spawnedObject", ".", "transform", ".", "rotation", ")", ";", "networkPrefabHandler", ".", "HandleNetworkPrefabDestroy", "(", "spawnedObject", ")", ";", "networkPrefabHandler", ".", "RemoveHandler", "(", "baseObject", ")", ";", "gameObjectRegistered", "=", "networkPrefabHandler", ".", "AddHandler", "(", "baseObject", ",", "networkPrefaInstanceHandler", ")", ";", "Assert", ".", "True", "(", "gameObjectRegistered", ")", ";", "prefabPosition", "=", "new", "Vector3", "(", "2.0f", ",", "1.0f", ",", "5.0f", ")", ";", "prefabRotation", "=", "new", "Quaternion", "(", "4.0f", ",", "1.5f", ",", "5.4f", ",", "5.1f", ")", ";", "spawnedObject", "=", "networkPrefabHandler", ".", "HandleNetworkPrefabSpawn", "(", "baseObject", ".", "GlobalObjectIdHash", ",", "0", ",", "prefabPosition", ",", "prefabRotation", ")", ";", "Assert", ".", "NotNull", "(", "spawnedObject", ")", ";", "Assert", ".", "True", "(", "spawnedObject", ".", "name", ".", "Contains", "(", "testPrefabObjectName", ")", ")", ";", "Assert", ".", "True", "(", "prefabPosition", "==", "spawnedObject", ".", "transform", ".", "position", ")", ";", "Assert", ".", "True", "(", "prefabRotation", "==", "spawnedObject", ".", "transform", ".", "rotation", ")", ";", "networkPrefabHandler", ".", "HandleNetworkPrefabDestroy", "(", "spawnedObject", ")", ";", "networkPrefabHandler", ".", "RemoveHandler", "(", "baseObject", ")", ";", "gameObjectRegistered", "=", "networkPrefabHandler", ".", "AddHandler", "(", "baseObject", ".", "GlobalObjectIdHash", ",", "networkPrefaInstanceHandler", ")", ";", "Assert", ".", "True", "(", "gameObjectRegistered", ")", ";", "prefabPosition", "=", "new", "Vector3", "(", "6.0f", ",", "4.0f", ",", "1.0f", ")", ";", "prefabRotation", "=", "new", "Quaternion", "(", "3f", ",", "2f", ",", "4f", ",", "1f", ")", ";", "spawnedObject", "=", "networkPrefabHandler", ".", "HandleNetworkPrefabSpawn", "(", "baseObject", ".", "GlobalObjectIdHash", ",", "0", ",", "prefabPosition", ",", "prefabRotation", ")", ";", "Assert", ".", "NotNull", "(", "spawnedObject", ")", ";", "Assert", ".", "True", "(", "spawnedObject", ".", "name", ".", "Contains", "(", "testPrefabObjectName", ")", ")", ";", "Assert", ".", "True", "(", "prefabPosition", "==", "spawnedObject", ".", "transform", ".", "position", ")", ";", "Assert", ".", "True", "(", "prefabRotation", "==", "spawnedObject", ".", "transform", ".", "rotation", ")", ";", "networkPrefabHandler", ".", "HandleNetworkPrefabDestroy", "(", "spawnedObject", ")", ";", "networkPrefabHandler", ".", "RemoveHandler", "(", "baseObject", ")", ";", "Assert", ".", "False", "(", "networkPrefaInstanceHandler", ".", "StillHasInstances", "(", ")", ")", ";", "}", "[", "SetUp", "]", "public", "void", "Setup", "(", ")", "{", "NetworkManagerHelper", ".", "StartNetworkManager", "(", "out", "_", ",", "NetworkManagerHelper", ".", "NetworkManagerOperatingMode", ".", "None", ")", ";", "}", "[", "TearDown", "]", "public", "void", "TearDown", "(", ")", "{", "NetworkManagerHelper", ".", "ShutdownNetworkManager", "(", ")", ";", "var", "networkObjects", "=", "UnityEngine", ".", "Object", ".", "FindObjectsOfType", "<", "NetworkObject", ">", "(", ")", ".", "ToList", "(", ")", ";", "var", "networkObjectsList", "=", "networkObjects", ".", "Where", "(", "c", "=>", "c", ".", "name", ".", "Contains", "(", "k_PrefabObjectName", ")", ")", ";", "foreach", "(", "var", "networkObject", "in", "networkObjectsList", ")", "{", "UnityEngine", ".", "Object", ".", "DestroyImmediate", "(", "networkObject", ")", ";", "}", "}", "}" ]
The NetworkPrefabHandler unit tests validates: Registering with GameObject, NetworkObject, or GlobalObjectIdHash Newly assigned rotation or position values for newly spawned NetworkObject instances are valid Destroying a newly spawned NetworkObject instance works Removing a INetworkPrefabInstanceHandler is removed and can be verified (very last check)
[ "The", "NetworkPrefabHandler", "unit", "tests", "validates", ":", "Registering", "with", "GameObject", "NetworkObject", "or", "GlobalObjectIdHash", "Newly", "assigned", "rotation", "or", "position", "values", "for", "newly", "spawned", "NetworkObject", "instances", "are", "valid", "Destroying", "a", "newly", "spawned", "NetworkObject", "instance", "works", "Removing", "a", "INetworkPrefabInstanceHandler", "is", "removed", "and", "can", "be", "verified", "(", "very", "last", "check", ")" ]
[ "/// <summary>", "/// Tests the NetwokConfig NetworkPrefabs initialization during NetworkManager's Init method to make sure that", "/// it will still initialize but remove the invalid prefabs", "/// </summary>", "// Add null entry", "// Add a NetworkPrefab with no prefab", "// Add a NetworkPrefab override with an invalid hash", "// Add a NetworkPrefab override with a valid hash but an invalid target prefab", "// Add a NetworkPrefab override with a valid hash to override but an invalid target prefab", "// Add a NetworkPrefab override with an invalid source prefab to override", "// Add a NetworkPrefab override with a valid source prefab to override but an invalid target prefab", "// Add a valid prefab", "// Add a NetworkPrefab override with a valid hash and valid target prefab", "// Add a NetworkPrefab override with a valid prefab and valid target prefab", "// In the end we should only have 3 valid registered network prefabs", "//Register via GameObject", "//Test result of registering via GameObject reference", "//Test that something was instantiated", "//Test that this is indeed an instance of our original object", "//Test for position and rotation", "//Destroy our prefab instance", "//Remove our handler", "//Register via NetworkObject", "//Test result of registering via NetworkObject reference", "//Change it up", "//Test that something was instantiated", "//Test that this is indeed an instance of our original object", "//Test for position and rotation", "//Destroy our prefab instance", "//Remove our handler", "//Register via GlobalObjectIdHash", "//Test result of registering via GlobalObjectIdHash reference", "//Change it up", "//Test that something was instantiated", "//Test that this is indeed an instance of our original object", "//Test for position and rotation", "//Destroy our prefab instance", "//Remove our handler", "//Create, instantiate, and host", "//Stop, shutdown, and destroy" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
1,328
77
36407fbf715a83315d3e823ffbd0ffd643bf5103
Azureyjt/java-design-patterns
eip-wire-tap/src/main/java/com/iluwatar/eip/wiretap/App.java
[ "MIT" ]
Java
App
/** * In most integration cases there is a need to monitor the messages flowing through the system. It * is usually achieved by intercepting the message and redirecting it to a different location like * console, filesystem or the database. It is important that such functionality should not modify * the original message and influence the processing path. * * <p> * Wire Tap allows you to route messages to a separate location while they are being forwarded to * the ultimate destination. It basically consumes messages of the input channel and publishes the * unmodified message to both output channels. * </p> */
In most integration cases there is a need to monitor the messages flowing through the system. It is usually achieved by intercepting the message and redirecting it to a different location like console, filesystem or the database. It is important that such functionality should not modify the original message and influence the processing path. Wire Tap allows you to route messages to a separate location while they are being forwarded to the ultimate destination. It basically consumes messages of the input channel and publishes the unmodified message to both output channels.
[ "In", "most", "integration", "cases", "there", "is", "a", "need", "to", "monitor", "the", "messages", "flowing", "through", "the", "system", ".", "It", "is", "usually", "achieved", "by", "intercepting", "the", "message", "and", "redirecting", "it", "to", "a", "different", "location", "like", "console", "filesystem", "or", "the", "database", ".", "It", "is", "important", "that", "such", "functionality", "should", "not", "modify", "the", "original", "message", "and", "influence", "the", "processing", "path", ".", "Wire", "Tap", "allows", "you", "to", "route", "messages", "to", "a", "separate", "location", "while", "they", "are", "being", "forwarded", "to", "the", "ultimate", "destination", ".", "It", "basically", "consumes", "messages", "of", "the", "input", "channel", "and", "publishes", "the", "unmodified", "message", "to", "both", "output", "channels", "." ]
@SpringBootApplication public class App { /** * Program entry point. It starts Spring Boot application and using Apache Camel it * auto-configures routes. * * @param args command line args */ public static void main(String[] args) throws Exception { // Run Spring Boot application and obtain ApplicationContext ConfigurableApplicationContext context = SpringApplication.run(App.class, args); // Get CamelContext from ApplicationContext CamelContext camelContext = (CamelContext) context.getBean("camelContext"); // Add a new routes that will handle endpoints form WireTapRoute class. camelContext.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("{{endpoint}}").log("ENDPOINT: ${body}"); from("{{wireTapEndpoint}}").log("WIRETAPPED ENDPOINT: ${body}"); } }); // Add producer that will send test message to an entry point in WireTapRoute camelContext.createProducerTemplate().sendBody("{{entry}}", "Test message"); SpringApplication.exit(context); } }
[ "@", "SpringBootApplication", "public", "class", "App", "{", "/**\n * Program entry point. It starts Spring Boot application and using Apache Camel it\n * auto-configures routes.\n *\n * @param args command line args\n */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "throws", "Exception", "{", "ConfigurableApplicationContext", "context", "=", "SpringApplication", ".", "run", "(", "App", ".", "class", ",", "args", ")", ";", "CamelContext", "camelContext", "=", "(", "CamelContext", ")", "context", ".", "getBean", "(", "\"", "camelContext", "\"", ")", ";", "camelContext", ".", "addRoutes", "(", "new", "RouteBuilder", "(", ")", "{", "@", "Override", "public", "void", "configure", "(", ")", "throws", "Exception", "{", "from", "(", "\"", "{{endpoint}}", "\"", ")", ".", "log", "(", "\"", "ENDPOINT: ${body}", "\"", ")", ";", "from", "(", "\"", "{{wireTapEndpoint}}", "\"", ")", ".", "log", "(", "\"", "WIRETAPPED ENDPOINT: ${body}", "\"", ")", ";", "}", "}", ")", ";", "camelContext", ".", "createProducerTemplate", "(", ")", ".", "sendBody", "(", "\"", "{{entry}}", "\"", ",", "\"", "Test message", "\"", ")", ";", "SpringApplication", ".", "exit", "(", "context", ")", ";", "}", "}" ]
In most integration cases there is a need to monitor the messages flowing through the system.
[ "In", "most", "integration", "cases", "there", "is", "a", "need", "to", "monitor", "the", "messages", "flowing", "through", "the", "system", "." ]
[ "// Run Spring Boot application and obtain ApplicationContext", "// Get CamelContext from ApplicationContext", "// Add a new routes that will handle endpoints form WireTapRoute class.", "// Add producer that will send test message to an entry point in WireTapRoute" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
227
123
b65c64dac01359c0de51b14a39f5ef25b672d71b
kemcbride/Neolib
neolib/quests/KitchenQuest.py
[ "MIT" ]
Python
KitchenQuest
Provides an interface for accepting and completing Kitchen Quests Provides functionality for initiating and completing quests given by the Mystery Island Kitchen. Each part is broken down into accepting a quest, determining it's total worth, buying the necessary items, and finally completing the quest. Attributes usr (User) -- Associated user recipe (str) -- Name of the current recipe time (tuple) -- Number of hours and minutes left on the quest items (list) -- List of quest items npSpent (int) -- Total NPs spent on the quest prize (str) -- Prize awarded by completing the quest Initialization KitchenQuest(usr) Loads the existing quest, otherwise attempts to accept a new quest. Loads the kitchen quest page and checks for an active quest. If an active quest is found it will load the quest details and compare the quest items to the user's inventory. If any item matching the quest item name is found in the inventory, it will automatically remove the item from the list of quest items. If no active quest is found, will attempt to accept a new quest and load the quest details. Parameters url (str) -- Remote URL address of the page Example >>> q = KitchenQuest(usr) >>> q.getPrice(2) True >>> q.npSpent 5100 >>> q.buyQuestItems() True >>> q.submitQuest() True >>> q.prize 'blah has gained a level!'
Provides an interface for accepting and completing Kitchen Quests Provides functionality for initiating and completing quests given by the Mystery Island Kitchen. Each part is broken down into accepting a quest, determining it's total worth, buying the necessary items, and finally completing the quest. Loads the existing quest, otherwise attempts to accept a new quest. Loads the kitchen quest page and checks for an active quest. If an active quest is found it will load the quest details and compare the quest items to the user's inventory. If any item matching the quest item name is found in the inventory, it will automatically remove the item from the list of quest items. If no active quest is found, will attempt to accept a new quest and load the quest details. Parameters url (str) -- Remote URL address of the page
[ "Provides", "an", "interface", "for", "accepting", "and", "completing", "Kitchen", "Quests", "Provides", "functionality", "for", "initiating", "and", "completing", "quests", "given", "by", "the", "Mystery", "Island", "Kitchen", ".", "Each", "part", "is", "broken", "down", "into", "accepting", "a", "quest", "determining", "it", "'", "s", "total", "worth", "buying", "the", "necessary", "items", "and", "finally", "completing", "the", "quest", ".", "Loads", "the", "existing", "quest", "otherwise", "attempts", "to", "accept", "a", "new", "quest", ".", "Loads", "the", "kitchen", "quest", "page", "and", "checks", "for", "an", "active", "quest", ".", "If", "an", "active", "quest", "is", "found", "it", "will", "load", "the", "quest", "details", "and", "compare", "the", "quest", "items", "to", "the", "user", "'", "s", "inventory", ".", "If", "any", "item", "matching", "the", "quest", "item", "name", "is", "found", "in", "the", "inventory", "it", "will", "automatically", "remove", "the", "item", "from", "the", "list", "of", "quest", "items", ".", "If", "no", "active", "quest", "is", "found", "will", "attempt", "to", "accept", "a", "new", "quest", "and", "load", "the", "quest", "details", ".", "Parameters", "url", "(", "str", ")", "--", "Remote", "URL", "address", "of", "the", "page" ]
class KitchenQuest: """Provides an interface for accepting and completing Kitchen Quests Provides functionality for initiating and completing quests given by the Mystery Island Kitchen. Each part is broken down into accepting a quest, determining it's total worth, buying the necessary items, and finally completing the quest. Attributes usr (User) -- Associated user recipe (str) -- Name of the current recipe time (tuple) -- Number of hours and minutes left on the quest items (list) -- List of quest items npSpent (int) -- Total NPs spent on the quest prize (str) -- Prize awarded by completing the quest Initialization KitchenQuest(usr) Loads the existing quest, otherwise attempts to accept a new quest. Loads the kitchen quest page and checks for an active quest. If an active quest is found it will load the quest details and compare the quest items to the user's inventory. If any item matching the quest item name is found in the inventory, it will automatically remove the item from the list of quest items. If no active quest is found, will attempt to accept a new quest and load the quest details. Parameters url (str) -- Remote URL address of the page Example >>> q = KitchenQuest(usr) >>> q.getPrice(2) True >>> q.npSpent 5100 >>> q.buyQuestItems() True >>> q.submitQuest() True >>> q.prize 'blah has gained a level!' """ usr = None recipe = "" time = None items = None npSpent = 0 prize = "" failedItem = "" def __init__(self, usr): if not usr: raise invalidUser self.usr = usr pg = usr.getPage("http://www.neopets.com/island/kitchen.phtml") if "Sorry, too late" in pg.content: pg = usr.getPage("http://www.neopets.com/island/kitchen.phtml") if "there is a limit of" in pg.content: raise questLimitException if "still need some ingredients from you" in pg.content: self._parseActiveQuest(pg) usr.loadInventory() for item in self.items: if item.name in usr.inventory: del(self.items[self.items.index(item)]) return try: self.recipe = pg.find("td", "content").find("input", {'name': 'food_desc'})['value'] except Exception: logging.getLogger("neolib.quest").exception("Failed to parse quest recipe", {'pg': pg}) raise parseException form = pg.form(action="kitchen2.phtml") pg = form.submit() try: hour = pg.find("td", "content").find_all("b")[2].text min = pg.find("td", "content").find_all("b")[3].text self.time = (hour, min) self.items = [] for item in pg.find("td", "content").table.find_all("td"): tmpItem = Item(item.b.text) tmpItem.img = item.img['src'] self.items.append(tmpItem) except Exception: logging.getLogger("neolib.quest").exception("Failed to parse quest details", {'pg': pg}) raise parseException def updateQuest(self): """ Updates the active quest details by reloading the quest page """ pg = self.usr.getPage("http://www.neopets.com/island/kitchen.phtml") self._parseActiveQuest(pg) def getPrice(self, searches): """ Prices all quest items and returns result Searches the shop wizard x times (x being number given in searches) for each quest item and finds the lowest price for each item. Combines all item prices and sets KitchenQuest.npSpent to the final value. Returns whether or not this process was successful. Parameters: searches (int) -- The number of times to search the Shop Wizard for each quest item Returns bool - True if successful, otherwise False """ totalPrice = 0 for item in self.items: res = ShopWizard.priceItem(self.usr, item.name, searches, ShopWizard.RETLOW) if not res: self.failedItem = item.name return False item.price, item.owner, item.id = res totalPrice += item.price self.npSpent = totalPrice return True def buyQuestItems(self): """ Attempts to buy all quest items, returns result Returns bool - True if successful, otherwise False """ for item in self.items: us = UserShopFront(self.usr, item.owner, item.id, str(item.price)) us.loadInventory() if not item.name in us.inventory: return False if not us.inventory[item.name].buy(): return False return True def submitQuest(self): """ Submits the active quest, returns result Returns bool - True if successful, otherwise False """ form = pg.form(action="kitchen2.phtml") pg = form.submit() if "Woohoo" in pg.content: try: self.prize = pg.find(text = "The Chef waves his hands, and you may collect your prize...").parent.parent.find_all("b")[-1].text except Exception: logging.getLogger("neolib.quest").exception("Failed to parse kitchen quest prize", {'pg': pg}) raise parseException return True else: logging.getLogger("neolib.quest").info("Failed to complete kitchen quest", {'pg': pg}) return False def _parseActiveQuest(self, pg): try: dets = pg.find("td", "content").table.find_all("td") self.recipe = dets[1].text hour = dets[3].find_all("b")[1].text min = dets[3].find_all("b")[2].text self.time = (hour, min) imgs = pg.find("td", "content").table.find_all("td")[5].find_all("img") items = pg.find("td", "content").table.find_all("td")[5].find_all("b") self.items = [] for i in range(len(items)): tmpItem = Item(items[i].text) tmpItem.img = imgs[i]['src'] self.items.append(tmpItem) except Exception: logging.getLogger("neolib.quest").exception("Failed to parse quest details", {'pg': pg}) raise parseException
[ "class", "KitchenQuest", ":", "usr", "=", "None", "recipe", "=", "\"\"", "time", "=", "None", "items", "=", "None", "npSpent", "=", "0", "prize", "=", "\"\"", "failedItem", "=", "\"\"", "def", "__init__", "(", "self", ",", "usr", ")", ":", "if", "not", "usr", ":", "raise", "invalidUser", "self", ".", "usr", "=", "usr", "pg", "=", "usr", ".", "getPage", "(", "\"http://www.neopets.com/island/kitchen.phtml\"", ")", "if", "\"Sorry, too late\"", "in", "pg", ".", "content", ":", "pg", "=", "usr", ".", "getPage", "(", "\"http://www.neopets.com/island/kitchen.phtml\"", ")", "if", "\"there is a limit of\"", "in", "pg", ".", "content", ":", "raise", "questLimitException", "if", "\"still need some ingredients from you\"", "in", "pg", ".", "content", ":", "self", ".", "_parseActiveQuest", "(", "pg", ")", "usr", ".", "loadInventory", "(", ")", "for", "item", "in", "self", ".", "items", ":", "if", "item", ".", "name", "in", "usr", ".", "inventory", ":", "del", "(", "self", ".", "items", "[", "self", ".", "items", ".", "index", "(", "item", ")", "]", ")", "return", "try", ":", "self", ".", "recipe", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "find", "(", "\"input\"", ",", "{", "'name'", ":", "'food_desc'", "}", ")", "[", "'value'", "]", "except", "Exception", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "exception", "(", "\"Failed to parse quest recipe\"", ",", "{", "'pg'", ":", "pg", "}", ")", "raise", "parseException", "form", "=", "pg", ".", "form", "(", "action", "=", "\"kitchen2.phtml\"", ")", "pg", "=", "form", ".", "submit", "(", ")", "try", ":", "hour", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "find_all", "(", "\"b\"", ")", "[", "2", "]", ".", "text", "min", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "find_all", "(", "\"b\"", ")", "[", "3", "]", ".", "text", "self", ".", "time", "=", "(", "hour", ",", "min", ")", "self", ".", "items", "=", "[", "]", "for", "item", "in", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "table", ".", "find_all", "(", "\"td\"", ")", ":", "tmpItem", "=", "Item", "(", "item", ".", "b", ".", "text", ")", "tmpItem", ".", "img", "=", "item", ".", "img", "[", "'src'", "]", "self", ".", "items", ".", "append", "(", "tmpItem", ")", "except", "Exception", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "exception", "(", "\"Failed to parse quest details\"", ",", "{", "'pg'", ":", "pg", "}", ")", "raise", "parseException", "def", "updateQuest", "(", "self", ")", ":", "\"\"\" Updates the active quest details by reloading the quest page\n \"\"\"", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/island/kitchen.phtml\"", ")", "self", ".", "_parseActiveQuest", "(", "pg", ")", "def", "getPrice", "(", "self", ",", "searches", ")", ":", "\"\"\" Prices all quest items and returns result\n \n Searches the shop wizard x times (x being number given in searches) for each\n quest item and finds the lowest price for each item. Combines all item prices\n and sets KitchenQuest.npSpent to the final value. Returns whether or not this\n process was successful. \n \n Parameters:\n searches (int) -- The number of times to search the Shop Wizard for each quest item\n \n Returns\n bool - True if successful, otherwise False\n \"\"\"", "totalPrice", "=", "0", "for", "item", "in", "self", ".", "items", ":", "res", "=", "ShopWizard", ".", "priceItem", "(", "self", ".", "usr", ",", "item", ".", "name", ",", "searches", ",", "ShopWizard", ".", "RETLOW", ")", "if", "not", "res", ":", "self", ".", "failedItem", "=", "item", ".", "name", "return", "False", "item", ".", "price", ",", "item", ".", "owner", ",", "item", ".", "id", "=", "res", "totalPrice", "+=", "item", ".", "price", "self", ".", "npSpent", "=", "totalPrice", "return", "True", "def", "buyQuestItems", "(", "self", ")", ":", "\"\"\" Attempts to buy all quest items, returns result\n \n Returns\n bool - True if successful, otherwise False\n \"\"\"", "for", "item", "in", "self", ".", "items", ":", "us", "=", "UserShopFront", "(", "self", ".", "usr", ",", "item", ".", "owner", ",", "item", ".", "id", ",", "str", "(", "item", ".", "price", ")", ")", "us", ".", "loadInventory", "(", ")", "if", "not", "item", ".", "name", "in", "us", ".", "inventory", ":", "return", "False", "if", "not", "us", ".", "inventory", "[", "item", ".", "name", "]", ".", "buy", "(", ")", ":", "return", "False", "return", "True", "def", "submitQuest", "(", "self", ")", ":", "\"\"\" Submits the active quest, returns result\n \n Returns\n bool - True if successful, otherwise False\n \"\"\"", "form", "=", "pg", ".", "form", "(", "action", "=", "\"kitchen2.phtml\"", ")", "pg", "=", "form", ".", "submit", "(", ")", "if", "\"Woohoo\"", "in", "pg", ".", "content", ":", "try", ":", "self", ".", "prize", "=", "pg", ".", "find", "(", "text", "=", "\"The Chef waves his hands, and you may collect your prize...\"", ")", ".", "parent", ".", "parent", ".", "find_all", "(", "\"b\"", ")", "[", "-", "1", "]", ".", "text", "except", "Exception", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "exception", "(", "\"Failed to parse kitchen quest prize\"", ",", "{", "'pg'", ":", "pg", "}", ")", "raise", "parseException", "return", "True", "else", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "info", "(", "\"Failed to complete kitchen quest\"", ",", "{", "'pg'", ":", "pg", "}", ")", "return", "False", "def", "_parseActiveQuest", "(", "self", ",", "pg", ")", ":", "try", ":", "dets", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "table", ".", "find_all", "(", "\"td\"", ")", "self", ".", "recipe", "=", "dets", "[", "1", "]", ".", "text", "hour", "=", "dets", "[", "3", "]", ".", "find_all", "(", "\"b\"", ")", "[", "1", "]", ".", "text", "min", "=", "dets", "[", "3", "]", ".", "find_all", "(", "\"b\"", ")", "[", "2", "]", ".", "text", "self", ".", "time", "=", "(", "hour", ",", "min", ")", "imgs", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "table", ".", "find_all", "(", "\"td\"", ")", "[", "5", "]", ".", "find_all", "(", "\"img\"", ")", "items", "=", "pg", ".", "find", "(", "\"td\"", ",", "\"content\"", ")", ".", "table", ".", "find_all", "(", "\"td\"", ")", "[", "5", "]", ".", "find_all", "(", "\"b\"", ")", "self", ".", "items", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "items", ")", ")", ":", "tmpItem", "=", "Item", "(", "items", "[", "i", "]", ".", "text", ")", "tmpItem", ".", "img", "=", "imgs", "[", "i", "]", "[", "'src'", "]", "self", ".", "items", ".", "append", "(", "tmpItem", ")", "except", "Exception", ":", "logging", ".", "getLogger", "(", "\"neolib.quest\"", ")", ".", "exception", "(", "\"Failed to parse quest details\"", ",", "{", "'pg'", ":", "pg", "}", ")", "raise", "parseException" ]
Provides an interface for accepting and completing Kitchen Quests Provides functionality for initiating and completing quests given by the Mystery Island Kitchen.
[ "Provides", "an", "interface", "for", "accepting", "and", "completing", "Kitchen", "Quests", "Provides", "functionality", "for", "initiating", "and", "completing", "quests", "given", "by", "the", "Mystery", "Island", "Kitchen", "." ]
[ "\"\"\"Provides an interface for accepting and completing Kitchen Quests\n \n Provides functionality for initiating and completing quests given by the\n Mystery Island Kitchen. Each part is broken down into accepting a quest,\n determining it's total worth, buying the necessary items, and finally\n completing the quest.\n \n Attributes\n usr (User) -- Associated user\n recipe (str) -- Name of the current recipe\n time (tuple) -- Number of hours and minutes left on the quest\n items (list) -- List of quest items\n npSpent (int) -- Total NPs spent on the quest\n prize (str) -- Prize awarded by completing the quest\n \n Initialization\n KitchenQuest(usr)\n \n Loads the existing quest, otherwise attempts to accept a new quest.\n \n Loads the kitchen quest page and checks for an active quest. If an\n active quest is found it will load the quest details and compare the\n quest items to the user's inventory. If any item matching the quest item\n name is found in the inventory, it will automatically remove the item from\n the list of quest items. If no active quest is found, will attempt to accept\n a new quest and load the quest details.\n \n Parameters\n url (str) -- Remote URL address of the page\n \n Example\n >>> q = KitchenQuest(usr)\n >>> q.getPrice(2)\n True\n >>> q.npSpent\n 5100\n >>> q.buyQuestItems()\n True\n >>> q.submitQuest()\n True\n >>> q.prize\n 'blah has gained a level!'\n \"\"\"", "\"\"\" Updates the active quest details by reloading the quest page\n \"\"\"", "\"\"\" Prices all quest items and returns result\n \n Searches the shop wizard x times (x being number given in searches) for each\n quest item and finds the lowest price for each item. Combines all item prices\n and sets KitchenQuest.npSpent to the final value. Returns whether or not this\n process was successful. \n \n Parameters:\n searches (int) -- The number of times to search the Shop Wizard for each quest item\n \n Returns\n bool - True if successful, otherwise False\n \"\"\"", "\"\"\" Attempts to buy all quest items, returns result\n \n Returns\n bool - True if successful, otherwise False\n \"\"\"", "\"\"\" Submits the active quest, returns result\n \n Returns\n bool - True if successful, otherwise False\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
21
1,487
346
f3dade465ecbd9265de82c60069c6b93225149c0
Eptagone/Telegram.BotAPI
src/Telegram.BotAPI/Available Types/CallbackQuery.cs
[ "MIT" ]
C#
CallbackQuery
///<summary>This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.</summary>
This object represents an incoming callback query from a callback button in an inline keyboard. If the button that originated the query was attached to a message sent by the bot, the field message will be present. If the button was attached to a message sent via the bot (in inline mode), the field inline_message_id will be present. Exactly one of the fields data or game_short_name will be present.
[ "This", "object", "represents", "an", "incoming", "callback", "query", "from", "a", "callback", "button", "in", "an", "inline", "keyboard", ".", "If", "the", "button", "that", "originated", "the", "query", "was", "attached", "to", "a", "message", "sent", "by", "the", "bot", "the", "field", "message", "will", "be", "present", ".", "If", "the", "button", "was", "attached", "to", "a", "message", "sent", "via", "the", "bot", "(", "in", "inline", "mode", ")", "the", "field", "inline_message_id", "will", "be", "present", ".", "Exactly", "one", "of", "the", "fields", "data", "or", "game_short_name", "will", "be", "present", "." ]
[JsonObject(MemberSerialization = MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public sealed class CallbackQuery : IEquatable<CallbackQuery> { [JsonPropertyName(PropertyNames.Id)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Id { get; set; } [JsonPropertyName(PropertyNames.From)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public User From { get; set; } [JsonPropertyName(PropertyNames.Message)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Message Message { get; set; } [JsonPropertyName(PropertyNames.InlineMessageId)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string InlineMessageId { get; set; } [JsonPropertyName(PropertyNames.ChatInstance)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string ChatInstance { get; set; } [JsonPropertyName(PropertyNames.Data)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Data { get; set; } [JsonPropertyName(PropertyNames.GameShortName)] [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string GameShortName { get; set; } #pragma warning disable CS1591 public override bool Equals(object obj) { return Equals(obj as CallbackQuery); } public bool Equals(CallbackQuery other) { return other != null && Id == other.Id && EqualityComparer<User>.Default.Equals(From, other.From) && EqualityComparer<Message>.Default.Equals(Message, other.Message) && InlineMessageId == other.InlineMessageId && ChatInstance == other.ChatInstance && Data == other.Data && GameShortName == other.GameShortName; } public override int GetHashCode() { int hashCode = -1057610016; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Id); hashCode = hashCode * -1521134295 + EqualityComparer<User>.Default.GetHashCode(From); hashCode = hashCode * -1521134295 + EqualityComparer<Message>.Default.GetHashCode(Message); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(InlineMessageId); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(ChatInstance); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Data); hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(GameShortName); return hashCode; } public static bool operator ==(CallbackQuery left, CallbackQuery right) { return EqualityComparer<CallbackQuery>.Default.Equals(left, right); } public static bool operator !=(CallbackQuery left, CallbackQuery right) { return !(left == right); } #pragma warning restore CS1591 }
[ "[", "JsonObject", "(", "MemberSerialization", "=", "MemberSerialization", ".", "OptIn", ",", "NamingStrategyType", "=", "typeof", "(", "SnakeCaseNamingStrategy", ")", ")", "]", "public", "sealed", "class", "CallbackQuery", ":", "IEquatable", "<", "CallbackQuery", ">", "{", "[", "JsonPropertyName", "(", "PropertyNames", ".", "Id", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "string", "Id", "{", "get", ";", "set", ";", "}", "[", "JsonPropertyName", "(", "PropertyNames", ".", "From", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "User", "From", "{", "get", ";", "set", ";", "}", "[", "JsonPropertyName", "(", "PropertyNames", ".", "Message", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "Message", "Message", "{", "get", ";", "set", ";", "}", "[", "JsonPropertyName", "(", "PropertyNames", ".", "InlineMessageId", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "string", "InlineMessageId", "{", "get", ";", "set", ";", "}", "[", "JsonPropertyName", "(", "PropertyNames", ".", "ChatInstance", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "string", "ChatInstance", "{", "get", ";", "set", ";", "}", "[", "JsonPropertyName", "(", "PropertyNames", ".", "Data", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "string", "Data", "{", "get", ";", "set", ";", "}", "[", "JsonPropertyName", "(", "PropertyNames", ".", "GameShortName", ")", "]", "[", "JsonProperty", "(", "DefaultValueHandling", "=", "DefaultValueHandling", ".", "Ignore", ")", "]", "public", "string", "GameShortName", "{", "get", ";", "set", ";", "}", "pragma", "warning", "disable", "CS1591", "public", "override", "bool", "Equals", "(", "object", "obj", ")", "{", "return", "Equals", "(", "obj", "as", "CallbackQuery", ")", ";", "}", "public", "bool", "Equals", "(", "CallbackQuery", "other", ")", "{", "return", "other", "!=", "null", "&&", "Id", "==", "other", ".", "Id", "&&", "EqualityComparer", "<", "User", ">", ".", "Default", ".", "Equals", "(", "From", ",", "other", ".", "From", ")", "&&", "EqualityComparer", "<", "Message", ">", ".", "Default", ".", "Equals", "(", "Message", ",", "other", ".", "Message", ")", "&&", "InlineMessageId", "==", "other", ".", "InlineMessageId", "&&", "ChatInstance", "==", "other", ".", "ChatInstance", "&&", "Data", "==", "other", ".", "Data", "&&", "GameShortName", "==", "other", ".", "GameShortName", ";", "}", "public", "override", "int", "GetHashCode", "(", ")", "{", "int", "hashCode", "=", "-", "1057610016", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "string", ">", ".", "Default", ".", "GetHashCode", "(", "Id", ")", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "User", ">", ".", "Default", ".", "GetHashCode", "(", "From", ")", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "Message", ">", ".", "Default", ".", "GetHashCode", "(", "Message", ")", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "string", ">", ".", "Default", ".", "GetHashCode", "(", "InlineMessageId", ")", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "string", ">", ".", "Default", ".", "GetHashCode", "(", "ChatInstance", ")", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "string", ">", ".", "Default", ".", "GetHashCode", "(", "Data", ")", ";", "hashCode", "=", "hashCode", "*", "-", "1521134295", "+", "EqualityComparer", "<", "string", ">", ".", "Default", ".", "GetHashCode", "(", "GameShortName", ")", ";", "return", "hashCode", ";", "}", "public", "static", "bool", "operator", "==", "(", "CallbackQuery", "left", ",", "CallbackQuery", "right", ")", "{", "return", "EqualityComparer", "<", "CallbackQuery", ">", ".", "Default", ".", "Equals", "(", "left", ",", "right", ")", ";", "}", "public", "static", "bool", "operator", "!=", "(", "CallbackQuery", "left", ",", "CallbackQuery", "right", ")", "{", "return", "!", "(", "left", "==", "right", ")", ";", "}", "pragma", "warning", "restore", "CS1591", "}" ]
This object represents an incoming callback query from a callback button in an inline keyboard.
[ "This", "object", "represents", "an", "incoming", "callback", "query", "from", "a", "callback", "button", "in", "an", "inline", "keyboard", "." ]
[ "///<summary>Unique identifier for this query.</summary>", "///<summary>Sender.</summary>", "///<summary>Optional. Message with the callback button that originated the query. Note that message content and message date will not be available if the message is too old.</summary>", "///<summary>Optional. Identifier of the message sent via the bot in inline mode, that originated the query.</summary>", "///<summary>Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in games.</summary>", "///<summary>Optional. Data associated with the callback button. Be aware that a bad client can send arbitrary data in this field.</summary>", "///<summary>Optional. Short name of a Game to be returned, serves as the unique identifier for the game.</summary>", "// Missing XML comment for publicly visible type or member", "// Missing XML comment for publicly visible type or member" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
650
84
48fa5d7ed50b5d62c2f8b4f0f88ed0266448efae
dtouch3d/cle
cle/backends/symbol.py
[ "BSD-2-Clause" ]
Python
Symbol
Representation of a symbol from a binary file. Smart enough to rebase itself. There should never be more than one Symbol instance representing a single symbol. To make sure of this, only use the :meth:`cle.backends.Backend.get_symbol()` to create new symbols. :ivar owner: The object that contains this symbol :vartype owner: cle.backends.Backend :ivar str name: The name of this symbol :ivar int addr: The un-based address of this symbol, an RVA :iver int size: The size of this symbol :ivar int type: The type of this symbol as one of SYMBOL.TYPE_* :ivar bool resolved: Whether this import symbol has been resolved to a real symbol :ivar resolvedby: The real symbol this import symbol has been resolve to :vartype resolvedby: None or cle.backends.Symbol :ivar str resolvewith: The name of the library we must use to resolve this symbol, or None if none is required.
Representation of a symbol from a binary file. Smart enough to rebase itself. There should never be more than one Symbol instance representing a single symbol. To make sure of this, only use the :meth:`cle.backends.Backend.get_symbol()` to create new symbols.
[ "Representation", "of", "a", "symbol", "from", "a", "binary", "file", ".", "Smart", "enough", "to", "rebase", "itself", ".", "There", "should", "never", "be", "more", "than", "one", "Symbol", "instance", "representing", "a", "single", "symbol", ".", "To", "make", "sure", "of", "this", "only", "use", "the", ":", "meth", ":", "`", "cle", ".", "backends", ".", "Backend", ".", "get_symbol", "()", "`", "to", "create", "new", "symbols", "." ]
class Symbol: """ Representation of a symbol from a binary file. Smart enough to rebase itself. There should never be more than one Symbol instance representing a single symbol. To make sure of this, only use the :meth:`cle.backends.Backend.get_symbol()` to create new symbols. :ivar owner: The object that contains this symbol :vartype owner: cle.backends.Backend :ivar str name: The name of this symbol :ivar int addr: The un-based address of this symbol, an RVA :iver int size: The size of this symbol :ivar int type: The type of this symbol as one of SYMBOL.TYPE_* :ivar bool resolved: Whether this import symbol has been resolved to a real symbol :ivar resolvedby: The real symbol this import symbol has been resolve to :vartype resolvedby: None or cle.backends.Symbol :ivar str resolvewith: The name of the library we must use to resolve this symbol, or None if none is required. """ # enum for symbol types TYPE_OTHER = 0 TYPE_NONE = 1 TYPE_FUNCTION = 2 TYPE_OBJECT = 3 TYPE_SECTION = 4 def __init__(self, owner, name, relative_addr, size, sym_type): """ Not documenting this since if you try calling it, you're wrong. """ self.owner = owner self.name = name self.relative_addr = relative_addr self.size = size self.type = sym_type self.resolved = False self.resolvedby = None # would be nice if we could populate demangled_names here... #demangled = self.demangled_name #if demangled is not None: # self.owner.demangled_names[self.name] = demangled def __repr__(self): if self.is_import: return '<Symbol "%s" in %s (import)>' % (self.name, self.owner.provides) else: return '<Symbol "%s" in %s at %#x>' % (self.name, self.owner.provides, self.rebased_addr) def resolve(self, obj): self.resolved = True self.resolvedby = obj self.owner.resolved_imports.append(self) @property def rebased_addr(self): """ The address of this symbol in the global memory space """ return AT.from_rva(self.relative_addr, self.owner).to_mva() @property def linked_addr(self): return AT.from_rva(self.relative_addr, self.owner).to_lva() @property def is_function(self): """ Whether this symbol is a function """ return self.type == Symbol.TYPE_FUNCTION # These may be overridden in subclasses is_static = False is_common = False is_import = False is_export = False is_local = False is_weak = False is_extern = False is_forward = False @property def demangled_name(self): """ The name of this symbol, run through a C++ demangler Warning: this calls out to the external program `c++filt` and will fail loudly if it's not installed """ # make sure it's mangled if self.name.startswith("_Z"): name = self.name if '@@' in self.name: name = self.name.split("@@")[0] args = ['c++filt'] args.append(name) pipe = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) stdout, _ = pipe.communicate() demangled = stdout.decode().split("\n") if demangled: return demangled[0] return self.name def resolve_forwarder(self): """ If this symbol is a forwarding export, return the symbol the forwarding refers to, or None if it cannot be found. """ return self # compatibility layer _complained_owner = False @property def owner_obj(self): if not Symbol._complained_owner: Symbol._complained_owner = True l.critical("Deprecation warning: use symbol.owner instead of symbol.owner_obj") return self.owner
[ "class", "Symbol", ":", "TYPE_OTHER", "=", "0", "TYPE_NONE", "=", "1", "TYPE_FUNCTION", "=", "2", "TYPE_OBJECT", "=", "3", "TYPE_SECTION", "=", "4", "def", "__init__", "(", "self", ",", "owner", ",", "name", ",", "relative_addr", ",", "size", ",", "sym_type", ")", ":", "\"\"\"\n Not documenting this since if you try calling it, you're wrong.\n \"\"\"", "self", ".", "owner", "=", "owner", "self", ".", "name", "=", "name", "self", ".", "relative_addr", "=", "relative_addr", "self", ".", "size", "=", "size", "self", ".", "type", "=", "sym_type", "self", ".", "resolved", "=", "False", "self", ".", "resolvedby", "=", "None", "def", "__repr__", "(", "self", ")", ":", "if", "self", ".", "is_import", ":", "return", "'<Symbol \"%s\" in %s (import)>'", "%", "(", "self", ".", "name", ",", "self", ".", "owner", ".", "provides", ")", "else", ":", "return", "'<Symbol \"%s\" in %s at %#x>'", "%", "(", "self", ".", "name", ",", "self", ".", "owner", ".", "provides", ",", "self", ".", "rebased_addr", ")", "def", "resolve", "(", "self", ",", "obj", ")", ":", "self", ".", "resolved", "=", "True", "self", ".", "resolvedby", "=", "obj", "self", ".", "owner", ".", "resolved_imports", ".", "append", "(", "self", ")", "@", "property", "def", "rebased_addr", "(", "self", ")", ":", "\"\"\"\n The address of this symbol in the global memory space\n \"\"\"", "return", "AT", ".", "from_rva", "(", "self", ".", "relative_addr", ",", "self", ".", "owner", ")", ".", "to_mva", "(", ")", "@", "property", "def", "linked_addr", "(", "self", ")", ":", "return", "AT", ".", "from_rva", "(", "self", ".", "relative_addr", ",", "self", ".", "owner", ")", ".", "to_lva", "(", ")", "@", "property", "def", "is_function", "(", "self", ")", ":", "\"\"\"\n Whether this symbol is a function\n \"\"\"", "return", "self", ".", "type", "==", "Symbol", ".", "TYPE_FUNCTION", "is_static", "=", "False", "is_common", "=", "False", "is_import", "=", "False", "is_export", "=", "False", "is_local", "=", "False", "is_weak", "=", "False", "is_extern", "=", "False", "is_forward", "=", "False", "@", "property", "def", "demangled_name", "(", "self", ")", ":", "\"\"\"\n The name of this symbol, run through a C++ demangler\n\n Warning: this calls out to the external program `c++filt` and will fail loudly if it's not installed\n \"\"\"", "if", "self", ".", "name", ".", "startswith", "(", "\"_Z\"", ")", ":", "name", "=", "self", ".", "name", "if", "'@@'", "in", "self", ".", "name", ":", "name", "=", "self", ".", "name", ".", "split", "(", "\"@@\"", ")", "[", "0", "]", "args", "=", "[", "'c++filt'", "]", "args", ".", "append", "(", "name", ")", "pipe", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdin", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "stdout", ",", "_", "=", "pipe", ".", "communicate", "(", ")", "demangled", "=", "stdout", ".", "decode", "(", ")", ".", "split", "(", "\"\\n\"", ")", "if", "demangled", ":", "return", "demangled", "[", "0", "]", "return", "self", ".", "name", "def", "resolve_forwarder", "(", "self", ")", ":", "\"\"\"\n If this symbol is a forwarding export, return the symbol the forwarding refers to, or None if it cannot be found.\n \"\"\"", "return", "self", "_complained_owner", "=", "False", "@", "property", "def", "owner_obj", "(", "self", ")", ":", "if", "not", "Symbol", ".", "_complained_owner", ":", "Symbol", ".", "_complained_owner", "=", "True", "l", ".", "critical", "(", "\"Deprecation warning: use symbol.owner instead of symbol.owner_obj\"", ")", "return", "self", ".", "owner" ]
Representation of a symbol from a binary file.
[ "Representation", "of", "a", "symbol", "from", "a", "binary", "file", "." ]
[ "\"\"\"\n Representation of a symbol from a binary file. Smart enough to rebase itself.\n\n There should never be more than one Symbol instance representing a single symbol. To make sure of this, only use\n the :meth:`cle.backends.Backend.get_symbol()` to create new symbols.\n\n :ivar owner: The object that contains this symbol\n :vartype owner: cle.backends.Backend\n :ivar str name: The name of this symbol\n :ivar int addr: The un-based address of this symbol, an RVA\n :iver int size: The size of this symbol\n :ivar int type: The type of this symbol as one of SYMBOL.TYPE_*\n :ivar bool resolved: Whether this import symbol has been resolved to a real symbol\n :ivar resolvedby: The real symbol this import symbol has been resolve to\n :vartype resolvedby: None or cle.backends.Symbol\n :ivar str resolvewith: The name of the library we must use to resolve this symbol, or None if none is required.\n \"\"\"", "# enum for symbol types", "\"\"\"\n Not documenting this since if you try calling it, you're wrong.\n \"\"\"", "# would be nice if we could populate demangled_names here...", "#demangled = self.demangled_name", "#if demangled is not None:", "# self.owner.demangled_names[self.name] = demangled", "\"\"\"\n The address of this symbol in the global memory space\n \"\"\"", "\"\"\"\n Whether this symbol is a function\n \"\"\"", "# These may be overridden in subclasses", "\"\"\"\n The name of this symbol, run through a C++ demangler\n\n Warning: this calls out to the external program `c++filt` and will fail loudly if it's not installed\n \"\"\"", "# make sure it's mangled", "\"\"\"\n If this symbol is a forwarding export, return the symbol the forwarding refers to, or None if it cannot be found.\n \"\"\"", "# compatibility layer" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [ { "identifier": "ivar", "docstring": "The object that contains this symbol", "docstring_tokens": [ "The", "object", "that", "contains", "this", "symbol" ] }, { "identifier": "vartype", "docstring": null, "docstring_tokens": [ "None" ] }, { "identifier": "ivar", "docstring": "The name of this symbol", "docstring_tokens": [ "The", "name", "of", "this", "symbol" ] }, { "identifier": "ivar", "docstring": "The un-based address of this symbol, an RVA", "docstring_tokens": [ "The", "un", "-", "based", "address", "of", "this", "symbol", "an", "RVA" ] }, { "identifier": "iver", "docstring": "The size of this symbol", "docstring_tokens": [ "The", "size", "of", "this", "symbol" ] }, { "identifier": "ivar", "docstring": "The type of this symbol as one of SYMBOL.TYPE_", "docstring_tokens": [ "The", "type", "of", "this", "symbol", "as", "one", "of", "SYMBOL", ".", "TYPE_" ] }, { "identifier": "ivar", "docstring": "Whether this import symbol has been resolved to a real symbol", "docstring_tokens": [ "Whether", "this", "import", "symbol", "has", "been", "resolved", "to", "a", "real", "symbol" ] }, { "identifier": "ivar", "docstring": "The real symbol this import symbol has been resolve to", "docstring_tokens": [ "The", "real", "symbol", "this", "import", "symbol", "has", "been", "resolve", "to" ] }, { "identifier": "vartype", "docstring": "None or cle.backends.Symbol", "docstring_tokens": [ "None", "or", "cle", ".", "backends", ".", "Symbol" ] }, { "identifier": "ivar", "docstring": "The name of the library we must use to resolve this symbol, or None if none is required.", "docstring_tokens": [ "The", "name", "of", "the", "library", "we", "must", "use", "to", "resolve", "this", "symbol", "or", "None", "if", "none", "is", "required", "." ] } ] }
false
16
944
230
be4cb7bec32cc6351219c2ef23cc711a585bbef1
toddrme2178/audiomate
audiomate/corpus/validation/base.py
[ "MIT" ]
Python
ValidationResult
Representation of the result of a validation. The basic result just indicates a pass or fail. Depending on the validator it can be extended to hold more information (e.g. utterance-ids which triggered the task to fail). Args: passed (bool): A boolean indicating, if the validation has passed (True) or failed (False). name (str): The name of the validator, that produced the result. info (dict): Dictionary containing key/value string-pairs with detailed information of the validation. For example id of the label-list that was validated.
Representation of the result of a validation. The basic result just indicates a pass or fail. Depending on the validator it can be extended to hold more information .
[ "Representation", "of", "the", "result", "of", "a", "validation", ".", "The", "basic", "result", "just", "indicates", "a", "pass", "or", "fail", ".", "Depending", "on", "the", "validator", "it", "can", "be", "extended", "to", "hold", "more", "information", "." ]
class ValidationResult: """ Representation of the result of a validation. The basic result just indicates a pass or fail. Depending on the validator it can be extended to hold more information (e.g. utterance-ids which triggered the task to fail). Args: passed (bool): A boolean indicating, if the validation has passed (True) or failed (False). name (str): The name of the validator, that produced the result. info (dict): Dictionary containing key/value string-pairs with detailed information of the validation. For example id of the label-list that was validated. """ def __init__(self, passed, name='Validation', info=None): self.passed = passed self.name = name self.info = info def get_report(self): """ Return a string containing a report of the result. This can used to print or save to a text file. Returns: str: String containing infos about the result """ lines = [ self.name, '=' * len(self.name) ] if self.info is not None: lines.append('') sorted_info = sorted(self.info.items(), key=lambda x: x[0]) lines.extend(['--> {}: {}'.format(k, v) for k, v in sorted_info]) lines.append('') lines.append('Result: {}'.format('Passed' if self.passed else 'Failed')) return '\n'.join(lines)
[ "class", "ValidationResult", ":", "def", "__init__", "(", "self", ",", "passed", ",", "name", "=", "'Validation'", ",", "info", "=", "None", ")", ":", "self", ".", "passed", "=", "passed", "self", ".", "name", "=", "name", "self", ".", "info", "=", "info", "def", "get_report", "(", "self", ")", ":", "\"\"\"\n Return a string containing a report of the result.\n This can used to print or save to a text file.\n\n Returns:\n str: String containing infos about the result\n \"\"\"", "lines", "=", "[", "self", ".", "name", ",", "'='", "*", "len", "(", "self", ".", "name", ")", "]", "if", "self", ".", "info", "is", "not", "None", ":", "lines", ".", "append", "(", "''", ")", "sorted_info", "=", "sorted", "(", "self", ".", "info", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "0", "]", ")", "lines", ".", "extend", "(", "[", "'--> {}: {}'", ".", "format", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "sorted_info", "]", ")", "lines", ".", "append", "(", "''", ")", "lines", ".", "append", "(", "'Result: {}'", ".", "format", "(", "'Passed'", "if", "self", ".", "passed", "else", "'Failed'", ")", ")", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
Representation of the result of a validation.
[ "Representation", "of", "the", "result", "of", "a", "validation", "." ]
[ "\"\"\"\n Representation of the result of a validation.\n The basic result just indicates a pass or fail.\n Depending on the validator it can be extended to hold more information\n (e.g. utterance-ids which triggered the task to fail).\n\n Args:\n passed (bool): A boolean indicating, if the validation has passed (True) or failed (False).\n name (str): The name of the validator, that produced the result.\n info (dict): Dictionary containing key/value string-pairs with detailed information of the validation.\n For example id of the label-list that was validated.\n \"\"\"", "\"\"\"\n Return a string containing a report of the result.\n This can used to print or save to a text file.\n\n Returns:\n str: String containing infos about the result\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "passed", "type": null, "docstring": "A boolean indicating, if the validation has passed (True) or failed (False).", "docstring_tokens": [ "A", "boolean", "indicating", "if", "the", "validation", "has", "passed", "(", "True", ")", "or", "failed", "(", "False", ")", "." ], "default": null, "is_optional": false }, { "identifier": "name", "type": null, "docstring": "The name of the validator, that produced the result.", "docstring_tokens": [ "The", "name", "of", "the", "validator", "that", "produced", "the", "result", "." ], "default": null, "is_optional": false }, { "identifier": "info", "type": null, "docstring": "Dictionary containing key/value string-pairs with detailed information of the validation.\nFor example id of the label-list that was validated.", "docstring_tokens": [ "Dictionary", "containing", "key", "/", "value", "string", "-", "pairs", "with", "detailed", "information", "of", "the", "validation", ".", "For", "example", "id", "of", "the", "label", "-", "list", "that", "was", "validated", "." ], "default": null, "is_optional": false } ], "others": [] }
false
14
308
124
753569eaa97ecfab355c12db588729d90e480f1e
Kajaste/pychoir
pychoir/callables.py
[ "MIT" ]
Python
WhenPassedTo
Matchers that check how a value behaves when passed to a callable. :param callable_: The callable to pass the value to. Usage: >>> from pychoir import WhenPassedTo >>> "foo" == WhenPassedTo(int).raises(ValueError) True >>> "5" == WhenPassedTo(int).does_not_raise() True >>> "5" == WhenPassedTo(int).returns(5) True
Matchers that check how a value behaves when passed to a callable.
[ "Matchers", "that", "check", "how", "a", "value", "behaves", "when", "passed", "to", "a", "callable", "." ]
class WhenPassedTo: """Matchers that check how a value behaves when passed to a callable. :param callable_: The callable to pass the value to. Usage: >>> from pychoir import WhenPassedTo >>> "foo" == WhenPassedTo(int).raises(ValueError) True >>> "5" == WhenPassedTo(int).does_not_raise() True >>> "5" == WhenPassedTo(int).returns(5) True """ def __init__(self, callable_: Callable[[Any], Any]): self.callable = callable_ def returns(self, value: Any) -> Matcher: return _Returns(self.callable, value) def raises(self, exception: Optional[Type[Exception]] = None) -> Matcher: return _Raises(self.callable, exception) def does_not_raise(self) -> Matcher: return _DoesNotRaise(self.callable)
[ "class", "WhenPassedTo", ":", "def", "__init__", "(", "self", ",", "callable_", ":", "Callable", "[", "[", "Any", "]", ",", "Any", "]", ")", ":", "self", ".", "callable", "=", "callable_", "def", "returns", "(", "self", ",", "value", ":", "Any", ")", "->", "Matcher", ":", "return", "_Returns", "(", "self", ".", "callable", ",", "value", ")", "def", "raises", "(", "self", ",", "exception", ":", "Optional", "[", "Type", "[", "Exception", "]", "]", "=", "None", ")", "->", "Matcher", ":", "return", "_Raises", "(", "self", ".", "callable", ",", "exception", ")", "def", "does_not_raise", "(", "self", ")", "->", "Matcher", ":", "return", "_DoesNotRaise", "(", "self", ".", "callable", ")" ]
Matchers that check how a value behaves when passed to a callable.
[ "Matchers", "that", "check", "how", "a", "value", "behaves", "when", "passed", "to", "a", "callable", "." ]
[ "\"\"\"Matchers that check how a value behaves when passed to a callable.\n\n :param callable_: The callable to pass the value to.\n\n Usage:\n >>> from pychoir import WhenPassedTo\n >>> \"foo\" == WhenPassedTo(int).raises(ValueError)\n True\n >>> \"5\" == WhenPassedTo(int).does_not_raise()\n True\n >>> \"5\" == WhenPassedTo(int).returns(5)\n True\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "callable_", "type": null, "docstring": "The callable to pass the value to.\nUsage:\n>>> from pychoir import WhenPassedTo\n>>> \"foo\" == WhenPassedTo(int).raises(ValueError)\nTrue\n>>> \"5\" == WhenPassedTo(int).does_not_raise()\nTrue\n>>> \"5\" == WhenPassedTo(int).returns(5)\nTrue", "docstring_tokens": [ "The", "callable", "to", "pass", "the", "value", "to", ".", "Usage", ":", ">>>", "from", "pychoir", "import", "WhenPassedTo", ">>>", "\"", "foo", "\"", "==", "WhenPassedTo", "(", "int", ")", ".", "raises", "(", "ValueError", ")", "True", ">>>", "\"", "5", "\"", "==", "WhenPassedTo", "(", "int", ")", ".", "does_not_raise", "()", "True", ">>>", "\"", "5", "\"", "==", "WhenPassedTo", "(", "int", ")", ".", "returns", "(", "5", ")", "True" ], "default": null, "is_optional": null } ], "others": [] }
false
13
195
94
1542f55a60fead247b26433ce27e88fb1af86f21
gengoai/mono-repo
apollo/src/main/java/com/gengoai/apollo/ml/transform/AbstractSingleSourceTransform.java
[ "Apache-2.0" ]
Java
AbstractSingleSourceTransform
/** * <p> * A base implementation of a {@link SingleSourceTransform}. Concrete implementations have access to the * <code>input</code> and <code>output</code> names and must implement the following methods: * </p> * <p><ul> * <li>{@link #fit(MStream)} - fits the transform to a stream of {@link Observation} from its input source</li> * <li>{@link #transform(Observation)} - transforms an {@link Observation} from its input source</li> * <li>{@link #updateMetadata(DataSet)} - updates the {@link ObservationMetadata} associated with * the {@link DataSet}, which may require updating both the input and output source metadata.</li> * </ul></p> * * @param <T> the type parameter * @author David B. Bracewell */
A base implementation of a SingleSourceTransform. Concrete implementations have access to the input and output names and must implement the following methods: #fit(MStream) - fits the transform to a stream of Observation from its input source #transform(Observation) - transforms an Observation from its input source #updateMetadata(DataSet) - updates the ObservationMetadata associated with the DataSet, which may require updating both the input and output source metadata. @param the type parameter @author David B. Bracewell
[ "A", "base", "implementation", "of", "a", "SingleSourceTransform", ".", "Concrete", "implementations", "have", "access", "to", "the", "input", "and", "output", "names", "and", "must", "implement", "the", "following", "methods", ":", "#fit", "(", "MStream", ")", "-", "fits", "the", "transform", "to", "a", "stream", "of", "Observation", "from", "its", "input", "source", "#transform", "(", "Observation", ")", "-", "transforms", "an", "Observation", "from", "its", "input", "source", "#updateMetadata", "(", "DataSet", ")", "-", "updates", "the", "ObservationMetadata", "associated", "with", "the", "DataSet", "which", "may", "require", "updating", "both", "the", "input", "and", "output", "source", "metadata", ".", "@param", "the", "type", "parameter", "@author", "David", "B", ".", "Bracewell" ]
public abstract class AbstractSingleSourceTransform<T extends AbstractSingleSourceTransform<T>> implements Transform, SingleSourceTransform { private static final long serialVersionUID = 1L; /** * The name of the input source */ @NonNull protected String input = Datum.DEFAULT_INPUT; /** * The name of the output source */ @NonNull protected String output = Datum.DEFAULT_INPUT; protected NDArrayFactory ndArrayFactory; public AbstractSingleSourceTransform() { this.ndArrayFactory = NDArrayFactory.ND; } @Override public T copy() { return Cast.as(Copyable.deepCopy(this)); } /** * fits the transform to a stream of {@link Observation} from its input source * * @param observations the stream of observations from the input source */ protected abstract void fit(@NonNull MStream<Observation> observations); @Override public DataSet fitAndTransform(DataSet dataset) { ndArrayFactory = dataset.getNDArrayFactory(); fit(dataset.stream().map(d -> d.get(input))); return transform(dataset); } @Override public final Set<String> getInputs() { return Collections.singleton(input); } @Override public final Set<String> getOutputs() { return Collections.singleton(output); } @Override public T input(@NonNull String name) { this.input = name; if(Strings.isNotNullOrBlank(output)) { this.output = name; } return Cast.as(this); } @Override public T output(@NonNull String name) { this.output = name; return Cast.as(this); } @Override public T source(@NonNull String name) { this.input = name; this.output = name; return Cast.as(this); } @Override public final DataSet transform(@NonNull DataSet dataset) { DataSet data = dataset.map(this::transform); updateMetadata(data); return data; } @Override public Datum transform(@NonNull Datum datum) { datum.put(output, transform(datum.get(input))); return datum; } /** * Transforms the given observation. * * @param observation the observation to transform * @return the transformed observation */ protected abstract Observation transform(@NonNull Observation observation); /** * Updates the {@link ObservationMetadata} for the input and output as needed. * * @param data the data */ protected abstract void updateMetadata(@NonNull DataSet data); }
[ "public", "abstract", "class", "AbstractSingleSourceTransform", "<", "T", "extends", "AbstractSingleSourceTransform", "<", "T", ">", ">", "implements", "Transform", ",", "SingleSourceTransform", "{", "private", "static", "final", "long", "serialVersionUID", "=", "1L", ";", "/**\n * The name of the input source\n */", "@", "NonNull", "protected", "String", "input", "=", "Datum", ".", "DEFAULT_INPUT", ";", "/**\n * The name of the output source\n */", "@", "NonNull", "protected", "String", "output", "=", "Datum", ".", "DEFAULT_INPUT", ";", "protected", "NDArrayFactory", "ndArrayFactory", ";", "public", "AbstractSingleSourceTransform", "(", ")", "{", "this", ".", "ndArrayFactory", "=", "NDArrayFactory", ".", "ND", ";", "}", "@", "Override", "public", "T", "copy", "(", ")", "{", "return", "Cast", ".", "as", "(", "Copyable", ".", "deepCopy", "(", "this", ")", ")", ";", "}", "/**\n * fits the transform to a stream of {@link Observation} from its input source\n *\n * @param observations the stream of observations from the input source\n */", "protected", "abstract", "void", "fit", "(", "@", "NonNull", "MStream", "<", "Observation", ">", "observations", ")", ";", "@", "Override", "public", "DataSet", "fitAndTransform", "(", "DataSet", "dataset", ")", "{", "ndArrayFactory", "=", "dataset", ".", "getNDArrayFactory", "(", ")", ";", "fit", "(", "dataset", ".", "stream", "(", ")", ".", "map", "(", "d", "->", "d", ".", "get", "(", "input", ")", ")", ")", ";", "return", "transform", "(", "dataset", ")", ";", "}", "@", "Override", "public", "final", "Set", "<", "String", ">", "getInputs", "(", ")", "{", "return", "Collections", ".", "singleton", "(", "input", ")", ";", "}", "@", "Override", "public", "final", "Set", "<", "String", ">", "getOutputs", "(", ")", "{", "return", "Collections", ".", "singleton", "(", "output", ")", ";", "}", "@", "Override", "public", "T", "input", "(", "@", "NonNull", "String", "name", ")", "{", "this", ".", "input", "=", "name", ";", "if", "(", "Strings", ".", "isNotNullOrBlank", "(", "output", ")", ")", "{", "this", ".", "output", "=", "name", ";", "}", "return", "Cast", ".", "as", "(", "this", ")", ";", "}", "@", "Override", "public", "T", "output", "(", "@", "NonNull", "String", "name", ")", "{", "this", ".", "output", "=", "name", ";", "return", "Cast", ".", "as", "(", "this", ")", ";", "}", "@", "Override", "public", "T", "source", "(", "@", "NonNull", "String", "name", ")", "{", "this", ".", "input", "=", "name", ";", "this", ".", "output", "=", "name", ";", "return", "Cast", ".", "as", "(", "this", ")", ";", "}", "@", "Override", "public", "final", "DataSet", "transform", "(", "@", "NonNull", "DataSet", "dataset", ")", "{", "DataSet", "data", "=", "dataset", ".", "map", "(", "this", "::", "transform", ")", ";", "updateMetadata", "(", "data", ")", ";", "return", "data", ";", "}", "@", "Override", "public", "Datum", "transform", "(", "@", "NonNull", "Datum", "datum", ")", "{", "datum", ".", "put", "(", "output", ",", "transform", "(", "datum", ".", "get", "(", "input", ")", ")", ")", ";", "return", "datum", ";", "}", "/**\n * Transforms the given observation.\n *\n * @param observation the observation to transform\n * @return the transformed observation\n */", "protected", "abstract", "Observation", "transform", "(", "@", "NonNull", "Observation", "observation", ")", ";", "/**\n * Updates the {@link ObservationMetadata} for the input and output as needed.\n *\n * @param data the data\n */", "protected", "abstract", "void", "updateMetadata", "(", "@", "NonNull", "DataSet", "data", ")", ";", "}" ]
<p> A base implementation of a {@link SingleSourceTransform}.
[ "<p", ">", "A", "base", "implementation", "of", "a", "{", "@link", "SingleSourceTransform", "}", "." ]
[]
[ { "param": "Transform, SingleSourceTransform", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Transform, SingleSourceTransform", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
13
542
181
253b2b3cd28b45e7b53c5945d1ff15c22da1782d
DouglasWaterfall/dalsemi
examples/Hygrochron/src/dumpmission.java
[ "OLDAP-2.2.1" ]
Java
dumpmission
/** * Dumps the mission from a DS1922/DS2422 temperature and A-D/Humidity * data-logger. If this is a DS1922H, all data values will be converted * and displayed as humidity values. * * @version 1.00, 14 Aug, 2003 * @author shughes */
Dumps the mission from a DS1922/DS2422 temperature and A-D/Humidity data-logger. If this is a DS1922H, all data values will be converted and displayed as humidity values.
[ "Dumps", "the", "mission", "from", "a", "DS1922", "/", "DS2422", "temperature", "and", "A", "-", "D", "/", "Humidity", "data", "-", "logger", ".", "If", "this", "is", "a", "DS1922H", "all", "data", "values", "will", "be", "converted", "and", "displayed", "as", "humidity", "values", "." ]
public class dumpmission { /** usage string, all available command-line switches */ static String[][] usageString = new String[][] { {"-hideTemp", "", "if present, temperature values will be suppressed in output"}, {"-hideData", "", "if present, data values will be suppressed in output"}, {"-stopMission", "", "if present, mission will be stopped before the data is retrieved"}, {"-useOverdrive", "", "if present, mission data will be collected in overdrive speed"}, {"-readWritePass", "H", "This is the read/write password to use for reading the mission, H=8 bytes of ascii-encoded hex"}, {"-readOnlyPass", "H", "This is the read-only password to use for reading the mission, H=8 bytes of ascii-encoded hex"} }; /** prints out a usage string and exits */ public static void usage() { System.out.println(); System.out.println("switches:"); for(int i=0; i<usageString.length; i++) { System.out.println(" " + usageString[i][0] + usageString[i][1]); System.out.println(" " + usageString[i][2]); } System.exit(0); } /** the main routine, parses the input switches, dumps the mission data */ public static void main(String[] args) { DSPortAdapter adapter = null; boolean showHumidity = true; boolean showTemperature = true; boolean stopMission = false; boolean useOverdrive = false; byte[] readWritePass = null, readOnlyPass = null; try { if(args.length>0) { for(int i=0; i<args.length; i++) { String arg = args[i].toUpperCase(); if(arg.equals(usageString[0][0].toUpperCase())) { showTemperature = false; } else if(arg.equals(usageString[1][0].toUpperCase())) { showHumidity = false; } else if(arg.equals(usageString[2][0].toUpperCase())) { stopMission = true; } else if(arg.equals(usageString[3][0].toUpperCase())) { useOverdrive = true; } else if(arg.indexOf(usageString[4][0].toUpperCase())==0) { readWritePass = Convert.toByteArray( arg.substring(usageString[4][0].length())); } else if(arg.indexOf(usageString[5][0].toUpperCase())==0) { readOnlyPass = Convert.toByteArray( arg.substring(usageString[5][0].length())); } else if(arg.equals("-H")) { usage(); } else { System.out.println("bad argument: '" + args[i] + "'"); usage(); } } } adapter = OneWireAccessProvider.getDefaultAdapter(); adapter.beginExclusive(true); adapter.targetFamily(0x41); OneWireContainer41 owc = (OneWireContainer41)adapter.getFirstDeviceContainer(); if(owc!=null) { System.out.println("Found " + owc.toString()); if(useOverdrive) { System.out.println("setting speed as overdrive"); owc.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, true); } if(readWritePass!=null) owc.setContainerReadWritePassword(readWritePass, 0); if(readOnlyPass!=null) owc.setContainerReadOnlyPassword(readOnlyPass, 0); byte[] state = owc.readDevice(); //read to set container variables if(stopMission) { System.out.println("Stopping mission"); boolean missionStopped = false; while(!missionStopped) { try { if(!owc.isMissionRunning()) { System.out.println("Mission is stopped"); missionStopped = true; } else { owc.stopMission(); } } catch(Exception e) {;} } } boolean loadResults = false; while(!loadResults) { try { System.out.println("loading mission results"); owc.loadMissionResults(); loadResults = true; } catch(Exception e) { e.printStackTrace(); } } System.out.println("Is Mission Running: " + owc.isMissionRunning()); if(owc.isMissionSUTA()) System.out.println("Start Upon Temperature Alarm: " + (owc.isMissionWFTA()?"Waiting for Temperature Alarm":"Got Temperature Alarm, Mission Started")); System.out.println("Sample Rate: " + owc.getMissionSampleRate(0) + " secs"); System.out.println("Mission Start Time: " + (new java.util.Date(owc.getMissionTimeStamp(0)))); System.out.println("Mission Sample Count: " + owc.getMissionSampleCount(0)); System.out.println("Rollover Enabled: " + owc.isMissionRolloverEnabled()); if(owc.isMissionRolloverEnabled()) { System.out.println("Rollover Occurred: " + owc.hasMissionRolloverOccurred()); if(owc.hasMissionRolloverOccurred()) { System.out.println("First Sample Timestamp: " + (new java.util.Date( owc.getMissionSampleTimeStamp(OneWireContainer41.TEMPERATURE_CHANNEL,0) | owc.getMissionSampleTimeStamp(OneWireContainer41.DATA_CHANNEL,0)))); System.out.println("Total Mission Samples: " + owc.getMissionSampleCountTotal(0)); } } System.out.println("Temperature Logging: " + (!owc.getMissionChannelEnable(OneWireContainer41.TEMPERATURE_CHANNEL)? "Disabled": owc.getMissionResolution(OneWireContainer41.TEMPERATURE_CHANNEL) + " bit")); System.out.println("Temperature Low Alarm: " + (!owc.getMissionAlarmEnable(OneWireContainer41.TEMPERATURE_CHANNEL, 0)? "Disabled": owc.getMissionAlarm(OneWireContainer41.TEMPERATURE_CHANNEL, 0) + "C (" + (owc.hasMissionAlarmed(OneWireContainer41.TEMPERATURE_CHANNEL, 0)? "ALARM)":"no alarm)"))); System.out.println("Temperature High Alarm: " + (!owc.getMissionAlarmEnable(OneWireContainer41.TEMPERATURE_CHANNEL, 1)? "Disabled": owc.getMissionAlarm(OneWireContainer41.TEMPERATURE_CHANNEL, 1) + "C (" + (owc.hasMissionAlarmed(OneWireContainer41.TEMPERATURE_CHANNEL, 1)? "ALARM)":"no alarm)"))); System.out.println(owc.getMissionLabel(OneWireContainer41.DATA_CHANNEL) + " Logging: " + (!owc.getMissionChannelEnable(OneWireContainer41.DATA_CHANNEL)? "Disabled": owc.getMissionResolution(OneWireContainer41.DATA_CHANNEL) + " bit")); System.out.println(owc.getMissionLabel(OneWireContainer41.DATA_CHANNEL) + " Low Alarm: " + (!owc.getMissionAlarmEnable(OneWireContainer41.DATA_CHANNEL, 0)? "Disabled": owc.getMissionAlarm(OneWireContainer41.DATA_CHANNEL, 0) + "% RH (" + (owc.hasMissionAlarmed(OneWireContainer41.DATA_CHANNEL, 0)? "ALARM)":"no alarm)"))); System.out.println(owc.getMissionLabel(OneWireContainer41.DATA_CHANNEL) + " High Alarm: " + (!owc.getMissionAlarmEnable(OneWireContainer41.DATA_CHANNEL, 1)? "Disabled": owc.getMissionAlarm(OneWireContainer41.DATA_CHANNEL, 1) + "% RH (" + (owc.hasMissionAlarmed(OneWireContainer41.DATA_CHANNEL, 1)? "ALARM)":"no alarm)"))); System.out.println("Total Device Samples: " + owc.getDeviceSampleCount()); if(showTemperature) { System.out.println("Temperature Readings"); if(!owc.getMissionChannelEnable(owc.TEMPERATURE_CHANNEL)) { System.out.println("Temperature Mission Not enabled"); } else { int dataCount = owc.getMissionSampleCount(owc.TEMPERATURE_CHANNEL); System.out.println("SampleCount = " + dataCount); for(int i=0; i<dataCount; i++) { System.out.println(owc.getMissionSample(owc.TEMPERATURE_CHANNEL, i)); } } } if(showHumidity) { System.out.println( owc.getMissionLabel(owc.DATA_CHANNEL) + " Readings"); if(!owc.getMissionChannelEnable(owc.DATA_CHANNEL)) { System.out.println( owc.getMissionLabel(owc.DATA_CHANNEL) + " Mission Not enabled"); } else { int dataCount = owc.getMissionSampleCount(owc.DATA_CHANNEL); System.out.println("SampleCount = " + dataCount); for(int i=0; i<dataCount; i++) { System.out.println(owc.getMissionSample(owc.DATA_CHANNEL, i)); } } } } else { System.out.println("No DS1922/DS2422 device found"); } } catch(Exception e) { e.printStackTrace(); } finally { if(adapter!=null) adapter.endExclusive(); } } }
[ "public", "class", "dumpmission", "{", "/** usage string, all available command-line switches */", "static", "String", "[", "]", "[", "]", "usageString", "=", "new", "String", "[", "]", "[", "]", "{", "{", "\"", "-hideTemp", "\"", ",", "\"", "\"", ",", "\"", "if present, temperature values will be suppressed in output", "\"", "}", ",", "{", "\"", "-hideData", "\"", ",", "\"", "\"", ",", "\"", "if present, data values will be suppressed in output", "\"", "}", ",", "{", "\"", "-stopMission", "\"", ",", "\"", "\"", ",", "\"", "if present, mission will be stopped before the data is retrieved", "\"", "}", ",", "{", "\"", "-useOverdrive", "\"", ",", "\"", "\"", ",", "\"", "if present, mission data will be collected in overdrive speed", "\"", "}", ",", "{", "\"", "-readWritePass", "\"", ",", "\"", "H", "\"", ",", "\"", "This is the read/write password to use for reading the mission, H=8 bytes of ascii-encoded hex", "\"", "}", ",", "{", "\"", "-readOnlyPass", "\"", ",", "\"", "H", "\"", ",", "\"", "This is the read-only password to use for reading the mission, H=8 bytes of ascii-encoded hex", "\"", "}", "}", ";", "/** prints out a usage string and exits */", "public", "static", "void", "usage", "(", ")", "{", "System", ".", "out", ".", "println", "(", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "switches:", "\"", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "usageString", ".", "length", ";", "i", "++", ")", "{", "System", ".", "out", ".", "println", "(", "\"", " ", "\"", "+", "usageString", "[", "i", "]", "[", "0", "]", "+", "usageString", "[", "i", "]", "[", "1", "]", ")", ";", "System", ".", "out", ".", "println", "(", "\"", " ", "\"", "+", "usageString", "[", "i", "]", "[", "2", "]", ")", ";", "}", "System", ".", "exit", "(", "0", ")", ";", "}", "/** the main routine, parses the input switches, dumps the mission data */", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "DSPortAdapter", "adapter", "=", "null", ";", "boolean", "showHumidity", "=", "true", ";", "boolean", "showTemperature", "=", "true", ";", "boolean", "stopMission", "=", "false", ";", "boolean", "useOverdrive", "=", "false", ";", "byte", "[", "]", "readWritePass", "=", "null", ",", "readOnlyPass", "=", "null", ";", "try", "{", "if", "(", "args", ".", "length", ">", "0", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "++", ")", "{", "String", "arg", "=", "args", "[", "i", "]", ".", "toUpperCase", "(", ")", ";", "if", "(", "arg", ".", "equals", "(", "usageString", "[", "0", "]", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", ")", "{", "showTemperature", "=", "false", ";", "}", "else", "if", "(", "arg", ".", "equals", "(", "usageString", "[", "1", "]", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", ")", "{", "showHumidity", "=", "false", ";", "}", "else", "if", "(", "arg", ".", "equals", "(", "usageString", "[", "2", "]", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", ")", "{", "stopMission", "=", "true", ";", "}", "else", "if", "(", "arg", ".", "equals", "(", "usageString", "[", "3", "]", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", ")", "{", "useOverdrive", "=", "true", ";", "}", "else", "if", "(", "arg", ".", "indexOf", "(", "usageString", "[", "4", "]", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", "==", "0", ")", "{", "readWritePass", "=", "Convert", ".", "toByteArray", "(", "arg", ".", "substring", "(", "usageString", "[", "4", "]", "[", "0", "]", ".", "length", "(", ")", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "indexOf", "(", "usageString", "[", "5", "]", "[", "0", "]", ".", "toUpperCase", "(", ")", ")", "==", "0", ")", "{", "readOnlyPass", "=", "Convert", ".", "toByteArray", "(", "arg", ".", "substring", "(", "usageString", "[", "5", "]", "[", "0", "]", ".", "length", "(", ")", ")", ")", ";", "}", "else", "if", "(", "arg", ".", "equals", "(", "\"", "-H", "\"", ")", ")", "{", "usage", "(", ")", ";", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "bad argument: '", "\"", "+", "args", "[", "i", "]", "+", "\"", "'", "\"", ")", ";", "usage", "(", ")", ";", "}", "}", "}", "adapter", "=", "OneWireAccessProvider", ".", "getDefaultAdapter", "(", ")", ";", "adapter", ".", "beginExclusive", "(", "true", ")", ";", "adapter", ".", "targetFamily", "(", "0x41", ")", ";", "OneWireContainer41", "owc", "=", "(", "OneWireContainer41", ")", "adapter", ".", "getFirstDeviceContainer", "(", ")", ";", "if", "(", "owc", "!=", "null", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Found ", "\"", "+", "owc", ".", "toString", "(", ")", ")", ";", "if", "(", "useOverdrive", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "setting speed as overdrive", "\"", ")", ";", "owc", ".", "setSpeed", "(", "DSPortAdapter", ".", "SPEED_OVERDRIVE", ",", "true", ")", ";", "}", "if", "(", "readWritePass", "!=", "null", ")", "owc", ".", "setContainerReadWritePassword", "(", "readWritePass", ",", "0", ")", ";", "if", "(", "readOnlyPass", "!=", "null", ")", "owc", ".", "setContainerReadOnlyPassword", "(", "readOnlyPass", ",", "0", ")", ";", "byte", "[", "]", "state", "=", "owc", ".", "readDevice", "(", ")", ";", "if", "(", "stopMission", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Stopping mission", "\"", ")", ";", "boolean", "missionStopped", "=", "false", ";", "while", "(", "!", "missionStopped", ")", "{", "try", "{", "if", "(", "!", "owc", ".", "isMissionRunning", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Mission is stopped", "\"", ")", ";", "missionStopped", "=", "true", ";", "}", "else", "{", "owc", ".", "stopMission", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", ";", "}", "}", "}", "boolean", "loadResults", "=", "false", ";", "while", "(", "!", "loadResults", ")", "{", "try", "{", "System", ".", "out", ".", "println", "(", "\"", "loading mission results", "\"", ")", ";", "owc", ".", "loadMissionResults", "(", ")", ";", "loadResults", "=", "true", ";", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "}", "System", ".", "out", ".", "println", "(", "\"", "Is Mission Running: ", "\"", "+", "owc", ".", "isMissionRunning", "(", ")", ")", ";", "if", "(", "owc", ".", "isMissionSUTA", "(", ")", ")", "System", ".", "out", ".", "println", "(", "\"", "Start Upon Temperature Alarm: ", "\"", "+", "(", "owc", ".", "isMissionWFTA", "(", ")", "?", "\"", "Waiting for Temperature Alarm", "\"", ":", "\"", "Got Temperature Alarm, Mission Started", "\"", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Sample Rate: ", "\"", "+", "owc", ".", "getMissionSampleRate", "(", "0", ")", "+", "\"", " secs", "\"", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Mission Start Time: ", "\"", "+", "(", "new", "java", ".", "util", ".", "Date", "(", "owc", ".", "getMissionTimeStamp", "(", "0", ")", ")", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Mission Sample Count: ", "\"", "+", "owc", ".", "getMissionSampleCount", "(", "0", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Rollover Enabled: ", "\"", "+", "owc", ".", "isMissionRolloverEnabled", "(", ")", ")", ";", "if", "(", "owc", ".", "isMissionRolloverEnabled", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Rollover Occurred: ", "\"", "+", "owc", ".", "hasMissionRolloverOccurred", "(", ")", ")", ";", "if", "(", "owc", ".", "hasMissionRolloverOccurred", "(", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "First Sample Timestamp: ", "\"", "+", "(", "new", "java", ".", "util", ".", "Date", "(", "owc", ".", "getMissionSampleTimeStamp", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "0", ")", "|", "owc", ".", "getMissionSampleTimeStamp", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "0", ")", ")", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Total Mission Samples: ", "\"", "+", "owc", ".", "getMissionSampleCountTotal", "(", "0", ")", ")", ";", "}", "}", "System", ".", "out", ".", "println", "(", "\"", "Temperature Logging: ", "\"", "+", "(", "!", "owc", ".", "getMissionChannelEnable", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ")", "?", "\"", "Disabled", "\"", ":", "owc", ".", "getMissionResolution", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ")", "+", "\"", " bit", "\"", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Temperature Low Alarm: ", "\"", "+", "(", "!", "owc", ".", "getMissionAlarmEnable", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "0", ")", "?", "\"", "Disabled", "\"", ":", "owc", ".", "getMissionAlarm", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "0", ")", "+", "\"", "C (", "\"", "+", "(", "owc", ".", "hasMissionAlarmed", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "0", ")", "?", "\"", "ALARM)", "\"", ":", "\"", "no alarm)", "\"", ")", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Temperature High Alarm: ", "\"", "+", "(", "!", "owc", ".", "getMissionAlarmEnable", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "1", ")", "?", "\"", "Disabled", "\"", ":", "owc", ".", "getMissionAlarm", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "1", ")", "+", "\"", "C (", "\"", "+", "(", "owc", ".", "hasMissionAlarmed", "(", "OneWireContainer41", ".", "TEMPERATURE_CHANNEL", ",", "1", ")", "?", "\"", "ALARM)", "\"", ":", "\"", "no alarm)", "\"", ")", ")", ")", ";", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionLabel", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ")", "+", "\"", " Logging: ", "\"", "+", "(", "!", "owc", ".", "getMissionChannelEnable", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ")", "?", "\"", "Disabled", "\"", ":", "owc", ".", "getMissionResolution", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ")", "+", "\"", " bit", "\"", ")", ")", ";", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionLabel", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ")", "+", "\"", " Low Alarm: ", "\"", "+", "(", "!", "owc", ".", "getMissionAlarmEnable", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "0", ")", "?", "\"", "Disabled", "\"", ":", "owc", ".", "getMissionAlarm", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "0", ")", "+", "\"", "% RH (", "\"", "+", "(", "owc", ".", "hasMissionAlarmed", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "0", ")", "?", "\"", "ALARM)", "\"", ":", "\"", "no alarm)", "\"", ")", ")", ")", ";", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionLabel", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ")", "+", "\"", " High Alarm: ", "\"", "+", "(", "!", "owc", ".", "getMissionAlarmEnable", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "1", ")", "?", "\"", "Disabled", "\"", ":", "owc", ".", "getMissionAlarm", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "1", ")", "+", "\"", "% RH (", "\"", "+", "(", "owc", ".", "hasMissionAlarmed", "(", "OneWireContainer41", ".", "DATA_CHANNEL", ",", "1", ")", "?", "\"", "ALARM)", "\"", ":", "\"", "no alarm)", "\"", ")", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "Total Device Samples: ", "\"", "+", "owc", ".", "getDeviceSampleCount", "(", ")", ")", ";", "if", "(", "showTemperature", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Temperature Readings", "\"", ")", ";", "if", "(", "!", "owc", ".", "getMissionChannelEnable", "(", "owc", ".", "TEMPERATURE_CHANNEL", ")", ")", "{", "System", ".", "out", ".", "println", "(", "\"", "Temperature Mission Not enabled", "\"", ")", ";", "}", "else", "{", "int", "dataCount", "=", "owc", ".", "getMissionSampleCount", "(", "owc", ".", "TEMPERATURE_CHANNEL", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "SampleCount = ", "\"", "+", "dataCount", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dataCount", ";", "i", "++", ")", "{", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionSample", "(", "owc", ".", "TEMPERATURE_CHANNEL", ",", "i", ")", ")", ";", "}", "}", "}", "if", "(", "showHumidity", ")", "{", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionLabel", "(", "owc", ".", "DATA_CHANNEL", ")", "+", "\"", " Readings", "\"", ")", ";", "if", "(", "!", "owc", ".", "getMissionChannelEnable", "(", "owc", ".", "DATA_CHANNEL", ")", ")", "{", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionLabel", "(", "owc", ".", "DATA_CHANNEL", ")", "+", "\"", " Mission Not enabled", "\"", ")", ";", "}", "else", "{", "int", "dataCount", "=", "owc", ".", "getMissionSampleCount", "(", "owc", ".", "DATA_CHANNEL", ")", ";", "System", ".", "out", ".", "println", "(", "\"", "SampleCount = ", "\"", "+", "dataCount", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "dataCount", ";", "i", "++", ")", "{", "System", ".", "out", ".", "println", "(", "owc", ".", "getMissionSample", "(", "owc", ".", "DATA_CHANNEL", ",", "i", ")", ")", ";", "}", "}", "}", "}", "else", "{", "System", ".", "out", ".", "println", "(", "\"", "No DS1922/DS2422 device found", "\"", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "if", "(", "adapter", "!=", "null", ")", "adapter", ".", "endExclusive", "(", ")", ";", "}", "}", "}" ]
Dumps the mission from a DS1922/DS2422 temperature and A-D/Humidity data-logger.
[ "Dumps", "the", "mission", "from", "a", "DS1922", "/", "DS2422", "temperature", "and", "A", "-", "D", "/", "Humidity", "data", "-", "logger", "." ]
[ "//read to set container variables\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
27
2,108
87
35f8e209b351fa95e669df36318280f0c39fe459
rlwhitcomb/utilities
java/info/rlwhitcomb/heart/Heart.java
[ "MIT" ]
Java
Heart
/** * Demonstration program to use bitmaps to display character pictures. * Inspired by a question I answered on Quora: * <a href="https://www.quora.com/I-have-to-use-6-rows-and-7-columns-for-a-heart-pattern-in-Java-programming-Can-you-help-me">I have to use 6 rows and 7 columns for a heart pattern in Java programming. Can you help me?</a> */
Demonstration program to use bitmaps to display character pictures. Inspired by a question I answered on Quora: I have to use 6 rows and 7 columns for a heart pattern in Java programming.
[ "Demonstration", "program", "to", "use", "bitmaps", "to", "display", "character", "pictures", ".", "Inspired", "by", "a", "question", "I", "answered", "on", "Quora", ":", "I", "have", "to", "use", "6", "rows", "and", "7", "columns", "for", "a", "heart", "pattern", "in", "Java", "programming", "." ]
public class Heart { /** The original data to display the heart pattern. */ private static int[] HEART_DATA = { 0b0110110, 0b1001001, 0b1000001, 0b0100010, 0b0010100, 0b0001000 }; /** Another example with a different bit size. */ private static int[] CROSS_DATA = { 0b00011000, 0b00011000, 0b00011000, 0b11111111, 0b11111111, 0b00011000, 0b00011000, 0b00011000, 0b00011000, 0b00011000, 0b00011000, 0b00011000 }; /** * Given a character and a width, produce a string with that character * repeated for the entire width. * @param dotChar The "dot" character to be replicated. * @param width The number of times to replicate the character. * @return The completed string. */ private static String getStringOfNChars(final char dotChar, final int width) { StringBuilder buf = new StringBuilder(width); for (int i = 0; i < width; i++) { buf.append(dotChar); } return buf.toString(); } /** * Shortcut method to display the data with default character, bit size, and width. * @param data The bitmap data to display (in the low-order bits). */ private static void printData(final int[] data) { printData(data, 8); } /** * Shortcut method to display the data with default character, and width, but * specifying how many low-order bits are relevant in the input data. * @param data The bitmap data to display (in the low-order bits). * @param bits The number of low-order bits in each integer of the data that are * significant (that is, that hold the design to display). */ private static void printData(final int[] data, final int bits) { printData(data, bits, '*', 2); } /** * Shortcut method to display the data with default character, but * specifying how many low-order bits are relevant in the input data, and the * "width" of each bit position. * @param data The bitmap data to display (in the low-order bits). * @param bits The number of low-order bits in each integer of the data that are * significant (that is, that hold the design to display). * @param width The multiplier for the character for each bit of the data. A width * of two will print two of the character for each bit of data, for instance. */ private static void printData(final int[] data, final int bits, final int width) { printData(data, bits, '*', width); } /** * The main method to display the data with the given character, specifying how many * low-order bits are relevant in the input data, and the "width" of each bit position. * @param data The bitmap data to display (in the low-order bits). * @param bits The number of low-order bits in each integer of the data that are * significant (that is, that hold the design to display). * @param dotChar The character to display for each one bit in the data, which is * multiplied by the width. * @param width The multiplier for the character for each bit of the data. A width * of two will print two of the character for each bit of data, for instance. */ private static void printData(final int[] data, final int bits, final char dotChar, final int width) { final String dot = getStringOfNChars(dotChar, width); final String blank = getStringOfNChars(' ', width); for (int i = 0; i < data.length; i++) { int row = data[i]; for (int j = bits - 1; j >= 0; j--) { boolean bit = ((row >> j) & 1) == 1; System.out.print(bit ? dot : blank); } System.out.println(); } System.out.println(); } /** * Run the program from the command line. * @param args The parsed command line arguments. */ public static void main(final String[] args) { printData(HEART_DATA, 7); printData(HEART_DATA, 7, '#', 2); printData(HEART_DATA, 7, '#', 1); printData(CROSS_DATA); printData(CROSS_DATA, 8, 1); printData(CROSS_DATA, 8, '#', 1); } }
[ "public", "class", "Heart", "{", "/** The original data to display the heart pattern. */", "private", "static", "int", "[", "]", "HEART_DATA", "=", "{", "0b0110110", ",", "0b1001001", ",", "0b1000001", ",", "0b0100010", ",", "0b0010100", ",", "0b0001000", "}", ";", "/** Another example with a different bit size. */", "private", "static", "int", "[", "]", "CROSS_DATA", "=", "{", "0b00011000", ",", "0b00011000", ",", "0b00011000", ",", "0b11111111", ",", "0b11111111", ",", "0b00011000", ",", "0b00011000", ",", "0b00011000", ",", "0b00011000", ",", "0b00011000", ",", "0b00011000", ",", "0b00011000", "}", ";", "/**\n * Given a character and a width, produce a string with that character\n * repeated for the entire width.\n * @param dotChar The \"dot\" character to be replicated.\n * @param width The number of times to replicate the character.\n * @return The completed string.\n */", "private", "static", "String", "getStringOfNChars", "(", "final", "char", "dotChar", ",", "final", "int", "width", ")", "{", "StringBuilder", "buf", "=", "new", "StringBuilder", "(", "width", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "width", ";", "i", "++", ")", "{", "buf", ".", "append", "(", "dotChar", ")", ";", "}", "return", "buf", ".", "toString", "(", ")", ";", "}", "/**\n * Shortcut method to display the data with default character, bit size, and width.\n * @param data The bitmap data to display (in the low-order bits).\n */", "private", "static", "void", "printData", "(", "final", "int", "[", "]", "data", ")", "{", "printData", "(", "data", ",", "8", ")", ";", "}", "/**\n * Shortcut method to display the data with default character, and width, but\n * specifying how many low-order bits are relevant in the input data.\n * @param data The bitmap data to display (in the low-order bits).\n * @param bits The number of low-order bits in each integer of the data that are\n * significant (that is, that hold the design to display).\n */", "private", "static", "void", "printData", "(", "final", "int", "[", "]", "data", ",", "final", "int", "bits", ")", "{", "printData", "(", "data", ",", "bits", ",", "'*'", ",", "2", ")", ";", "}", "/**\n * Shortcut method to display the data with default character, but\n * specifying how many low-order bits are relevant in the input data, and the\n * \"width\" of each bit position.\n * @param data The bitmap data to display (in the low-order bits).\n * @param bits The number of low-order bits in each integer of the data that are\n * significant (that is, that hold the design to display).\n * @param width The multiplier for the character for each bit of the data. A width\n * of two will print two of the character for each bit of data, for instance.\n */", "private", "static", "void", "printData", "(", "final", "int", "[", "]", "data", ",", "final", "int", "bits", ",", "final", "int", "width", ")", "{", "printData", "(", "data", ",", "bits", ",", "'*'", ",", "width", ")", ";", "}", "/**\n * The main method to display the data with the given character, specifying how many\n * low-order bits are relevant in the input data, and the \"width\" of each bit position.\n * @param data The bitmap data to display (in the low-order bits).\n * @param bits The number of low-order bits in each integer of the data that are\n * significant (that is, that hold the design to display).\n * @param dotChar The character to display for each one bit in the data, which is\n * multiplied by the width.\n * @param width The multiplier for the character for each bit of the data. A width\n * of two will print two of the character for each bit of data, for instance.\n */", "private", "static", "void", "printData", "(", "final", "int", "[", "]", "data", ",", "final", "int", "bits", ",", "final", "char", "dotChar", ",", "final", "int", "width", ")", "{", "final", "String", "dot", "=", "getStringOfNChars", "(", "dotChar", ",", "width", ")", ";", "final", "String", "blank", "=", "getStringOfNChars", "(", "' '", ",", "width", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "int", "row", "=", "data", "[", "i", "]", ";", "for", "(", "int", "j", "=", "bits", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "boolean", "bit", "=", "(", "(", "row", ">>", "j", ")", "&", "1", ")", "==", "1", ";", "System", ".", "out", ".", "print", "(", "bit", "?", "dot", ":", "blank", ")", ";", "}", "System", ".", "out", ".", "println", "(", ")", ";", "}", "System", ".", "out", ".", "println", "(", ")", ";", "}", "/**\n * Run the program from the command line.\n * @param args The parsed command line arguments.\n */", "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "{", "printData", "(", "HEART_DATA", ",", "7", ")", ";", "printData", "(", "HEART_DATA", ",", "7", ",", "'#'", ",", "2", ")", ";", "printData", "(", "HEART_DATA", ",", "7", ",", "'#'", ",", "1", ")", ";", "printData", "(", "CROSS_DATA", ")", ";", "printData", "(", "CROSS_DATA", ",", "8", ",", "1", ")", ";", "printData", "(", "CROSS_DATA", ",", "8", ",", "'#'", ",", "1", ")", ";", "}", "}" ]
Demonstration program to use bitmaps to display character pictures.
[ "Demonstration", "program", "to", "use", "bitmaps", "to", "display", "character", "pictures", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
1,162
90
5c6cfb4a7846a6581a1d4c9f3dd9aa1cd9bb1ed9
hmqgg/bilibili-danmaku-client
src/index.js
[ "MIT" ]
JavaScript
DanmakuClient
/** * DanmakuClient is the only open API to applications. * Internally it is a thin wrap over ApplicationConnection, which provides a * more explicit control of the lifecycle and partial backwards compatibility * to the old version. * The lifecycle of DanmakuClient is as follows: * - Start from state 'idle'. * - 'idle' -> 'opening': On start(). * - 'opening' -> 'opened': When connection is successfully opened. Emit event 'open'. * -> 'closing': On terminate(). * -> 'closed': If the connection is closed by the server. Emit event 'close'. * -> 'closed': If an error has occurred. Emit event 'close'. Emit event * 'error' with the error. * - 'opened' -> 'closing': On terminate(). * -> 'closed': If the connection is closed by the server. Emit event 'close'. * -> 'closed': If an error has occurred. Emit event 'close'. Emit event * 'error' with the error. * - 'closing' -> 'closed': When connection is succefully closed. Emit event 'close'. * - End in state 'closed'. */
DanmakuClient is the only open API to applications. Internally it is a thin wrap over ApplicationConnection, which provides a more explicit control of the lifecycle and partial backwards compatibility to the old version. The lifecycle of DanmakuClient is as follows: - Start from state 'idle'.
[ "DanmakuClient", "is", "the", "only", "open", "API", "to", "applications", ".", "Internally", "it", "is", "a", "thin", "wrap", "over", "ApplicationConnection", "which", "provides", "a", "more", "explicit", "control", "of", "the", "lifecycle", "and", "partial", "backwards", "compatibility", "to", "the", "old", "version", ".", "The", "lifecycle", "of", "DanmakuClient", "is", "as", "follows", ":", "-", "Start", "from", "state", "'", "idle", "'", "." ]
class DanmakuClient extends EventEmitter { /** * Construct a new DanmakuClient with the given Room id and options. * Note that the Room id must be the original Room id, that is, the short Room id * is not accepted. * For example, one of the official Live Rooms, https://live.bilibili.com/1, * uses the original Room id 5440. In this case, trying to connect to Room 1 would * not work properly, the correct way is to connect to Room 5440. * @param {Number} room The id of the Room to connect to. * @param {Object} [options] The options to pass to ApplicationConnection. * Use this only when you know what you're doing. */ constructor(room, options) { super(); this.room = room; this.options = options; this.state = 'idle'; } /** * Start the DanmakuClient. * This method is only available in state 'idle'. Otherwise nothing will happen. * Internally the underlying ApplicationConnection is not created before start(), * so this.connection will not be available then, */ start() { if (this.state !== 'idle') return; this.connection = new ApplicationConnection(this.room, this.options); this.state = 'opening'; this.connection.on('open', () => { this.state = 'opened'; this.emit('open'); }); this.connection.on('error', err => this.emit('error', err)); this.connection.on('close', () => { this.state = 'closed'; this.emit('close'); }); this.connection.on('message', event => this.emit('event', event)); } /** * Request closing of the DanmakuClient. * Note that this method will return immediately after requesting. The client will * be actually closed at time when the 'close' event is emitted. */ terminate() { if (this.state === 'opening' || this.state === 'opened') this.connection.close(); } }
[ "class", "DanmakuClient", "extends", "EventEmitter", "{", "constructor", "(", "room", ",", "options", ")", "{", "super", "(", ")", ";", "this", ".", "room", "=", "room", ";", "this", ".", "options", "=", "options", ";", "this", ".", "state", "=", "'idle'", ";", "}", "start", "(", ")", "{", "if", "(", "this", ".", "state", "!==", "'idle'", ")", "return", ";", "this", ".", "connection", "=", "new", "ApplicationConnection", "(", "this", ".", "room", ",", "this", ".", "options", ")", ";", "this", ".", "state", "=", "'opening'", ";", "this", ".", "connection", ".", "on", "(", "'open'", ",", "(", ")", "=>", "{", "this", ".", "state", "=", "'opened'", ";", "this", ".", "emit", "(", "'open'", ")", ";", "}", ")", ";", "this", ".", "connection", ".", "on", "(", "'error'", ",", "err", "=>", "this", ".", "emit", "(", "'error'", ",", "err", ")", ")", ";", "this", ".", "connection", ".", "on", "(", "'close'", ",", "(", ")", "=>", "{", "this", ".", "state", "=", "'closed'", ";", "this", ".", "emit", "(", "'close'", ")", ";", "}", ")", ";", "this", ".", "connection", ".", "on", "(", "'message'", ",", "event", "=>", "this", ".", "emit", "(", "'event'", ",", "event", ")", ")", ";", "}", "terminate", "(", ")", "{", "if", "(", "this", ".", "state", "===", "'opening'", "||", "this", ".", "state", "===", "'opened'", ")", "this", ".", "connection", ".", "close", "(", ")", ";", "}", "}" ]
DanmakuClient is the only open API to applications.
[ "DanmakuClient", "is", "the", "only", "open", "API", "to", "applications", "." ]
[ "/**\n * Construct a new DanmakuClient with the given Room id and options.\n * Note that the Room id must be the original Room id, that is, the short Room id\n * is not accepted.\n * For example, one of the official Live Rooms, https://live.bilibili.com/1,\n * uses the original Room id 5440. In this case, trying to connect to Room 1 would\n * not work properly, the correct way is to connect to Room 5440.\n * @param {Number} room The id of the Room to connect to.\n * @param {Object} [options] The options to pass to ApplicationConnection.\n * Use this only when you know what you're doing.\n */", "/**\n * Start the DanmakuClient.\n * This method is only available in state 'idle'. Otherwise nothing will happen.\n * Internally the underlying ApplicationConnection is not created before start(),\n * so this.connection will not be available then,\n */", "/**\n * Request closing of the DanmakuClient.\n * Note that this method will return immediately after requesting. The client will\n * be actually closed at time when the 'close' event is emitted.\n */" ]
[ { "param": "EventEmitter", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "EventEmitter", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
14
453
250
13df0ff1c0a09d6127d889dc4c9fcda9893dffd3
zcoderz/leetcode
src/main/java/face_book/hard/ContinousSubArraySum.java
[ "BSD-3-Clause" ]
Java
ContinousSubArraySum
/** * 523. Continuous Subarray Sum * Medium * * 726 * * 124 * * Add to List * * Share * Given an integer array nums and an integer k, return true if nums has a * continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. * * An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. * * * * Example 1: * * Input: nums = [23,2,4,6,7], k = 6 * Output: true * Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. * * IMP-1 * * ToDO: Add to website. this is a tricky one, redo... */
523. Continuous Subarray Sum Medium 726 124 Add to List Share Given an integer array nums and an integer k, return true if nums has a continuous subarray of size at least two whose elements sum up to a multiple of k, or false otherwise. An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. Example 1. nums = [23,2,4,6,7], k = 6 Output: true Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. IMP-1 Add to website. this is a tricky one, redo
[ "523", ".", "Continuous", "Subarray", "Sum", "Medium", "726", "124", "Add", "to", "List", "Share", "Given", "an", "integer", "array", "nums", "and", "an", "integer", "k", "return", "true", "if", "nums", "has", "a", "continuous", "subarray", "of", "size", "at", "least", "two", "whose", "elements", "sum", "up", "to", "a", "multiple", "of", "k", "or", "false", "otherwise", ".", "An", "integer", "x", "is", "a", "multiple", "of", "k", "if", "there", "exists", "an", "integer", "n", "such", "that", "x", "=", "n", "*", "k", ".", "0", "is", "always", "a", "multiple", "of", "k", ".", "Example", "1", ".", "nums", "=", "[", "23", "2", "4", "6", "7", "]", "k", "=", "6", "Output", ":", "true", "Explanation", ":", "[", "2", "4", "]", "is", "a", "continuous", "subarray", "of", "size", "2", "whose", "elements", "sum", "up", "to", "6", ".", "IMP", "-", "1", "Add", "to", "website", ".", "this", "is", "a", "tricky", "one", "redo" ]
public class ContinousSubArraySum { public static void main (String [] args) { ContinousSubArraySum continous = new ContinousSubArraySum(); int [] nums = {23,2,4,6,6}; boolean res = continous.checkSubarraySum(nums, 7); System.out.println(res); } public boolean checkSubarraySum(int[] nums, int k) { int total = 0; Map<Integer, Integer> map = new HashMap<>(); map.put(0, -1); for (int i = 0; i < nums.length; i++) { total += nums[i]; int mod = total % k; if (map.containsKey(mod) && (i - map.get(mod) > 1)) { return true; } map.put(mod, map.getOrDefault(mod, i)); } return false; } }
[ "public", "class", "ContinousSubArraySum", "{", "public", "static", "void", "main", "(", "String", "[", "]", "args", ")", "{", "ContinousSubArraySum", "continous", "=", "new", "ContinousSubArraySum", "(", ")", ";", "int", "[", "]", "nums", "=", "{", "23", ",", "2", ",", "4", ",", "6", ",", "6", "}", ";", "boolean", "res", "=", "continous", ".", "checkSubarraySum", "(", "nums", ",", "7", ")", ";", "System", ".", "out", ".", "println", "(", "res", ")", ";", "}", "public", "boolean", "checkSubarraySum", "(", "int", "[", "]", "nums", ",", "int", "k", ")", "{", "int", "total", "=", "0", ";", "Map", "<", "Integer", ",", "Integer", ">", "map", "=", "new", "HashMap", "<", ">", "(", ")", ";", "map", ".", "put", "(", "0", ",", "-", "1", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nums", ".", "length", ";", "i", "++", ")", "{", "total", "+=", "nums", "[", "i", "]", ";", "int", "mod", "=", "total", "%", "k", ";", "if", "(", "map", ".", "containsKey", "(", "mod", ")", "&&", "(", "i", "-", "map", ".", "get", "(", "mod", ")", ">", "1", ")", ")", "{", "return", "true", ";", "}", "map", ".", "put", "(", "mod", ",", "map", ".", "getOrDefault", "(", "mod", ",", "i", ")", ")", ";", "}", "return", "false", ";", "}", "}" ]
523.
[ "523", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
195
199
7ebb6f8ae7f112525ef18dd17216c1485d9c65e2
cedric-legallo/nuxeo-ui-elements
viewers/nuxeo-pdf-viewer.js
[ "Apache-2.0" ]
JavaScript
PDFViewer
/** * An element for viewing PDF files. * * Example: * * <nuxeo-pdf-viewer src="sample.pdf"></nuxeo-pdf-viewer> * * ### Styling * * The following custom properties and mixins are available for styling: * * Custom property | Description | Default * ----------------|-------------|---------- * `--nuxeo-pdf-viewer-layout` | Mixin applied to the viewer | `{}` * `--nuxeo-pdf-viewer-iframe` | Mixin applied to the iframe enclosing pdfjs | `{}` * * * @memberof Nuxeo * @demo demo/nuxeo-pdf-viewer/index.html */
An element for viewing PDF files. Example. Styling The following custom properties and mixins are available for styling.
[ "An", "element", "for", "viewing", "PDF", "files", ".", "Example", ".", "Styling", "The", "following", "custom", "properties", "and", "mixins", "are", "available", "for", "styling", "." ]
class PDFViewer extends Nuxeo.Element { static get template() { return html` <style> :host { display: block; @apply --nuxeo-pdf-viewer-layout; } iframe { width: 100%; height: 100%; border: 0; @apply --nuxeo-pdf-viewer-iframe; } </style> <iframe src\$="[[_path(src)]]"></iframe> `; } static get is() { return 'nuxeo-pdf-viewer'; } static get properties() { return { /** * The path to the pdf file to display. */ src: { type: String, }, }; } static get importMeta() { return import.meta; } _path(file) { // get an absolute href const el = document.createElement('a'); el.href = file; return this.resolveUrl(`pdfjs/web/viewer.html?file=${encodeURI(el.href)}`); } }
[ "class", "PDFViewer", "extends", "Nuxeo", ".", "Element", "{", "static", "get", "template", "(", ")", "{", "return", "html", "`", "\\$", "`", ";", "}", "static", "get", "is", "(", ")", "{", "return", "'nuxeo-pdf-viewer'", ";", "}", "static", "get", "properties", "(", ")", "{", "return", "{", "src", ":", "{", "type", ":", "String", ",", "}", ",", "}", ";", "}", "static", "get", "importMeta", "(", ")", "{", "return", "import", ".", "meta", ";", "}", "_path", "(", "file", ")", "{", "const", "el", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "el", ".", "href", "=", "file", ";", "return", "this", ".", "resolveUrl", "(", "`", "${", "encodeURI", "(", "el", ".", "href", ")", "}", "`", ")", ";", "}", "}" ]
An element for viewing PDF files.
[ "An", "element", "for", "viewing", "PDF", "files", "." ]
[ "/**\n * The path to the pdf file to display.\n */", "// get an absolute href" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
13
232
159
190d1fd1f562b9839976688c8f95f10af2e54592
tirthbharatiya/interview_questions
LC_52_n_queens_II.java
[ "MIT" ]
Java
Solution
/* The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. Example 1: Input: n = 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown. Example 2: Input: n = 1 Output: 1 Constraints: 1 <= n <= 9 */
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. Example 1: Input: n = 4 Output: 2 Explanation: There are two distinct solutions to the 4-queens puzzle as shown. Example 2: Input: n = 1 Output: 1
[ "The", "n", "-", "queens", "puzzle", "is", "the", "problem", "of", "placing", "n", "queens", "on", "an", "n", "x", "n", "chessboard", "such", "that", "no", "two", "queens", "attack", "each", "other", ".", "Given", "an", "integer", "n", "return", "the", "number", "of", "distinct", "solutions", "to", "the", "n", "-", "queens", "puzzle", ".", "Example", "1", ":", "Input", ":", "n", "=", "4", "Output", ":", "2", "Explanation", ":", "There", "are", "two", "distinct", "solutions", "to", "the", "4", "-", "queens", "puzzle", "as", "shown", ".", "Example", "2", ":", "Input", ":", "n", "=", "1", "Output", ":", "1" ]
class Solution { Set<String> solutions = new HashSet<>(); public int totalNQueens(int n) { solveNQueens(n, 0, new boolean[n][n]); return solutions.size(); } void solveNQueens(int n, int r, boolean[][] board) { if(r == n) { solutions.add(getSolution(board)); return; } if(r > n) { return; } for(int i=0; i<n; i++) { if(checkPossible(board, r, i)) { board[r][i] = true; solveNQueens(n, r+1, board); board[r][i] = false; } } } boolean checkPossible(boolean[][] board, int row, int col) { int n = board.length; for(int i=0; i<n; i++) { if(board[row][i] || board[i][col]) { return false; } if(row+i < n) { if(col+i < n && board[row+i][col+i]) { return false; } if(col-i >= 0 && board[row+i][col-i]) { return false; } } if(row-i >= 0) { if(col+i < n && board[row-i][col+i]) { return false; } if(col-i >= 0 && board[row-i][col-i]) { return false; } } } return true; } String getSolution(boolean[][] board) { int n = board.length; String sol = ""; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(board[i][j]) { sol += ','; } else { sol += '.'; } } } return sol; } }
[ "class", "Solution", "{", "Set", "<", "String", ">", "solutions", "=", "new", "HashSet", "<", ">", "(", ")", ";", "public", "int", "totalNQueens", "(", "int", "n", ")", "{", "solveNQueens", "(", "n", ",", "0", ",", "new", "boolean", "[", "n", "]", "[", "n", "]", ")", ";", "return", "solutions", ".", "size", "(", ")", ";", "}", "void", "solveNQueens", "(", "int", "n", ",", "int", "r", ",", "boolean", "[", "]", "[", "]", "board", ")", "{", "if", "(", "r", "==", "n", ")", "{", "solutions", ".", "add", "(", "getSolution", "(", "board", ")", ")", ";", "return", ";", "}", "if", "(", "r", ">", "n", ")", "{", "return", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "checkPossible", "(", "board", ",", "r", ",", "i", ")", ")", "{", "board", "[", "r", "]", "[", "i", "]", "=", "true", ";", "solveNQueens", "(", "n", ",", "r", "+", "1", ",", "board", ")", ";", "board", "[", "r", "]", "[", "i", "]", "=", "false", ";", "}", "}", "}", "boolean", "checkPossible", "(", "boolean", "[", "]", "[", "]", "board", ",", "int", "row", ",", "int", "col", ")", "{", "int", "n", "=", "board", ".", "length", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "board", "[", "row", "]", "[", "i", "]", "||", "board", "[", "i", "]", "[", "col", "]", ")", "{", "return", "false", ";", "}", "if", "(", "row", "+", "i", "<", "n", ")", "{", "if", "(", "col", "+", "i", "<", "n", "&&", "board", "[", "row", "+", "i", "]", "[", "col", "+", "i", "]", ")", "{", "return", "false", ";", "}", "if", "(", "col", "-", "i", ">=", "0", "&&", "board", "[", "row", "+", "i", "]", "[", "col", "-", "i", "]", ")", "{", "return", "false", ";", "}", "}", "if", "(", "row", "-", "i", ">=", "0", ")", "{", "if", "(", "col", "+", "i", "<", "n", "&&", "board", "[", "row", "-", "i", "]", "[", "col", "+", "i", "]", ")", "{", "return", "false", ";", "}", "if", "(", "col", "-", "i", ">=", "0", "&&", "board", "[", "row", "-", "i", "]", "[", "col", "-", "i", "]", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}", "String", "getSolution", "(", "boolean", "[", "]", "[", "]", "board", ")", "{", "int", "n", "=", "board", ".", "length", ";", "String", "sol", "=", "\"", "\"", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "for", "(", "int", "j", "=", "0", ";", "j", "<", "n", ";", "j", "++", ")", "{", "if", "(", "board", "[", "i", "]", "[", "j", "]", ")", "{", "sol", "+=", "','", ";", "}", "else", "{", "sol", "+=", "'.'", ";", "}", "}", "}", "return", "sol", ";", "}", "}" ]
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
[ "The", "n", "-", "queens", "puzzle", "is", "the", "problem", "of", "placing", "n", "queens", "on", "an", "n", "x", "n", "chessboard", "such", "that", "no", "two", "queens", "attack", "each", "other", "." ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
422
116
7f0f7161287f802aeee5f442883df21ae8886a25
intel-secl/verification-service
features/mtwilson-auto-refresh-trust/src/main/java/com/intel/mtwilson/plugin/AutoRefreshTrust.java
[ "BSD-3-Clause" ]
Java
AutoRefreshTrust
/** * Required configuration: * 1. enabled - true if the trust status of all hosts should be refreshed automatically * 2. max time in cache (seconds) - if a host trust record is older than this number it will be automatically refreshed * * This bean should be executed periodically (once every minute, or every 5 minutes) in order to automatically * refresh the trust status * * @author jbuhacoff */
Required configuration: 1. enabled - true if the trust status of all hosts should be refreshed automatically 2. max time in cache (seconds) - if a host trust record is older than this number it will be automatically refreshed This bean should be executed periodically (once every minute, or every 5 minutes) in order to automatically refresh the trust status @author jbuhacoff
[ "Required", "configuration", ":", "1", ".", "enabled", "-", "true", "if", "the", "trust", "status", "of", "all", "hosts", "should", "be", "refreshed", "automatically", "2", ".", "max", "time", "in", "cache", "(", "seconds", ")", "-", "if", "a", "host", "trust", "record", "is", "older", "than", "this", "number", "it", "will", "be", "automatically", "refreshed", "This", "bean", "should", "be", "executed", "periodically", "(", "once", "every", "minute", "or", "every", "5", "minutes", ")", "in", "order", "to", "automatically", "refresh", "the", "trust", "status", "@author", "jbuhacoff" ]
public class AutoRefreshTrust implements Runnable { private Logger log = LoggerFactory.getLogger(getClass()); private boolean enabled = true; private long maxCacheDuration = 5; // hour private TimeUnit maxCacheDurationUnits = TimeUnit.MINUTES; private int refreshTimeBeforeSamlExpiry = 300; // seconds private long interval = 120; // seconds private TimeUnit intervalUnits = TimeUnit.SECONDS; public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setMaxCacheDuration(long maxCacheDuration) { this.maxCacheDuration = maxCacheDuration; } public void setMaxCacheDurationUnits(TimeUnit maxCacheDurationUnits) { this.maxCacheDurationUnits = maxCacheDurationUnits; } public void setInterval(long interval) { this.interval = interval; } public void setIntervalUnits(TimeUnit intervalUnits) { this.intervalUnits = intervalUnits; } private volatile boolean running; public AutoRefreshTrust(long interval, TimeUnit intervalUnits) { this.interval = interval; this.intervalUnits = intervalUnits; } public void cancel() { running = false; } @Override public void run() { running = true; while (running) { // make a list of hosts whose last trust status check is more than max cache duration ago List<String> hostsToRefresh = findHostIdsWithExpiredCache(); if (hostsToRefresh != null && hostsToRefresh.size() > 0) { List<String> hostListForFlavorVerifyQueue = new HostRepository().filterHostsAlreadyInQueue(hostsToRefresh, true); // update host status of all the hosts to be added to flavor-verify queue new HostResource().updateHostStatusList(hostListForFlavorVerifyQueue, QUEUE, null); //add all the hosts with expired saml to queue new HostResource().addHostsToFlavorVerifyQueue(hostListForFlavorVerifyQueue, true); log.info("AutoRefreshTrust completed for {} hosts.", hostsToRefresh.size()); } else { log.info("No hosts for bulk refresh"); } if (!running) { break; } try { log.trace("Auto refresh thread would sleep for {} seconds.", TimeUnit.SECONDS.convert(interval, intervalUnits)); Thread.sleep(TimeUnit.MILLISECONDS.convert(interval, intervalUnits)); } catch (InterruptedException ex) { log.info("AutoRefreshTrust: Error during waiting for the next process: {}", ex.getMessage()); } } } public List<String> findHostIdsWithExpiredCache() { try { return My.jpa().mwReport().findHostsWithExpiredCache(refreshTimeBeforeSamlExpiry); } catch (Exception ex) { log.error("AutoRefreshTrust:findHostnamesWithExpiredCache - Error during retrieval of hosts with expired cache.", ex); return null; } } public static class ExpiredHostStatus { String hostname; Date lastChecked; // alwasys more than maxCacheDuration ago... } }
[ "public", "class", "AutoRefreshTrust", "implements", "Runnable", "{", "private", "Logger", "log", "=", "LoggerFactory", ".", "getLogger", "(", "getClass", "(", ")", ")", ";", "private", "boolean", "enabled", "=", "true", ";", "private", "long", "maxCacheDuration", "=", "5", ";", "private", "TimeUnit", "maxCacheDurationUnits", "=", "TimeUnit", ".", "MINUTES", ";", "private", "int", "refreshTimeBeforeSamlExpiry", "=", "300", ";", "private", "long", "interval", "=", "120", ";", "private", "TimeUnit", "intervalUnits", "=", "TimeUnit", ".", "SECONDS", ";", "public", "void", "setEnabled", "(", "boolean", "enabled", ")", "{", "this", ".", "enabled", "=", "enabled", ";", "}", "public", "void", "setMaxCacheDuration", "(", "long", "maxCacheDuration", ")", "{", "this", ".", "maxCacheDuration", "=", "maxCacheDuration", ";", "}", "public", "void", "setMaxCacheDurationUnits", "(", "TimeUnit", "maxCacheDurationUnits", ")", "{", "this", ".", "maxCacheDurationUnits", "=", "maxCacheDurationUnits", ";", "}", "public", "void", "setInterval", "(", "long", "interval", ")", "{", "this", ".", "interval", "=", "interval", ";", "}", "public", "void", "setIntervalUnits", "(", "TimeUnit", "intervalUnits", ")", "{", "this", ".", "intervalUnits", "=", "intervalUnits", ";", "}", "private", "volatile", "boolean", "running", ";", "public", "AutoRefreshTrust", "(", "long", "interval", ",", "TimeUnit", "intervalUnits", ")", "{", "this", ".", "interval", "=", "interval", ";", "this", ".", "intervalUnits", "=", "intervalUnits", ";", "}", "public", "void", "cancel", "(", ")", "{", "running", "=", "false", ";", "}", "@", "Override", "public", "void", "run", "(", ")", "{", "running", "=", "true", ";", "while", "(", "running", ")", "{", "List", "<", "String", ">", "hostsToRefresh", "=", "findHostIdsWithExpiredCache", "(", ")", ";", "if", "(", "hostsToRefresh", "!=", "null", "&&", "hostsToRefresh", ".", "size", "(", ")", ">", "0", ")", "{", "List", "<", "String", ">", "hostListForFlavorVerifyQueue", "=", "new", "HostRepository", "(", ")", ".", "filterHostsAlreadyInQueue", "(", "hostsToRefresh", ",", "true", ")", ";", "new", "HostResource", "(", ")", ".", "updateHostStatusList", "(", "hostListForFlavorVerifyQueue", ",", "QUEUE", ",", "null", ")", ";", "new", "HostResource", "(", ")", ".", "addHostsToFlavorVerifyQueue", "(", "hostListForFlavorVerifyQueue", ",", "true", ")", ";", "log", ".", "info", "(", "\"", "AutoRefreshTrust completed for {} hosts.", "\"", ",", "hostsToRefresh", ".", "size", "(", ")", ")", ";", "}", "else", "{", "log", ".", "info", "(", "\"", "No hosts for bulk refresh", "\"", ")", ";", "}", "if", "(", "!", "running", ")", "{", "break", ";", "}", "try", "{", "log", ".", "trace", "(", "\"", "Auto refresh thread would sleep for {} seconds.", "\"", ",", "TimeUnit", ".", "SECONDS", ".", "convert", "(", "interval", ",", "intervalUnits", ")", ")", ";", "Thread", ".", "sleep", "(", "TimeUnit", ".", "MILLISECONDS", ".", "convert", "(", "interval", ",", "intervalUnits", ")", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "log", ".", "info", "(", "\"", "AutoRefreshTrust: Error during waiting for the next process: {}", "\"", ",", "ex", ".", "getMessage", "(", ")", ")", ";", "}", "}", "}", "public", "List", "<", "String", ">", "findHostIdsWithExpiredCache", "(", ")", "{", "try", "{", "return", "My", ".", "jpa", "(", ")", ".", "mwReport", "(", ")", ".", "findHostsWithExpiredCache", "(", "refreshTimeBeforeSamlExpiry", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "log", ".", "error", "(", "\"", "AutoRefreshTrust:findHostnamesWithExpiredCache - Error during retrieval of hosts with expired cache.", "\"", ",", "ex", ")", ";", "return", "null", ";", "}", "}", "public", "static", "class", "ExpiredHostStatus", "{", "String", "hostname", ";", "Date", "lastChecked", ";", "}", "}" ]
Required configuration: 1. enabled - true if the trust status of all hosts should be refreshed automatically 2. max time in cache (seconds) - if a host trust record is older than this number it will be automatically refreshed
[ "Required", "configuration", ":", "1", ".", "enabled", "-", "true", "if", "the", "trust", "status", "of", "all", "hosts", "should", "be", "refreshed", "automatically", "2", ".", "max", "time", "in", "cache", "(", "seconds", ")", "-", "if", "a", "host", "trust", "record", "is", "older", "than", "this", "number", "it", "will", "be", "automatically", "refreshed" ]
[ "// hour", "// seconds", "// seconds", "// make a list of hosts whose last trust status check is more than max cache duration ago", "// update host status of all the hosts to be added to flavor-verify queue", "//add all the hosts with expired saml to queue", "// alwasys more than maxCacheDuration ago..." ]
[ { "param": "Runnable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "Runnable", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
646
94
05efb60e6c17b6b2297db768f0f862eb37e62320
JamesCao2048/BlizzardData
Corpus/aspectj/5987.java
[ "MIT" ]
Java
AjctestsAdapter
/* * Adapt Harness tests to JUnit driver. This renders suite files as TestSuite * and AjcTest as TestCase. When run, aborts are reported as error and fails as * failures, with all messages stuffed into the one JUnit exception message. * Test options are supported, but no harness options. The TestSuite * implementation prevents us from re-running tests. In the Eclipse JUnit test * runner, the tests display hierarchically and with annotations and with * messages. You can stop the tests, but not traverse to the source or re-run * the test. */
Adapt Harness tests to JUnit driver. This renders suite files as TestSuite and AjcTest as TestCase. When run, aborts are reported as error and fails as failures, with all messages stuffed into the one JUnit exception message. Test options are supported, but no harness options. The TestSuite implementation prevents us from re-running tests. In the Eclipse JUnit test runner, the tests display hierarchically and with annotations and with messages. You can stop the tests, but not traverse to the source or re-run the test.
[ "Adapt", "Harness", "tests", "to", "JUnit", "driver", ".", "This", "renders", "suite", "files", "as", "TestSuite", "and", "AjcTest", "as", "TestCase", ".", "When", "run", "aborts", "are", "reported", "as", "error", "and", "fails", "as", "failures", "with", "all", "messages", "stuffed", "into", "the", "one", "JUnit", "exception", "message", ".", "Test", "options", "are", "supported", "but", "no", "harness", "options", ".", "The", "TestSuite", "implementation", "prevents", "us", "from", "re", "-", "running", "tests", ".", "In", "the", "Eclipse", "JUnit", "test", "runner", "the", "tests", "display", "hierarchically", "and", "with", "annotations", "and", "with", "messages", ".", "You", "can", "stop", "the", "tests", "but", "not", "traverse", "to", "the", "source", "or", "re", "-", "run", "the", "test", "." ]
public class AjctestsAdapter extends TestSuite { public static final String VERBOSE_NAME = AjctestsAdapter.class.getName() + ".VERBOSE"; private static final boolean VERBOSE = HarnessJUnitUtil .readBooleanSystemProperty(VERBOSE_NAME); /** * Factory to make and populate suite without options. * * @param suitePath * the String path to a harness suite file * @return AjctestJUnitSuite populated with tests */ public static AjctestsAdapter make(String suitePath) { return make(suitePath, null); } /** * Factory to make and populate suite * * @param suitePath * the String path to a harness suite file * @param options * the String[] options to use when creating tests * @return AjctestJUnitSuite populated with tests */ public static AjctestsAdapter make(String suitePath, String[] options) { AjctestsAdapter result = new AjctestsAdapter(suitePath, options); AjcTest.Spec[] tests = AjcTest.Suite.getTests(result.getSpec()); if (VERBOSE) { log("loading " + tests.length + " tests in " + suitePath); } for (int i = 0; i < tests.length; i++) { AjcTest.Spec ajcTest = tests[i]; result.addTest(new AjcTestSpecAsTest(ajcTest, result)); } return result; } private static void log(String message) { System.err.println(message); System.err.flush(); } private final String suitePath; private final String[] options; private AjcTest.Suite.Spec spec; private Runner runner; private Validator validator; private IMessageHolder holder; private Sandbox sandbox; private File suiteDir; private String name; private AjctestsAdapter(String suitePath, String[] options) { this.suitePath = suitePath; String[] opts = new String[0]; if (!HarnessJUnitUtil.isEmpty(options)) { opts = new String[options.length]; System.arraycopy(options, 0, opts, 0, opts.length); } this.options = opts; } public void addTest(Test test) { if (!(test instanceof AjcTestSpecAsTest)) { String m = "expecting AjcTestSpecAsTest, got " + (null == test ? "null test" : test.getClass().getName() + ": " + test); throw new IllegalArgumentException(m); } super.addTest(test); } public void addTestSuite(Class testClass) { throw new Error("unimplemented"); } public String getName() { if (null == name) { name = HarnessJUnitUtil.cleanTestName(suitePath + Arrays.asList(options)); } return name; } /** * Callback from test to run it using suite-wide holder, etc. The caller is * responsible for calling result.startTest(test) and result.endTest(test); * * @param test * the AjcTestSpecAsTest to run * @param result * the TestResult for any result messages (may be null) */ protected void runTest(AjcTestSpecAsTest test, TestResult result) { final Runner runner = getRunner(); final Sandbox sandbox = getSandbox(); final Validator validator = getValidator(); int numIncomplete = 0; final RunStatus status = new RunStatus(new MessageHandler(), runner); status.setIdentifier(test.toString()); try { IMessageHolder holder = getHolder(); holder.clearMessages(); IRunIterator steps = test.spec.makeRunIterator(sandbox, validator); if (0 < holder.numMessages(IMessage.ERROR, true)) { MessageUtil.handleAll(status, holder, IMessage.INFO, true, false); } else { runner.runIterator(steps, status, null); } if (steps instanceof RunSpecIterator) { numIncomplete = ((RunSpecIterator) steps).getNumIncomplete(); } } finally { try { // reportResult handles null TestResult HarnessJUnitUtil .reportResult(null, status, test, numIncomplete); } finally { validator.deleteTempFiles(true); } } } private File getSuiteDir() { if (null == suiteDir) { File file = new File(suitePath); file = file.getParentFile(); if (null == file) { file = new File("."); } suiteDir = file; } return suiteDir; } private Validator getValidator() { if (null == validator) { validator = new Validator(getHolder()); // XXX lock if keepTemp? } return validator; } private Runner getRunner() { if (null == runner) { runner = new Runner(); } return runner; } private IMessageHolder getHolder() { if (null == holder) { holder = new MessageHandler(); } return holder; } private AjcTest.Suite.Spec getSpec() { if (null == spec) { IMessageHolder holder = getHolder(); spec = HarnessJUnitUtil.getSuiteSpec(suitePath, options, getHolder()); if (VERBOSE && holder.hasAnyMessage(null, true)) { MessageUtil.print(System.err, holder, "skip ", MessageUtil.MESSAGE_MOST); } holder.clearMessages(); } return spec; } private Sandbox getSandbox() { if (null == sandbox) { sandbox = new Sandbox(spec.getSuiteDirFile(), getValidator()); } return sandbox; } /** * Wrap AjcTest.Spec for lookup by description * * @author wes */ public static class SpecTests { private static final HashMap TESTS = new HashMap(); // private static void putSpecTestsFor(String id, SpecTests tests) { // TESTS.put(id, tests); // } private static SpecTests getSpecTestsFor(String id) { SpecTests result = (SpecTests) TESTS.get(id); if (null == result) { throw new Error("no tests found for " + id); } return result; } // ------------------------------------ final AjctestsAdapter mAjctestsAdapter; private final Map mDescriptionToAjcTestSpec; // ------------------------------------ private SpecTests(AjctestsAdapter ajctestsAdapter, AjcTest.Spec[] tests) { mAjctestsAdapter = ajctestsAdapter; Map map = new HashMap(); for (int i = 0; i < tests.length; i++) { map.put(tests[i].getDescription(), tests[i]); } mDescriptionToAjcTestSpec = Collections.unmodifiableMap(map); } /** * @param description * the String description of the test * @throws IllegalArgumentException * if testName is not found */ protected void runTest(String description) { AjcTest.Spec spec = getSpec(description); AjctestsAdapter.AjcTestSpecAsTest ajcTestAsSpec = new AjctestsAdapter.AjcTestSpecAsTest( spec, mAjctestsAdapter); // runTest handles null TestResult mAjctestsAdapter.runTest(ajcTestAsSpec, null); } /** * @param description * the String description of the test * @throws IllegalArgumentException * if testName is not found */ private AjcTest.Spec getSpec(String description) { AjcTest.Spec spec = (AjcTest.Spec) mDescriptionToAjcTestSpec .get(description); if (null == spec) { throw new IllegalArgumentException("no test for " + description); } return spec; } /** * makeUsingTestClass(..) extends this to create TestCase with * test_{name} for each test case. */ public static class TestClass extends TestCase { public TestClass() { } private SpecTests mTests; /** * Called by code generated in makeUsingTestClass(..) * * @param description * the String identifier of the test stored in SpecTests * mTests. * @throws Error * on first and later uses if getTestsFor() returns * null. */ public final void runTest(String description) { if (null == mTests) { String classname = getClass().getName(); mTests = getSpecTestsFor(classname); } mTests.runTest(description); } } } /** Wrap AjcTest.Spec as a TestCase. Run by delegation to suite */ private static class AjcTestSpecAsTest extends TestCase implements HarnessJUnitUtil.IHasAjcSpec { // this could implement Test, but Ant batchtest fails to pull name final String name; final AjcTest.Spec spec; AjctestsAdapter suite; AjcTestSpecAsTest(AjcTest.Spec spec, AjctestsAdapter suite) { super(HarnessJUnitUtil.cleanTestName(spec.getDescription())); this.name = HarnessJUnitUtil.cleanTestName(spec.getDescription()); this.suite = suite; this.spec = spec; spec.setSuiteDir(suite.getSuiteDir()); } public int countTestCases() { return 1; } public AjcTest.Spec getAjcTestSpec() { return spec; } public void run(TestResult result) { if (null == suite) { throw new Error("need to re-init"); } try { AjState.FORCE_INCREMENTAL_DURING_TESTING = true; result.startTest(this); suite.runTest(this, result); } finally { result.endTest(this); suite = null; AjState.FORCE_INCREMENTAL_DURING_TESTING = false; } } public String getName() { return name; } public String toString() { return name; } } }
[ "public", "class", "AjctestsAdapter", "extends", "TestSuite", "{", "public", "static", "final", "String", "VERBOSE_NAME", "=", "AjctestsAdapter", ".", "class", ".", "getName", "(", ")", "+", "\"", ".VERBOSE", "\"", ";", "private", "static", "final", "boolean", "VERBOSE", "=", "HarnessJUnitUtil", ".", "readBooleanSystemProperty", "(", "VERBOSE_NAME", ")", ";", "/**\n * Factory to make and populate suite without options.\n * \n * @param suitePath\n * the String path to a harness suite file\n * @return AjctestJUnitSuite populated with tests\n */", "public", "static", "AjctestsAdapter", "make", "(", "String", "suitePath", ")", "{", "return", "make", "(", "suitePath", ",", "null", ")", ";", "}", "/**\n * Factory to make and populate suite\n * \n * @param suitePath\n * the String path to a harness suite file\n * @param options\n * the String[] options to use when creating tests\n * @return AjctestJUnitSuite populated with tests\n */", "public", "static", "AjctestsAdapter", "make", "(", "String", "suitePath", ",", "String", "[", "]", "options", ")", "{", "AjctestsAdapter", "result", "=", "new", "AjctestsAdapter", "(", "suitePath", ",", "options", ")", ";", "AjcTest", ".", "Spec", "[", "]", "tests", "=", "AjcTest", ".", "Suite", ".", "getTests", "(", "result", ".", "getSpec", "(", ")", ")", ";", "if", "(", "VERBOSE", ")", "{", "log", "(", "\"", "loading ", "\"", "+", "tests", ".", "length", "+", "\"", " tests in ", "\"", "+", "suitePath", ")", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tests", ".", "length", ";", "i", "++", ")", "{", "AjcTest", ".", "Spec", "ajcTest", "=", "tests", "[", "i", "]", ";", "result", ".", "addTest", "(", "new", "AjcTestSpecAsTest", "(", "ajcTest", ",", "result", ")", ")", ";", "}", "return", "result", ";", "}", "private", "static", "void", "log", "(", "String", "message", ")", "{", "System", ".", "err", ".", "println", "(", "message", ")", ";", "System", ".", "err", ".", "flush", "(", ")", ";", "}", "private", "final", "String", "suitePath", ";", "private", "final", "String", "[", "]", "options", ";", "private", "AjcTest", ".", "Suite", ".", "Spec", "spec", ";", "private", "Runner", "runner", ";", "private", "Validator", "validator", ";", "private", "IMessageHolder", "holder", ";", "private", "Sandbox", "sandbox", ";", "private", "File", "suiteDir", ";", "private", "String", "name", ";", "private", "AjctestsAdapter", "(", "String", "suitePath", ",", "String", "[", "]", "options", ")", "{", "this", ".", "suitePath", "=", "suitePath", ";", "String", "[", "]", "opts", "=", "new", "String", "[", "0", "]", ";", "if", "(", "!", "HarnessJUnitUtil", ".", "isEmpty", "(", "options", ")", ")", "{", "opts", "=", "new", "String", "[", "options", ".", "length", "]", ";", "System", ".", "arraycopy", "(", "options", ",", "0", ",", "opts", ",", "0", ",", "opts", ".", "length", ")", ";", "}", "this", ".", "options", "=", "opts", ";", "}", "public", "void", "addTest", "(", "Test", "test", ")", "{", "if", "(", "!", "(", "test", "instanceof", "AjcTestSpecAsTest", ")", ")", "{", "String", "m", "=", "\"", "expecting AjcTestSpecAsTest, got ", "\"", "+", "(", "null", "==", "test", "?", "\"", "null test", "\"", ":", "test", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\"", ": ", "\"", "+", "test", ")", ";", "throw", "new", "IllegalArgumentException", "(", "m", ")", ";", "}", "super", ".", "addTest", "(", "test", ")", ";", "}", "public", "void", "addTestSuite", "(", "Class", "testClass", ")", "{", "throw", "new", "Error", "(", "\"", "unimplemented", "\"", ")", ";", "}", "public", "String", "getName", "(", ")", "{", "if", "(", "null", "==", "name", ")", "{", "name", "=", "HarnessJUnitUtil", ".", "cleanTestName", "(", "suitePath", "+", "Arrays", ".", "asList", "(", "options", ")", ")", ";", "}", "return", "name", ";", "}", "/**\n * Callback from test to run it using suite-wide holder, etc. The caller is\n * responsible for calling result.startTest(test) and result.endTest(test);\n * \n * @param test\n * the AjcTestSpecAsTest to run\n * @param result\n * the TestResult for any result messages (may be null)\n */", "protected", "void", "runTest", "(", "AjcTestSpecAsTest", "test", ",", "TestResult", "result", ")", "{", "final", "Runner", "runner", "=", "getRunner", "(", ")", ";", "final", "Sandbox", "sandbox", "=", "getSandbox", "(", ")", ";", "final", "Validator", "validator", "=", "getValidator", "(", ")", ";", "int", "numIncomplete", "=", "0", ";", "final", "RunStatus", "status", "=", "new", "RunStatus", "(", "new", "MessageHandler", "(", ")", ",", "runner", ")", ";", "status", ".", "setIdentifier", "(", "test", ".", "toString", "(", ")", ")", ";", "try", "{", "IMessageHolder", "holder", "=", "getHolder", "(", ")", ";", "holder", ".", "clearMessages", "(", ")", ";", "IRunIterator", "steps", "=", "test", ".", "spec", ".", "makeRunIterator", "(", "sandbox", ",", "validator", ")", ";", "if", "(", "0", "<", "holder", ".", "numMessages", "(", "IMessage", ".", "ERROR", ",", "true", ")", ")", "{", "MessageUtil", ".", "handleAll", "(", "status", ",", "holder", ",", "IMessage", ".", "INFO", ",", "true", ",", "false", ")", ";", "}", "else", "{", "runner", ".", "runIterator", "(", "steps", ",", "status", ",", "null", ")", ";", "}", "if", "(", "steps", "instanceof", "RunSpecIterator", ")", "{", "numIncomplete", "=", "(", "(", "RunSpecIterator", ")", "steps", ")", ".", "getNumIncomplete", "(", ")", ";", "}", "}", "finally", "{", "try", "{", "HarnessJUnitUtil", ".", "reportResult", "(", "null", ",", "status", ",", "test", ",", "numIncomplete", ")", ";", "}", "finally", "{", "validator", ".", "deleteTempFiles", "(", "true", ")", ";", "}", "}", "}", "private", "File", "getSuiteDir", "(", ")", "{", "if", "(", "null", "==", "suiteDir", ")", "{", "File", "file", "=", "new", "File", "(", "suitePath", ")", ";", "file", "=", "file", ".", "getParentFile", "(", ")", ";", "if", "(", "null", "==", "file", ")", "{", "file", "=", "new", "File", "(", "\"", ".", "\"", ")", ";", "}", "suiteDir", "=", "file", ";", "}", "return", "suiteDir", ";", "}", "private", "Validator", "getValidator", "(", ")", "{", "if", "(", "null", "==", "validator", ")", "{", "validator", "=", "new", "Validator", "(", "getHolder", "(", ")", ")", ";", "}", "return", "validator", ";", "}", "private", "Runner", "getRunner", "(", ")", "{", "if", "(", "null", "==", "runner", ")", "{", "runner", "=", "new", "Runner", "(", ")", ";", "}", "return", "runner", ";", "}", "private", "IMessageHolder", "getHolder", "(", ")", "{", "if", "(", "null", "==", "holder", ")", "{", "holder", "=", "new", "MessageHandler", "(", ")", ";", "}", "return", "holder", ";", "}", "private", "AjcTest", ".", "Suite", ".", "Spec", "getSpec", "(", ")", "{", "if", "(", "null", "==", "spec", ")", "{", "IMessageHolder", "holder", "=", "getHolder", "(", ")", ";", "spec", "=", "HarnessJUnitUtil", ".", "getSuiteSpec", "(", "suitePath", ",", "options", ",", "getHolder", "(", ")", ")", ";", "if", "(", "VERBOSE", "&&", "holder", ".", "hasAnyMessage", "(", "null", ",", "true", ")", ")", "{", "MessageUtil", ".", "print", "(", "System", ".", "err", ",", "holder", ",", "\"", "skip ", "\"", ",", "MessageUtil", ".", "MESSAGE_MOST", ")", ";", "}", "holder", ".", "clearMessages", "(", ")", ";", "}", "return", "spec", ";", "}", "private", "Sandbox", "getSandbox", "(", ")", "{", "if", "(", "null", "==", "sandbox", ")", "{", "sandbox", "=", "new", "Sandbox", "(", "spec", ".", "getSuiteDirFile", "(", ")", ",", "getValidator", "(", ")", ")", ";", "}", "return", "sandbox", ";", "}", "/**\n * Wrap AjcTest.Spec for lookup by description\n * \n * @author wes\n */", "public", "static", "class", "SpecTests", "{", "private", "static", "final", "HashMap", "TESTS", "=", "new", "HashMap", "(", ")", ";", "private", "static", "SpecTests", "getSpecTestsFor", "(", "String", "id", ")", "{", "SpecTests", "result", "=", "(", "SpecTests", ")", "TESTS", ".", "get", "(", "id", ")", ";", "if", "(", "null", "==", "result", ")", "{", "throw", "new", "Error", "(", "\"", "no tests found for ", "\"", "+", "id", ")", ";", "}", "return", "result", ";", "}", "final", "AjctestsAdapter", "mAjctestsAdapter", ";", "private", "final", "Map", "mDescriptionToAjcTestSpec", ";", "private", "SpecTests", "(", "AjctestsAdapter", "ajctestsAdapter", ",", "AjcTest", ".", "Spec", "[", "]", "tests", ")", "{", "mAjctestsAdapter", "=", "ajctestsAdapter", ";", "Map", "map", "=", "new", "HashMap", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "tests", ".", "length", ";", "i", "++", ")", "{", "map", ".", "put", "(", "tests", "[", "i", "]", ".", "getDescription", "(", ")", ",", "tests", "[", "i", "]", ")", ";", "}", "mDescriptionToAjcTestSpec", "=", "Collections", ".", "unmodifiableMap", "(", "map", ")", ";", "}", "/**\n * @param description\n * the String description of the test\n * @throws IllegalArgumentException\n * if testName is not found\n */", "protected", "void", "runTest", "(", "String", "description", ")", "{", "AjcTest", ".", "Spec", "spec", "=", "getSpec", "(", "description", ")", ";", "AjctestsAdapter", ".", "AjcTestSpecAsTest", "ajcTestAsSpec", "=", "new", "AjctestsAdapter", ".", "AjcTestSpecAsTest", "(", "spec", ",", "mAjctestsAdapter", ")", ";", "mAjctestsAdapter", ".", "runTest", "(", "ajcTestAsSpec", ",", "null", ")", ";", "}", "/**\n * @param description\n * the String description of the test\n * @throws IllegalArgumentException\n * if testName is not found\n */", "private", "AjcTest", ".", "Spec", "getSpec", "(", "String", "description", ")", "{", "AjcTest", ".", "Spec", "spec", "=", "(", "AjcTest", ".", "Spec", ")", "mDescriptionToAjcTestSpec", ".", "get", "(", "description", ")", ";", "if", "(", "null", "==", "spec", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"", "no test for ", "\"", "+", "description", ")", ";", "}", "return", "spec", ";", "}", "/**\n * makeUsingTestClass(..) extends this to create TestCase with\n * test_{name} for each test case.\n */", "public", "static", "class", "TestClass", "extends", "TestCase", "{", "public", "TestClass", "(", ")", "{", "}", "private", "SpecTests", "mTests", ";", "/**\n * Called by code generated in makeUsingTestClass(..)\n * \n * @param description\n * the String identifier of the test stored in SpecTests\n * mTests.\n * @throws Error\n * on first and later uses if getTestsFor() returns\n * null.\n */", "public", "final", "void", "runTest", "(", "String", "description", ")", "{", "if", "(", "null", "==", "mTests", ")", "{", "String", "classname", "=", "getClass", "(", ")", ".", "getName", "(", ")", ";", "mTests", "=", "getSpecTestsFor", "(", "classname", ")", ";", "}", "mTests", ".", "runTest", "(", "description", ")", ";", "}", "}", "}", "/** Wrap AjcTest.Spec as a TestCase. Run by delegation to suite */", "private", "static", "class", "AjcTestSpecAsTest", "extends", "TestCase", "implements", "HarnessJUnitUtil", ".", "IHasAjcSpec", "{", "final", "String", "name", ";", "final", "AjcTest", ".", "Spec", "spec", ";", "AjctestsAdapter", "suite", ";", "AjcTestSpecAsTest", "(", "AjcTest", ".", "Spec", "spec", ",", "AjctestsAdapter", "suite", ")", "{", "super", "(", "HarnessJUnitUtil", ".", "cleanTestName", "(", "spec", ".", "getDescription", "(", ")", ")", ")", ";", "this", ".", "name", "=", "HarnessJUnitUtil", ".", "cleanTestName", "(", "spec", ".", "getDescription", "(", ")", ")", ";", "this", ".", "suite", "=", "suite", ";", "this", ".", "spec", "=", "spec", ";", "spec", ".", "setSuiteDir", "(", "suite", ".", "getSuiteDir", "(", ")", ")", ";", "}", "public", "int", "countTestCases", "(", ")", "{", "return", "1", ";", "}", "public", "AjcTest", ".", "Spec", "getAjcTestSpec", "(", ")", "{", "return", "spec", ";", "}", "public", "void", "run", "(", "TestResult", "result", ")", "{", "if", "(", "null", "==", "suite", ")", "{", "throw", "new", "Error", "(", "\"", "need to re-init", "\"", ")", ";", "}", "try", "{", "AjState", ".", "FORCE_INCREMENTAL_DURING_TESTING", "=", "true", ";", "result", ".", "startTest", "(", "this", ")", ";", "suite", ".", "runTest", "(", "this", ",", "result", ")", ";", "}", "finally", "{", "result", ".", "endTest", "(", "this", ")", ";", "suite", "=", "null", ";", "AjState", ".", "FORCE_INCREMENTAL_DURING_TESTING", "=", "false", ";", "}", "}", "public", "String", "getName", "(", ")", "{", "return", "name", ";", "}", "public", "String", "toString", "(", ")", "{", "return", "name", ";", "}", "}", "}" ]
Adapt Harness tests to JUnit driver.
[ "Adapt", "Harness", "tests", "to", "JUnit", "driver", "." ]
[ "// reportResult handles null TestResult", "// XXX lock if keepTemp?", "// private static void putSpecTestsFor(String id, SpecTests tests) {", "// TESTS.put(id, tests);", "// }", "// ------------------------------------", "// ------------------------------------", "// runTest handles null TestResult", "// this could implement Test, but Ant batchtest fails to pull name" ]
[ { "param": "TestSuite", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "TestSuite", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
17
2,179
124
ae49aa50dad7ad6ae820ba39546e029e1f366cfc
elephantrobotics-joey/marsai
ai/action/sound/mp3player.py
[ "Apache-2.0" ]
Python
MP3PlayClass
003-comfortableCat - meow quick 003 009-fierceCat - meow quick 010-sleepingCat - meow long 005-happyCat - meow long 006-hurryCat - purr 002-angrymoreCat - angry 008-painCat - angry 004-pitifulCat - ha~
006-hurryCat - purr 002-angrymoreCat - angry 008-painCat - angry 004-pitifulCat - ha~
[ "006", "-", "hurryCat", "-", "purr", "002", "-", "angrymoreCat", "-", "angry", "008", "-", "painCat", "-", "angry", "004", "-", "pitifulCat", "-", "ha~" ]
class MP3PlayClass: def __init__(self): GPIO.setmode(GPIO.BCM) self.IOlist = [5, 6, 13, 19, 26] for i in range(5): GPIO.setup(self.IOlist[i], GPIO.OUT) ''' 003-comfortableCat - meow quick 003 009-fierceCat - meow quick 010-sleepingCat - meow long 005-happyCat - meow long 006-hurryCat - purr 002-angrymoreCat - angry 008-painCat - angry 004-pitifulCat - ha~ ''' def setplayer(self, audio_Num): for i in range(5): if audio_Num & 1 == 1: GPIO.output(self.IOlist[i], GPIO.LOW) else: GPIO.output(self.IOlist[i], GPIO.HIGH) audio_Num >>= 1 ai.actionplanner.ActionPlanner.sleep(0.05) for i in range(5): GPIO.output(self.IOlist[i], GPIO.HIGH) # sounds def angry(self, intensity = 0): # intensity can be 0,1 angry_mp3_ls = [2,8] angry_mp3_index = angry_mp3_ls[intensity] self.setplayer(angry_mp3_index) ai.actionplanner.ActionPlanner.sleep(angry_td) def purr(self, intensity = 0): # intensity can be 0,1 purr_mp3_index = 6 purr_times = 1 + intensity for i in purr_times: self.setplayer(purr_mp3_index) ai.actionplanner.ActionPlanner.sleep(purr_td) def meow(self,intensity = 0, tp ='quick',): meow_mp3_index = [] if tp == 'quick': meow_mp3_index = [9,3] else: # long meow_mp3_index = [10,5] i = int(np.random.random()*2) # choice 2 self.setplayer(meow_mp3_index[i]) ai.actionplanner.ActionPlanner.sleep(meow_td) def ha(self, intensity= 0): ha_mp3_index = 4 self.setplayer(ha_mp3_index) ai.actionplanner.ActionPlanner.sleep(ha_td)
[ "class", "MP3PlayClass", ":", "def", "__init__", "(", "self", ")", ":", "GPIO", ".", "setmode", "(", "GPIO", ".", "BCM", ")", "self", ".", "IOlist", "=", "[", "5", ",", "6", ",", "13", ",", "19", ",", "26", "]", "for", "i", "in", "range", "(", "5", ")", ":", "GPIO", ".", "setup", "(", "self", ".", "IOlist", "[", "i", "]", ",", "GPIO", ".", "OUT", ")", "def", "setplayer", "(", "self", ",", "audio_Num", ")", ":", "for", "i", "in", "range", "(", "5", ")", ":", "if", "audio_Num", "&", "1", "==", "1", ":", "GPIO", ".", "output", "(", "self", ".", "IOlist", "[", "i", "]", ",", "GPIO", ".", "LOW", ")", "else", ":", "GPIO", ".", "output", "(", "self", ".", "IOlist", "[", "i", "]", ",", "GPIO", ".", "HIGH", ")", "audio_Num", ">>=", "1", "ai", ".", "actionplanner", ".", "ActionPlanner", ".", "sleep", "(", "0.05", ")", "for", "i", "in", "range", "(", "5", ")", ":", "GPIO", ".", "output", "(", "self", ".", "IOlist", "[", "i", "]", ",", "GPIO", ".", "HIGH", ")", "def", "angry", "(", "self", ",", "intensity", "=", "0", ")", ":", "angry_mp3_ls", "=", "[", "2", ",", "8", "]", "angry_mp3_index", "=", "angry_mp3_ls", "[", "intensity", "]", "self", ".", "setplayer", "(", "angry_mp3_index", ")", "ai", ".", "actionplanner", ".", "ActionPlanner", ".", "sleep", "(", "angry_td", ")", "def", "purr", "(", "self", ",", "intensity", "=", "0", ")", ":", "purr_mp3_index", "=", "6", "purr_times", "=", "1", "+", "intensity", "for", "i", "in", "purr_times", ":", "self", ".", "setplayer", "(", "purr_mp3_index", ")", "ai", ".", "actionplanner", ".", "ActionPlanner", ".", "sleep", "(", "purr_td", ")", "def", "meow", "(", "self", ",", "intensity", "=", "0", ",", "tp", "=", "'quick'", ",", ")", ":", "meow_mp3_index", "=", "[", "]", "if", "tp", "==", "'quick'", ":", "meow_mp3_index", "=", "[", "9", ",", "3", "]", "else", ":", "meow_mp3_index", "=", "[", "10", ",", "5", "]", "i", "=", "int", "(", "np", ".", "random", ".", "random", "(", ")", "*", "2", ")", "self", ".", "setplayer", "(", "meow_mp3_index", "[", "i", "]", ")", "ai", ".", "actionplanner", ".", "ActionPlanner", ".", "sleep", "(", "meow_td", ")", "def", "ha", "(", "self", ",", "intensity", "=", "0", ")", ":", "ha_mp3_index", "=", "4", "self", ".", "setplayer", "(", "ha_mp3_index", ")", "ai", ".", "actionplanner", ".", "ActionPlanner", ".", "sleep", "(", "ha_td", ")" ]
003-comfortableCat - meow quick 003 009-fierceCat - meow quick 010-sleepingCat - meow long 005-happyCat - meow long
[ "003", "-", "comfortableCat", "-", "meow", "quick", "003", "009", "-", "fierceCat", "-", "meow", "quick", "010", "-", "sleepingCat", "-", "meow", "long", "005", "-", "happyCat", "-", "meow", "long" ]
[ "'''\r\n 003-comfortableCat - meow quick 003\r\n 009-fierceCat - meow quick \r\n 010-sleepingCat - meow long\r\n 005-happyCat - meow long\r\n\r\n 006-hurryCat - purr\r\n\r\n 002-angrymoreCat - angry \r\n 008-painCat - angry\r\n\r\n 004-pitifulCat - ha~\r\n '''", "# sounds\r", "# intensity can be 0,1\r", "# intensity can be 0,1\r", "# long\r", "# choice 2\r" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
567
117
9dc2b3e0661b65f8740ae50982a57e9ac4cd548c
ML-SolInvictus/modified-MWDF
MWDF Project/Dwarf Fortress/hack/scripts/deterioratecorpses.rb
[ "MIT" ]
Ruby
DeteriorateCorpses
# Make corpse parts decay and vanish over time deterioratecorpses ================== Somewhere between a "mod" and a "fps booster", with a small impact on vanilla gameplay. In long running forts, especially evil biomes, you end up with a lot of toes, teeth, fingers, and limbs scattered all over the place. Various corpses from various sieges, stray kitten corpses, probably some heads. Basically, your map will look like a giant pile of assorted body parts, all of which individually eat up a small part of your FPS, which collectively eat up quite a bit. In addition, this script also targets various butchery byproducts. Enjoying your thriving animal industry? Your FPS does not. Those thousands of skulls, bones, hooves, and wool eat up precious FPS that could be used to kill goblins and elves. Whose corpses will also get destroyed by the script to kill more goblins and elves. This script causes all of those to rot away into nothing after several months. Usage: ``deterioratecorpses (start|stop)``
Make corpse parts decay and vanish over time deterioratecorpses Somewhere between a "mod" and a "fps booster", with a small impact on vanilla gameplay. In long running forts, especially evil biomes, you end up with a lot of toes, teeth, fingers, and limbs scattered all over the place. Various corpses from various sieges, stray kitten corpses, probably some heads. Basically, your map will look like a giant pile of assorted body parts, all of which individually eat up a small part of your FPS, which collectively eat up quite a bit. In addition, this script also targets various butchery byproducts. Enjoying your thriving animal industry. Your FPS does not. Those thousands of skulls, bones, hooves, and wool eat up precious FPS that could be used to kill goblins and elves. Whose corpses will also get destroyed by the script to kill more goblins and elves. This script causes all of those to rot away into nothing after several months. ``deterioratecorpses (start|stop)``
[ "Make", "corpse", "parts", "decay", "and", "vanish", "over", "time", "deterioratecorpses", "Somewhere", "between", "a", "\"", "mod", "\"", "and", "a", "\"", "fps", "booster", "\"", "with", "a", "small", "impact", "on", "vanilla", "gameplay", ".", "In", "long", "running", "forts", "especially", "evil", "biomes", "you", "end", "up", "with", "a", "lot", "of", "toes", "teeth", "fingers", "and", "limbs", "scattered", "all", "over", "the", "place", ".", "Various", "corpses", "from", "various", "sieges", "stray", "kitten", "corpses", "probably", "some", "heads", ".", "Basically", "your", "map", "will", "look", "like", "a", "giant", "pile", "of", "assorted", "body", "parts", "all", "of", "which", "individually", "eat", "up", "a", "small", "part", "of", "your", "FPS", "which", "collectively", "eat", "up", "quite", "a", "bit", ".", "In", "addition", "this", "script", "also", "targets", "various", "butchery", "byproducts", ".", "Enjoying", "your", "thriving", "animal", "industry", ".", "Your", "FPS", "does", "not", ".", "Those", "thousands", "of", "skulls", "bones", "hooves", "and", "wool", "eat", "up", "precious", "FPS", "that", "could", "be", "used", "to", "kill", "goblins", "and", "elves", ".", "Whose", "corpses", "will", "also", "get", "destroyed", "by", "the", "script", "to", "kill", "more", "goblins", "and", "elves", ".", "This", "script", "causes", "all", "of", "those", "to", "rot", "away", "into", "nothing", "after", "several", "months", ".", "`", "`", "deterioratecorpses", "(", "start|stop", ")", "`", "`" ]
class DeteriorateCorpses def initialize end def process return false unless @running df.world.items.other[:ANY_CORPSE].each { |i| if (i.flags.dead_dwarf == false) i.wear_timer += 1 if (i.wear_timer > 24 + rand(8)) i.wear_timer = 0 i.wear += 1 end if (i.wear > 3) i.flags.garbage_collect = true end end } df.world.items.other[:REMAINS].each { |i| if (i.flags.dead_dwarf == false) i.wear_timer += 1 if (i.wear_timer > 6) i.wear_timer = 0 i.wear += 1 end if (i.wear > 3) i.flags.garbage_collect = true end end } end def start @onupdate = df.onupdate_register('deterioratecorpses', 1200, 1200) { process } @running = true puts "Deterioration of body parts commencing..." end def stop df.onupdate_unregister(@onupdate) @running = false end def status @running ? 'Running.' : 'Stopped.' end end
[ "class", "DeteriorateCorpses", "def", "initialize", "end", "def", "process", "return", "false", "unless", "@running", "df", ".", "world", ".", "items", ".", "other", "[", ":ANY_CORPSE", "]", ".", "each", "{", "|", "i", "|", "if", "(", "i", ".", "flags", ".", "dead_dwarf", "==", "false", ")", "i", ".", "wear_timer", "+=", "1", "if", "(", "i", ".", "wear_timer", ">", "24", "+", "rand", "(", "8", ")", ")", "i", ".", "wear_timer", "=", "0", "i", ".", "wear", "+=", "1", "end", "if", "(", "i", ".", "wear", ">", "3", ")", "i", ".", "flags", ".", "garbage_collect", "=", "true", "end", "end", "}", "df", ".", "world", ".", "items", ".", "other", "[", ":REMAINS", "]", ".", "each", "{", "|", "i", "|", "if", "(", "i", ".", "flags", ".", "dead_dwarf", "==", "false", ")", "i", ".", "wear_timer", "+=", "1", "if", "(", "i", ".", "wear_timer", ">", "6", ")", "i", ".", "wear_timer", "=", "0", "i", ".", "wear", "+=", "1", "end", "if", "(", "i", ".", "wear", ">", "3", ")", "i", ".", "flags", ".", "garbage_collect", "=", "true", "end", "end", "}", "end", "def", "start", "@onupdate", "=", "df", ".", "onupdate_register", "(", "'deterioratecorpses'", ",", "1200", ",", "1200", ")", "{", "process", "}", "@running", "=", "true", "puts", "\"Deterioration of body parts commencing...\"", "end", "def", "stop", "df", ".", "onupdate_unregister", "(", "@onupdate", ")", "@running", "=", "false", "end", "def", "status", "@running", "?", "'Running.'", ":", "'Stopped.'", "end", "end" ]
Make corpse parts decay and vanish over time deterioratecorpses
[ "Make", "corpse", "parts", "decay", "and", "vanish", "over", "time", "deterioratecorpses" ]
[]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
16
326
241
3daf0565d7a32a8c6b12bef6dcc25e75b52bcd76
roryprimrose/Neovolve.Toolkit
Neovolve.Toolkit.Workflow/Properties/Resources.Designer.cs
[ "MIT" ]
C#
Resources
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Neovolve.Toolkit.Workflow.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string Activity_NoChildActivitiesDefined { get { return ResourceManager.GetString("Activity_NoChildActivitiesDefined", resourceCulture); } } internal static string BusinessFailureEvaluator_CodeNotBound { get { return ResourceManager.GetString("BusinessFailureEvaluator_CodeNotBound", resourceCulture); } } internal static string BusinessFailureEvaluator_ConflictingFailureInformationBound { get { return ResourceManager.GetString("BusinessFailureEvaluator_ConflictingFailureInformationBound", resourceCulture); } } internal static string BusinessFailureEvaluator_DescriptionNotBound { get { return ResourceManager.GetString("BusinessFailureEvaluator_DescriptionNotBound", resourceCulture); } } internal static string BusinessFailureEvaluator_FailureInformationNotBound { get { return ResourceManager.GetString("BusinessFailureEvaluator_FailureInformationNotBound", resourceCulture); } } internal static string BusinessFailureEvaluator_NoConditionBoundWarning { get { return ResourceManager.GetString("BusinessFailureEvaluator_NoConditionBoundWarning", resourceCulture); } } internal static string BusinessFailureScope_EvaluatorWithDifferentTypeDetected { get { return ResourceManager.GetString("BusinessFailureScope_EvaluatorWithDifferentTypeDetected", resourceCulture); } } internal static string ExecuteBookmark_InvalidBookmarkValueTypeProvided { get { return ResourceManager.GetString("ExecuteBookmark_InvalidBookmarkValueTypeProvided", resourceCulture); } } internal static string OperationIdentityInspector_NullBodyFailure { get { return ResourceManager.GetString("OperationIdentityInspector_NullBodyFailure", resourceCulture); } } internal static string OperationIdentityInspector_UnexpectedIdentityType { get { return ResourceManager.GetString("OperationIdentityInspector_UnexpectedIdentityType", resourceCulture); } } internal static string Retry_InvalidExceptionType { get { return ResourceManager.GetString("Retry_InvalidExceptionType", resourceCulture); } } internal static string SystemFailureEvaluator_MessageConstructorNotFound { get { return ResourceManager.GetString("SystemFailureEvaluator_MessageConstructorNotFound", resourceCulture); } } internal static string SystemFailureEvaluator_ParamNameConstructorNotFound { get { return ResourceManager.GetString("SystemFailureEvaluator_ParamNameConstructorNotFound", resourceCulture); } } internal static string SystemFailureEvaluator_ParamNameMessageConstructorNotFound { get { return ResourceManager.GetString("SystemFailureEvaluator_ParamNameMessageConstructorNotFound", resourceCulture); } } internal static string WorkflowExtensionBehavior_InvalidServiceHostType { get { return ResourceManager.GetString("WorkflowExtensionBehavior_InvalidServiceHostType", resourceCulture); } } internal static string WorkflowExtensionElement_ExtensionTypeNotLoaded { get { return ResourceManager.GetString("WorkflowExtensionElement_ExtensionTypeNotLoaded", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "4.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "internal", "class", "Resources", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "Resources", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Neovolve.Toolkit.Workflow.Properties.Resources", "\"", ",", "typeof", "(", "Resources", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "internal", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "internal", "static", "string", "Activity_NoChildActivitiesDefined", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Activity_NoChildActivitiesDefined", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "BusinessFailureEvaluator_CodeNotBound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BusinessFailureEvaluator_CodeNotBound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "BusinessFailureEvaluator_ConflictingFailureInformationBound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BusinessFailureEvaluator_ConflictingFailureInformationBound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "BusinessFailureEvaluator_DescriptionNotBound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BusinessFailureEvaluator_DescriptionNotBound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "BusinessFailureEvaluator_FailureInformationNotBound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BusinessFailureEvaluator_FailureInformationNotBound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "BusinessFailureEvaluator_NoConditionBoundWarning", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BusinessFailureEvaluator_NoConditionBoundWarning", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "BusinessFailureScope_EvaluatorWithDifferentTypeDetected", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "BusinessFailureScope_EvaluatorWithDifferentTypeDetected", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "ExecuteBookmark_InvalidBookmarkValueTypeProvided", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ExecuteBookmark_InvalidBookmarkValueTypeProvided", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationIdentityInspector_NullBodyFailure", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationIdentityInspector_NullBodyFailure", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "OperationIdentityInspector_UnexpectedIdentityType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OperationIdentityInspector_UnexpectedIdentityType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "Retry_InvalidExceptionType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Retry_InvalidExceptionType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SystemFailureEvaluator_MessageConstructorNotFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SystemFailureEvaluator_MessageConstructorNotFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SystemFailureEvaluator_ParamNameConstructorNotFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SystemFailureEvaluator_ParamNameConstructorNotFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "SystemFailureEvaluator_ParamNameMessageConstructorNotFound", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SystemFailureEvaluator_ParamNameMessageConstructorNotFound", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "WorkflowExtensionBehavior_InvalidServiceHostType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WorkflowExtensionBehavior_InvalidServiceHostType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "internal", "static", "string", "WorkflowExtensionElement_ExtensionTypeNotLoaded", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "WorkflowExtensionElement_ExtensionTypeNotLoaded", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to No child activities are defined.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A Code value must be provided if a Description value is provided..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Only the Failure property must be specified or Code and Description, not both..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A Description value must be provided if a Code value is provided..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Either the Failure property must be specified or Code and Description..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to This activity will always throw an exception with no Condition property set..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Scope contains a BusinessFailureEvaluator defined by a different generic type. BusinessFailureEvaluators with a different generic type will throw failures directly rather than collating the failures in this scope activity..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A value of type {0} was expected but a value of {1} was provided..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A Receive activity is required as a child activity..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The operation identity type expected was {0} but the identity type {1} was detected..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The type specified does not derived from System.Exception..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The exception type &apos;{0}&apos; does not define a constructor with parameter of message..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The exception type &apos;{0}&apos; does not define a constructor with parameter of paramName..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The exception type &apos;{0}&apos; does not define a constructor with parameters of paramName and message..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invalid ServiceHost type. Workflow extension can only be added to a WorkflowServiceHost instance..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The workflow extension type &apos;{0}&apos; could not be loaded..", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
828
84
470f9a821ad0fd008f9e9918430a5569c9ae5e32
osoco/better-ways-of-thinking-about-software
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/lms/djangoapps/discussion/notification_prefs/views.py
[ "MIT" ]
Python
UsernameCipher
A transformation of a username to/from an opaque token The purpose of the token is to make one-click unsubscribe links that don't require the user to log in. To prevent users from unsubscribing other users, we must ensure the token cannot be computed by anyone who has this source code. The token must also be embeddable in a URL. Thus, we take the following steps to encode (and do the inverse to decode): 1. Pad the UTF-8 encoding of the username with PKCS#7 padding to match the AES block length 2. Generate a random AES block length initialization vector 3. Use AES-256 (with a hash of settings.SECRET_KEY as the encryption key) in CBC mode to encrypt the username 4. Prepend the IV to the encrypted value to allow for initialization of the decryption cipher 5. base64url encode the result
A transformation of a username to/from an opaque token The purpose of the token is to make one-click unsubscribe links that don't require the user to log in. To prevent users from unsubscribing other users, we must ensure the token cannot be computed by anyone who has this source code. The token must also be embeddable in a URL. Thus, we take the following steps to encode (and do the inverse to decode): 1. Pad the UTF-8 encoding of the username with PKCS#7 padding to match the AES block length 2. Generate a random AES block length initialization vector 3. Use AES-256 (with a hash of settings.SECRET_KEY as the encryption key) in CBC mode to encrypt the username 4. Prepend the IV to the encrypted value to allow for initialization of the decryption cipher 5. base64url encode the result
[ "A", "transformation", "of", "a", "username", "to", "/", "from", "an", "opaque", "token", "The", "purpose", "of", "the", "token", "is", "to", "make", "one", "-", "click", "unsubscribe", "links", "that", "don", "'", "t", "require", "the", "user", "to", "log", "in", ".", "To", "prevent", "users", "from", "unsubscribing", "other", "users", "we", "must", "ensure", "the", "token", "cannot", "be", "computed", "by", "anyone", "who", "has", "this", "source", "code", ".", "The", "token", "must", "also", "be", "embeddable", "in", "a", "URL", ".", "Thus", "we", "take", "the", "following", "steps", "to", "encode", "(", "and", "do", "the", "inverse", "to", "decode", ")", ":", "1", ".", "Pad", "the", "UTF", "-", "8", "encoding", "of", "the", "username", "with", "PKCS#7", "padding", "to", "match", "the", "AES", "block", "length", "2", ".", "Generate", "a", "random", "AES", "block", "length", "initialization", "vector", "3", ".", "Use", "AES", "-", "256", "(", "with", "a", "hash", "of", "settings", ".", "SECRET_KEY", "as", "the", "encryption", "key", ")", "in", "CBC", "mode", "to", "encrypt", "the", "username", "4", ".", "Prepend", "the", "IV", "to", "the", "encrypted", "value", "to", "allow", "for", "initialization", "of", "the", "decryption", "cipher", "5", ".", "base64url", "encode", "the", "result" ]
class UsernameCipher: """ A transformation of a username to/from an opaque token The purpose of the token is to make one-click unsubscribe links that don't require the user to log in. To prevent users from unsubscribing other users, we must ensure the token cannot be computed by anyone who has this source code. The token must also be embeddable in a URL. Thus, we take the following steps to encode (and do the inverse to decode): 1. Pad the UTF-8 encoding of the username with PKCS#7 padding to match the AES block length 2. Generate a random AES block length initialization vector 3. Use AES-256 (with a hash of settings.SECRET_KEY as the encryption key) in CBC mode to encrypt the username 4. Prepend the IV to the encrypted value to allow for initialization of the decryption cipher 5. base64url encode the result """ @staticmethod def _get_aes_cipher(initialization_vector): hash_ = sha256() hash_.update(six.b(settings.SECRET_KEY)) return Cipher(AES(hash_.digest()), CBC(initialization_vector), backend=default_backend()) @staticmethod def encrypt(username): # lint-amnesty, pylint: disable=missing-function-docstring initialization_vector = os.urandom(AES_BLOCK_SIZE_BYTES) if not isinstance(initialization_vector, (bytes, bytearray)): initialization_vector = initialization_vector.encode('utf-8') aes_cipher = UsernameCipher._get_aes_cipher(initialization_vector) encryptor = aes_cipher.encryptor() padder = PKCS7(AES.block_size).padder() padded = padder.update(username.encode("utf-8")) + padder.finalize() return urlsafe_b64encode(initialization_vector + encryptor.update(padded) + encryptor.finalize()).decode() @staticmethod def decrypt(token): # lint-amnesty, pylint: disable=missing-function-docstring try: base64_decoded = urlsafe_b64decode(token) except (TypeError, Error): raise UsernameDecryptionException("base64url") # lint-amnesty, pylint: disable=raise-missing-from if len(base64_decoded) < AES_BLOCK_SIZE_BYTES: raise UsernameDecryptionException("initialization_vector") initialization_vector = base64_decoded[:AES_BLOCK_SIZE_BYTES] aes_encrypted = base64_decoded[AES_BLOCK_SIZE_BYTES:] aes_cipher = UsernameCipher._get_aes_cipher(initialization_vector) decryptor = aes_cipher.decryptor() unpadder = PKCS7(AES.block_size).unpadder() try: decrypted = decryptor.update(aes_encrypted) + decryptor.finalize() except ValueError: raise UsernameDecryptionException("aes") # lint-amnesty, pylint: disable=raise-missing-from try: unpadded = unpadder.update(decrypted) + unpadder.finalize() if len(unpadded) == 0: raise UsernameDecryptionException("padding") return unpadded except ValueError: raise UsernameDecryptionException("padding")
[ "class", "UsernameCipher", ":", "@", "staticmethod", "def", "_get_aes_cipher", "(", "initialization_vector", ")", ":", "hash_", "=", "sha256", "(", ")", "hash_", ".", "update", "(", "six", ".", "b", "(", "settings", ".", "SECRET_KEY", ")", ")", "return", "Cipher", "(", "AES", "(", "hash_", ".", "digest", "(", ")", ")", ",", "CBC", "(", "initialization_vector", ")", ",", "backend", "=", "default_backend", "(", ")", ")", "@", "staticmethod", "def", "encrypt", "(", "username", ")", ":", "initialization_vector", "=", "os", ".", "urandom", "(", "AES_BLOCK_SIZE_BYTES", ")", "if", "not", "isinstance", "(", "initialization_vector", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "initialization_vector", "=", "initialization_vector", ".", "encode", "(", "'utf-8'", ")", "aes_cipher", "=", "UsernameCipher", ".", "_get_aes_cipher", "(", "initialization_vector", ")", "encryptor", "=", "aes_cipher", ".", "encryptor", "(", ")", "padder", "=", "PKCS7", "(", "AES", ".", "block_size", ")", ".", "padder", "(", ")", "padded", "=", "padder", ".", "update", "(", "username", ".", "encode", "(", "\"utf-8\"", ")", ")", "+", "padder", ".", "finalize", "(", ")", "return", "urlsafe_b64encode", "(", "initialization_vector", "+", "encryptor", ".", "update", "(", "padded", ")", "+", "encryptor", ".", "finalize", "(", ")", ")", ".", "decode", "(", ")", "@", "staticmethod", "def", "decrypt", "(", "token", ")", ":", "try", ":", "base64_decoded", "=", "urlsafe_b64decode", "(", "token", ")", "except", "(", "TypeError", ",", "Error", ")", ":", "raise", "UsernameDecryptionException", "(", "\"base64url\"", ")", "if", "len", "(", "base64_decoded", ")", "<", "AES_BLOCK_SIZE_BYTES", ":", "raise", "UsernameDecryptionException", "(", "\"initialization_vector\"", ")", "initialization_vector", "=", "base64_decoded", "[", ":", "AES_BLOCK_SIZE_BYTES", "]", "aes_encrypted", "=", "base64_decoded", "[", "AES_BLOCK_SIZE_BYTES", ":", "]", "aes_cipher", "=", "UsernameCipher", ".", "_get_aes_cipher", "(", "initialization_vector", ")", "decryptor", "=", "aes_cipher", ".", "decryptor", "(", ")", "unpadder", "=", "PKCS7", "(", "AES", ".", "block_size", ")", ".", "unpadder", "(", ")", "try", ":", "decrypted", "=", "decryptor", ".", "update", "(", "aes_encrypted", ")", "+", "decryptor", ".", "finalize", "(", ")", "except", "ValueError", ":", "raise", "UsernameDecryptionException", "(", "\"aes\"", ")", "try", ":", "unpadded", "=", "unpadder", ".", "update", "(", "decrypted", ")", "+", "unpadder", ".", "finalize", "(", ")", "if", "len", "(", "unpadded", ")", "==", "0", ":", "raise", "UsernameDecryptionException", "(", "\"padding\"", ")", "return", "unpadded", "except", "ValueError", ":", "raise", "UsernameDecryptionException", "(", "\"padding\"", ")" ]
A transformation of a username to/from an opaque token The purpose of the token is to make one-click unsubscribe links that don't require the user to log in.
[ "A", "transformation", "of", "a", "username", "to", "/", "from", "an", "opaque", "token", "The", "purpose", "of", "the", "token", "is", "to", "make", "one", "-", "click", "unsubscribe", "links", "that", "don", "'", "t", "require", "the", "user", "to", "log", "in", "." ]
[ "\"\"\"\n A transformation of a username to/from an opaque token\n\n The purpose of the token is to make one-click unsubscribe links that don't\n require the user to log in. To prevent users from unsubscribing other users,\n we must ensure the token cannot be computed by anyone who has this\n source code. The token must also be embeddable in a URL.\n\n Thus, we take the following steps to encode (and do the inverse to decode):\n 1. Pad the UTF-8 encoding of the username with PKCS#7 padding to match the\n AES block length\n 2. Generate a random AES block length initialization vector\n 3. Use AES-256 (with a hash of settings.SECRET_KEY as the encryption key)\n in CBC mode to encrypt the username\n 4. Prepend the IV to the encrypted value to allow for initialization of the\n decryption cipher\n 5. base64url encode the result\n \"\"\"", "# lint-amnesty, pylint: disable=missing-function-docstring", "# lint-amnesty, pylint: disable=missing-function-docstring", "# lint-amnesty, pylint: disable=raise-missing-from", "# lint-amnesty, pylint: disable=raise-missing-from" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
15
690
208
03b637186731935f0ec90ca826b9a2fe35d77781
traDE4chor/ode
tasks/pomwithdependencies.rake
[ "Apache-2.0" ]
Ruby
Buildr
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with this # work for additional information regarding copyright ownership. The ASF # licenses this file to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License.
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 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.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", ".", "See", "the", "NOTICE", "file", "distributed", "with", "this", "work", "for", "additional", "information", "regarding", "copyright", "ownership", ".", "The", "ASF", "licenses", "this", "file", "to", "you", "under", "the", "Apache", "License", "Version", "2", ".", "0", "(", "the", "\"", "License", "\"", ")", ";", "you", "may", "not", "use", "this", "file", "except", "in", "compliance", "with", "the", "License", ".", "You", "may", "obtain", "a", "copy", "of", "the", "License", "at", "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", "." ]
module Buildr # # Module to add project dependencies to our artifact's pom files. # Inspired by BUILDR-486 and https://github.com/jvshahid/buildr-dependency-extensions. # module PomWithDependencies include Extension # We have to add the dependencies to the monkey patched POM before the dependencies are # changed in the compile, test and run after_define after_define(:compile) do |project| deps = [project.compile.dependencies.select {|dep| dep.respond_to?(:to_spec) && dep.respond_to?(:to_hash)}.map { |a| a.to_hash.merge(:scope => 'compile') }, project.test.dependencies.select {|dep| dep.respond_to?(:to_spec) && dep.respond_to?(:to_hash) && !project.compile.dependencies.include?(dep)}.map { |a| a.to_hash.merge(:scope => 'test') }, project.run.classpath.select {|dep| dep.respond_to?(:to_spec) && dep.respond_to?(:to_hash) && !project.compile.dependencies.include?(dep)}.map { |a| a.to_hash.merge(:scope => 'runtime') } ].flatten project.packages.each {|pack| pack.pom.dependencies = deps} end end module ActsAsArtifact # monkey patch Buildr's the pom xml generation def pom_xml Proc.new do xml = Builder::XmlMarkup.new(:indent=>2) xml.instruct! xml.project do xml.modelVersion '4.0.0' xml.groupId group xml.artifactId id xml.version version xml.classifier classifier if classifier unless @dependencies.nil? || @dependencies.empty? xml.dependencies do @dependencies.uniq.each do |art| xml.dependency do xml.groupId art[:group] xml.artifactId art[:id] xml.version art[:version] xml.classifier art[:classifier] if art.has_key? :classifier xml.scope art[:scope] if art.has_key? :scope end end end end end end end # make ActAsArtifac dependency aware def dependencies=(dependencies) @dependencies = dependencies end def dependencies @dependencies ||= POM.load(self).dependencies.map { |spec| artifact(spec) } if self.is_a? Artifact @dependencies ||= [] end end end
[ "module", "Buildr", "module", "PomWithDependencies", "include", "Extension", "after_define", "(", ":compile", ")", "do", "|", "project", "|", "deps", "=", "[", "project", ".", "compile", ".", "dependencies", ".", "select", "{", "|", "dep", "|", "dep", ".", "respond_to?", "(", ":to_spec", ")", "&&", "dep", ".", "respond_to?", "(", ":to_hash", ")", "}", ".", "map", "{", "|", "a", "|", "a", ".", "to_hash", ".", "merge", "(", ":scope", "=>", "'compile'", ")", "}", ",", "project", ".", "test", ".", "dependencies", ".", "select", "{", "|", "dep", "|", "dep", ".", "respond_to?", "(", ":to_spec", ")", "&&", "dep", ".", "respond_to?", "(", ":to_hash", ")", "&&", "!", "project", ".", "compile", ".", "dependencies", ".", "include?", "(", "dep", ")", "}", ".", "map", "{", "|", "a", "|", "a", ".", "to_hash", ".", "merge", "(", ":scope", "=>", "'test'", ")", "}", ",", "project", ".", "run", ".", "classpath", ".", "select", "{", "|", "dep", "|", "dep", ".", "respond_to?", "(", ":to_spec", ")", "&&", "dep", ".", "respond_to?", "(", ":to_hash", ")", "&&", "!", "project", ".", "compile", ".", "dependencies", ".", "include?", "(", "dep", ")", "}", ".", "map", "{", "|", "a", "|", "a", ".", "to_hash", ".", "merge", "(", ":scope", "=>", "'runtime'", ")", "}", "]", ".", "flatten", "project", ".", "packages", ".", "each", "{", "|", "pack", "|", "pack", ".", "pom", ".", "dependencies", "=", "deps", "}", "end", "end", "module", "ActsAsArtifact", "def", "pom_xml", "Proc", ".", "new", "do", "xml", "=", "Builder", "::", "XmlMarkup", ".", "new", "(", ":indent", "=>", "2", ")", "xml", ".", "instruct!", "xml", ".", "project", "do", "xml", ".", "modelVersion", "'4.0.0'", "xml", ".", "groupId", "group", "xml", ".", "artifactId", "id", "xml", ".", "version", "version", "xml", ".", "classifier", "classifier", "if", "classifier", "unless", "@dependencies", ".", "nil?", "||", "@dependencies", ".", "empty?", "xml", ".", "dependencies", "do", "@dependencies", ".", "uniq", ".", "each", "do", "|", "art", "|", "xml", ".", "dependency", "do", "xml", ".", "groupId", "art", "[", ":group", "]", "xml", ".", "artifactId", "art", "[", ":id", "]", "xml", ".", "version", "art", "[", ":version", "]", "xml", ".", "classifier", "art", "[", ":classifier", "]", "if", "art", ".", "has_key?", ":classifier", "xml", ".", "scope", "art", "[", ":scope", "]", "if", "art", ".", "has_key?", ":scope", "end", "end", "end", "end", "end", "end", "end", "def", "dependencies", "=", "(", "dependencies", ")", "@dependencies", "=", "dependencies", "end", "def", "dependencies", "@dependencies", "||=", "POM", ".", "load", "(", "self", ")", ".", "dependencies", ".", "map", "{", "|", "spec", "|", "artifact", "(", "spec", ")", "}", "if", "self", ".", "is_a?", "Artifact", "@dependencies", "||=", "[", "]", "end", "end", "end" ]
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.
[ "Licensed", "to", "the", "Apache", "Software", "Foundation", "(", "ASF", ")", "under", "one", "or", "more", "contributor", "license", "agreements", "." ]
[ "#", "# Module to add project dependencies to our artifact's pom files. ", "# Inspired by BUILDR-486 and https://github.com/jvshahid/buildr-dependency-extensions.", "#", "# We have to add the dependencies to the monkey patched POM before the dependencies are", "# changed in the compile, test and run after_define", "# monkey patch Buildr's the pom xml generation", "# make ActAsArtifac dependency aware" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
28
542
165
3cbac8cfef007c647cbfe9a3b0b58832d727cabe
ggagnaux/Sage300-SDK
resources/Sage300Resources/Sage.CA.SBS.ERP.Sage300.AR.Resources/Forms/InvoiceEntryResx.Designer.cs
[ "MIT" ]
C#
InvoiceEntryResx
/// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project.
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class InvoiceEntryResx { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal InvoiceEntryResx() { } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sage.CA.SBS.ERP.Sage300.AR.Resources.Forms.InvoiceEntryResx", typeof(InvoiceEntryResx).Assembly); resourceMan = temp; } return resourceMan; } } [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } public static string AccountDescription { get { return ResourceManager.GetString("AccountDescription", resourceCulture); } } public static string AgedTransactionsExceeds { get { return ResourceManager.GetString("AgedTransactionsExceeds", resourceCulture); } } public static string AmountDueC { get { return ResourceManager.GetString("AmountDueC", resourceCulture); } } public static string Apply { get { return ResourceManager.GetString("Apply", resourceCulture); } } public static string AR0032 { get { return ResourceManager.GetString("AR0032", resourceCulture); } } public static string AR0033 { get { return ResourceManager.GetString("AR0033", resourceCulture); } } public static string AR0034 { get { return ResourceManager.GetString("AR0034", resourceCulture); } } public static string AR0401 { get { return ResourceManager.GetString("AR0401", resourceCulture); } } public static string AR0402 { get { return ResourceManager.GetString("AR0402", resourceCulture); } } public static string CreateNewBatch { get { return ResourceManager.GetString("CreateNewBatch", resourceCulture); } } public static string CreateNewEntry { get { return ResourceManager.GetString("CreateNewEntry", resourceCulture); } } public static string CreditCheck { get { return ResourceManager.GetString("CreditCheck", resourceCulture); } } public static string CustCreditDayOverdue { get { return ResourceManager.GetString("CustCreditDayOverdue", resourceCulture); } } public static string CustCreditDaysOverdue { get { return ResourceManager.GetString("CustCreditDaysOverdue", resourceCulture); } } public static string CustomerAndShipmentAccounts { get { return ResourceManager.GetString("CustomerAndShipmentAccounts", resourceCulture); } } public static string CustomerCreditLimit { get { return ResourceManager.GetString("CustomerCreditLimit", resourceCulture); } } public static string DefaultDetailType { get { return ResourceManager.GetString("DefaultDetailType", resourceCulture); } } public static string DefaultFromInvoice { get { return ResourceManager.GetString("DefaultFromInvoice", resourceCulture); } } public static string DiscPercentage { get { return ResourceManager.GetString("DiscPercentage", resourceCulture); } } public static string Document { get { return ResourceManager.GetString("Document", resourceCulture); } } public static string Entity { get { return ResourceManager.GetString("Entity", resourceCulture); } } public static string EstimatedTax { get { return ResourceManager.GetString("EstimatedTax", resourceCulture); } } public static string EstimatedTaxAmount { get { return ResourceManager.GetString("EstimatedTaxAmount", resourceCulture); } } public static string InvalidSalesperson { get { return ResourceManager.GetString("InvalidSalesperson", resourceCulture); } } public static string InvoiceAmount { get { return ResourceManager.GetString("InvoiceAmount", resourceCulture); } } public static string InvoiceBatchInfoHeader { get { return ResourceManager.GetString("InvoiceBatchInfoHeader", resourceCulture); } } public static string InvoiceOptionalFieldsHeader { get { return ResourceManager.GetString("InvoiceOptionalFieldsHeader", resourceCulture); } } public static string InvoicePrinted { get { return ResourceManager.GetString("InvoicePrinted", resourceCulture); } } public static string LessDiscountC { get { return ResourceManager.GetString("LessDiscountC", resourceCulture); } } public static string LessEstTaxWithheld { get { return ResourceManager.GetString("LessEstTaxWithheld", resourceCulture); } } public static string LessPrepaymentC { get { return ResourceManager.GetString("LessPrepaymentC", resourceCulture); } } public static string LessRetainageC { get { return ResourceManager.GetString("LessRetainageC", resourceCulture); } } public static string NatAcctCreditLimit { get { return ResourceManager.GetString("NatAcctCreditLimit", resourceCulture); } } public static string NatCreditDayOverdue { get { return ResourceManager.GetString("NatCreditDayOverdue", resourceCulture); } } public static string NatCreditDaysOverdue { get { return ResourceManager.GetString("NatCreditDaysOverdue", resourceCulture); } } public static string NoPrepayments { get { return ResourceManager.GetString("NoPrepayments", resourceCulture); } } public static string OrigDocExchRate { get { return ResourceManager.GetString("OrigDocExchRate", resourceCulture); } } public static string PostInvoiceEntry { get { return ResourceManager.GetString("PostInvoiceEntry", resourceCulture); } } public static string PPDeleted { get { return ResourceManager.GetString("PPDeleted", resourceCulture); } } public static string Prepay { get { return ResourceManager.GetString("Prepay", resourceCulture); } } public static string PrepaymentAmount { get { return ResourceManager.GetString("PrepaymentAmount", resourceCulture); } } public static string PrintedEntry { get { return ResourceManager.GetString("PrintedEntry", resourceCulture); } } public static string QPrintedSuccessfully { get { return ResourceManager.GetString("QPrintedSuccessfully", resourceCulture); } } public static string RemainingAmount { get { return ResourceManager.GetString("RemainingAmount", resourceCulture); } } public static string Retainage { get { return ResourceManager.GetString("Retainage", resourceCulture); } } public static string RetainageExchangeRate { get { return ResourceManager.GetString("RetainageExchangeRate", resourceCulture); } } public static string RetainageRate { get { return ResourceManager.GetString("RetainageRate", resourceCulture); } } public static string ShipmentDetails { get { return ResourceManager.GetString("ShipmentDetails", resourceCulture); } } public static string SummaryBatch { get { return ResourceManager.GetString("SummaryBatch", resourceCulture); } } public static string Taxes { get { return ResourceManager.GetString("Taxes", resourceCulture); } } public static string TaxReportingDetails { get { return ResourceManager.GetString("TaxReportingDetails", resourceCulture); } } public static string Terms { get { return ResourceManager.GetString("Terms", resourceCulture); } } public static string TotalRetainageTax { get { return ResourceManager.GetString("TotalRetainageTax", resourceCulture); } } public static string TotalTaxAmount { get { return ResourceManager.GetString("TotalTaxAmount", resourceCulture); } } }
[ "[", "global", "::", "System", ".", "CodeDom", ".", "Compiler", ".", "GeneratedCodeAttribute", "(", "\"", "System.Resources.Tools.StronglyTypedResourceBuilder", "\"", ",", "\"", "15.0.0.0", "\"", ")", "]", "[", "global", "::", "System", ".", "Diagnostics", ".", "DebuggerNonUserCodeAttribute", "(", ")", "]", "[", "global", "::", "System", ".", "Runtime", ".", "CompilerServices", ".", "CompilerGeneratedAttribute", "(", ")", "]", "public", "class", "InvoiceEntryResx", "{", "private", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "resourceMan", ";", "private", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "resourceCulture", ";", "[", "global", "::", "System", ".", "Diagnostics", ".", "CodeAnalysis", ".", "SuppressMessageAttribute", "(", "\"", "Microsoft.Performance", "\"", ",", "\"", "CA1811:AvoidUncalledPrivateCode", "\"", ")", "]", "internal", "InvoiceEntryResx", "(", ")", "{", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "ResourceManager", "{", "get", "{", "if", "(", "object", ".", "ReferenceEquals", "(", "resourceMan", ",", "null", ")", ")", "{", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "temp", "=", "new", "global", "::", "System", ".", "Resources", ".", "ResourceManager", "(", "\"", "Sage.CA.SBS.ERP.Sage300.AR.Resources.Forms.InvoiceEntryResx", "\"", ",", "typeof", "(", "InvoiceEntryResx", ")", ".", "Assembly", ")", ";", "resourceMan", "=", "temp", ";", "}", "return", "resourceMan", ";", "}", "}", "[", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableAttribute", "(", "global", "::", "System", ".", "ComponentModel", ".", "EditorBrowsableState", ".", "Advanced", ")", "]", "public", "static", "global", "::", "System", ".", "Globalization", ".", "CultureInfo", "Culture", "{", "get", "{", "return", "resourceCulture", ";", "}", "set", "{", "resourceCulture", "=", "value", ";", "}", "}", "public", "static", "string", "AccountDescription", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AccountDescription", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AgedTransactionsExceeds", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AgedTransactionsExceeds", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AmountDueC", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AmountDueC", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Apply", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Apply", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AR0032", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AR0032", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AR0033", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AR0033", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AR0034", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AR0034", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AR0401", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AR0401", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "AR0402", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "AR0402", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CreateNewBatch", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CreateNewBatch", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CreateNewEntry", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CreateNewEntry", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CreditCheck", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CreditCheck", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CustCreditDayOverdue", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CustCreditDayOverdue", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CustCreditDaysOverdue", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CustCreditDaysOverdue", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CustomerAndShipmentAccounts", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CustomerAndShipmentAccounts", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "CustomerCreditLimit", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "CustomerCreditLimit", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DefaultDetailType", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DefaultDetailType", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DefaultFromInvoice", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DefaultFromInvoice", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "DiscPercentage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "DiscPercentage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Document", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Document", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Entity", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Entity", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EstimatedTax", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EstimatedTax", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "EstimatedTaxAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "EstimatedTaxAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InvalidSalesperson", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvalidSalesperson", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InvoiceAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvoiceAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InvoiceBatchInfoHeader", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvoiceBatchInfoHeader", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InvoiceOptionalFieldsHeader", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvoiceOptionalFieldsHeader", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "InvoicePrinted", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "InvoicePrinted", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "LessDiscountC", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "LessDiscountC", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "LessEstTaxWithheld", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "LessEstTaxWithheld", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "LessPrepaymentC", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "LessPrepaymentC", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "LessRetainageC", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "LessRetainageC", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NatAcctCreditLimit", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NatAcctCreditLimit", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NatCreditDayOverdue", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NatCreditDayOverdue", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NatCreditDaysOverdue", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NatCreditDaysOverdue", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "NoPrepayments", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "NoPrepayments", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "OrigDocExchRate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "OrigDocExchRate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PostInvoiceEntry", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PostInvoiceEntry", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PPDeleted", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PPDeleted", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Prepay", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Prepay", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PrepaymentAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PrepaymentAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "PrintedEntry", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "PrintedEntry", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "QPrintedSuccessfully", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "QPrintedSuccessfully", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RemainingAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RemainingAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Retainage", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Retainage", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RetainageExchangeRate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RetainageExchangeRate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "RetainageRate", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "RetainageRate", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "ShipmentDetails", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "ShipmentDetails", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "SummaryBatch", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "SummaryBatch", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Taxes", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Taxes", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "TaxReportingDetails", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TaxReportingDetails", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "Terms", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "Terms", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "TotalRetainageTax", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TotalRetainageTax", "\"", ",", "resourceCulture", ")", ";", "}", "}", "public", "static", "string", "TotalTaxAmount", "{", "get", "{", "return", "ResourceManager", ".", "GetString", "(", "\"", "TotalTaxAmount", "\"", ",", "resourceCulture", ")", ";", "}", "}", "}" ]
A strongly-typed resource class, for looking up localized strings, etc.
[ "A", "strongly", "-", "typed", "resource", "class", "for", "looking", "up", "localized", "strings", "etc", "." ]
[ "/// <summary>", "/// Returns the cached ResourceManager instance used by this class.", "/// </summary>", "/// <summary>", "/// Overrides the current thread's CurrentUICulture property for all", "/// resource lookups using this strongly typed resource class.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Account Description.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Aged Transactions Exceeds.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Amount Due:.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Project and Job Costing Apply Details.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice Details.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice Payment Schedules .", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice Detail Optional Fields.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice Optional Fields.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Create New Batch.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Create New Entry.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Credit Check.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The customer&apos;s total outstanding A/R balance that is {0} day or more overdue is {1}. This amount exceeds {2}..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The customer&apos;s total outstanding A/R balance that is {0} days or more overdue is {1}. This amount exceeds {2}..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Customer Details.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Customer Credit Limit.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Default Detail Type.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Default from Invoice.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Discount %.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Document.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A/R Invoice Entry.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to (Estimated Tax %1).", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Estimated Tax.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Salesperson code {0} is not defined in A/R Salespersons..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A/R Invoice Entry - Batch Information.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A/R Invoice Entry - Optional Fields.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Invoice Printed.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Less Discount:.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Less Estimated Tax Withheld.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Less Prepayment:.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Less Retainage:.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to National Account Credit Limit.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The national account&apos;s total outstanding A/R balance that is {0} day or more overdue is {1}. This amount exceeds {2}..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to The national account&apos;s total outstanding A/R balance that is {0} days or more overdue is {1}. This amount exceeds {2}..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to There are no prepayments for this Invoice..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Original Document Exchange Rate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to A/R Post Invoice Entry.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Prepayment for this invoice has been deleted..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Prepay....", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Prepayment Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to An invoice has been printed for entry {1}. The option to Allow Edit After Invoice Printed is not selected in A/R Options. You may view but cannot modify its contents..", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Was {0} printed successfully?.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Remaining Amount.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Retainage.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Apply-To Doc. Orig. Exch. Rate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Retainage Rate.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Shipment Details.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Batch Summary.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Taxes.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Tax Reporting Details.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Terms.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Total Retainage Tax.", "/// </summary>", "/// <summary>", "/// Looks up a localized string similar to Total Tax Amount.", "/// </summary>" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
false
17
1,790
84
25e33a38725031ef1c18550560665676da50d4f6
joelvh/tlaw
lib/tlaw/endpoint.rb
[ "MIT" ]
Ruby
Endpoint
# This class does all the hard work: actually calling some HTTP API # and processing responses. # # Each real API endpoint is this class descendant, defining its own # params and response processors. On each call small instance of this # class is created, {#call}-ed and dies as you don't need it anymore. # # Typically, you will neither create nor use endpoint descendants or # instances directly: # # * endpoint class definition is performed through {DSL} helpers, # * and then, containing namespace obtains `.<current_endpoint_name>()` # method, which is (almost) everything you need to know. #
This class does all the hard work: actually calling some HTTP API and processing responses. Each real API endpoint is this class descendant, defining its own params and response processors. On each call small instance of this class is created, {#call}-ed and dies as you don't need it anymore. Typically, you will neither create nor use endpoint descendants or instances directly. endpoint class definition is performed through {DSL} helpers, and then, containing namespace obtains `.()` method, which is (almost) everything you need to know.
[ "This", "class", "does", "all", "the", "hard", "work", ":", "actually", "calling", "some", "HTTP", "API", "and", "processing", "responses", ".", "Each", "real", "API", "endpoint", "is", "this", "class", "descendant", "defining", "its", "own", "params", "and", "response", "processors", ".", "On", "each", "call", "small", "instance", "of", "this", "class", "is", "created", "{", "#call", "}", "-", "ed", "and", "dies", "as", "you", "don", "'", "t", "need", "it", "anymore", ".", "Typically", "you", "will", "neither", "create", "nor", "use", "endpoint", "descendants", "or", "instances", "directly", ".", "endpoint", "class", "definition", "is", "performed", "through", "{", "DSL", "}", "helpers", "and", "then", "containing", "namespace", "obtains", "`", ".", "()", "`", "method", "which", "is", "(", "almost", ")", "everything", "you", "need", "to", "know", "." ]
class Endpoint < APIPath class << self # Inspects endpoint class prettily. # # Example: # # ```ruby # some_api.some_namespace.endpoints[:my_endpoint] # # => <SomeApi::SomeNamespace::MyEndpoint call-sequence: my_endpoint(param1, param2: nil), docs: .describe> # ``` def inspect "#<#{name || '(unnamed endpoint class)'}:" \ " call-sequence: #{symbol}(#{param_set.to_code}); docs: .describe>" end # @private def to_code "def #{to_method_definition}\n" \ " child(:#{symbol}, Endpoint).call({#{param_set.to_hash_code}})\n" \ 'end' end # @private def construct_template tpl = if query_string_params.empty? base_url else joiner = base_url.include?('?') ? '&' : '?' "#{base_url}{#{joiner}#{query_string_params.join(',')}}" end Addressable::Template.new(tpl) end # @private def process_response(response) response_processor.call(response) end private def query_string_params param_set.all_params.values.map(&:field).map(&:to_s) - Addressable::Template.new(base_url).keys end end attr_reader :url_template # Creates endpoint class (or descendant) instance. Typically, you # never use it directly. # # Params defined in parent namespace are passed here. # def initialize(**parent_params) super @client = Faraday.new do |faraday| faraday.use FaradayMiddleware::FollowRedirects faraday.adapter Faraday.default_adapter end @url_template = self.class.construct_template end # Does the real call to the API, with all params passed to this method # and to parent namespace. # # Typically, you don't use it directly, that's what called when you # do `some_namespace.endpoint_name(**params)`. # # @return [Hash,Array] Parsed, flattened and post-processed response # body. def call(**params) url = construct_url(**full_params(params)) self.class.process_response @client.get(url) rescue API::Error raise # Not catching in the next block rescue StandardError => e raise unless url raise API::Error, "#{e.class} at #{url}: #{e.message}" end def_delegators :object_class, :inspect, :describe private def full_params(**params) @parent_params.merge(params.reject { |_, v| v.nil? }) end def construct_url(**params) url_params = self.class.param_set.process(**params) @url_template .expand(url_params).normalize.to_s .split('?', 2) .yield_self { |url, param| [url.gsub('%2F', '/'), param] } .compact .join('?') end end
[ "class", "Endpoint", "<", "APIPath", "class", "<<", "self", "def", "inspect", "\"#<#{name || '(unnamed endpoint class)'}:\"", "\" call-sequence: #{symbol}(#{param_set.to_code}); docs: .describe>\"", "end", "def", "to_code", "\"def #{to_method_definition}\\n\"", "\" child(:#{symbol}, Endpoint).call({#{param_set.to_hash_code}})\\n\"", "'end'", "end", "def", "construct_template", "tpl", "=", "if", "query_string_params", ".", "empty?", "base_url", "else", "joiner", "=", "base_url", ".", "include?", "(", "'?'", ")", "?", "'&'", ":", "'?'", "\"#{base_url}{#{joiner}#{query_string_params.join(',')}}\"", "end", "Addressable", "::", "Template", ".", "new", "(", "tpl", ")", "end", "def", "process_response", "(", "response", ")", "response_processor", ".", "call", "(", "response", ")", "end", "private", "def", "query_string_params", "param_set", ".", "all_params", ".", "values", ".", "map", "(", "&", ":field", ")", ".", "map", "(", "&", ":to_s", ")", "-", "Addressable", "::", "Template", ".", "new", "(", "base_url", ")", ".", "keys", "end", "end", "attr_reader", ":url_template", "def", "initialize", "(", "**", "parent_params", ")", "super", "@client", "=", "Faraday", ".", "new", "do", "|", "faraday", "|", "faraday", ".", "use", "FaradayMiddleware", "::", "FollowRedirects", "faraday", ".", "adapter", "Faraday", ".", "default_adapter", "end", "@url_template", "=", "self", ".", "class", ".", "construct_template", "end", "def", "call", "(", "**", "params", ")", "url", "=", "construct_url", "(", "**", "full_params", "(", "params", ")", ")", "self", ".", "class", ".", "process_response", "@client", ".", "get", "(", "url", ")", "rescue", "API", "::", "Error", "raise", "rescue", "StandardError", "=>", "e", "raise", "unless", "url", "raise", "API", "::", "Error", ",", "\"#{e.class} at #{url}: #{e.message}\"", "end", "def_delegators", ":object_class", ",", ":inspect", ",", ":describe", "private", "def", "full_params", "(", "**", "params", ")", "@parent_params", ".", "merge", "(", "params", ".", "reject", "{", "|", "_", ",", "v", "|", "v", ".", "nil?", "}", ")", "end", "def", "construct_url", "(", "**", "params", ")", "url_params", "=", "self", ".", "class", ".", "param_set", ".", "process", "(", "**", "params", ")", "@url_template", ".", "expand", "(", "url_params", ")", ".", "normalize", ".", "to_s", ".", "split", "(", "'?'", ",", "2", ")", ".", "yield_self", "{", "|", "url", ",", "param", "|", "[", "url", ".", "gsub", "(", "'%2F'", ",", "'/'", ")", ",", "param", "]", "}", ".", "compact", ".", "join", "(", "'?'", ")", "end", "end" ]
This class does all the hard work: actually calling some HTTP API and processing responses.
[ "This", "class", "does", "all", "the", "hard", "work", ":", "actually", "calling", "some", "HTTP", "API", "and", "processing", "responses", "." ]
[ "# Inspects endpoint class prettily.", "#", "# Example:", "#", "# ```ruby", "# some_api.some_namespace.endpoints[:my_endpoint]", "# # => <SomeApi::SomeNamespace::MyEndpoint call-sequence: my_endpoint(param1, param2: nil), docs: .describe>", "# ```", "# @private", "# @private", "# @private", "# Creates endpoint class (or descendant) instance. Typically, you", "# never use it directly.", "#", "# Params defined in parent namespace are passed here.", "#", "# Does the real call to the API, with all params passed to this method", "# and to parent namespace.", "#", "# Typically, you don't use it directly, that's what called when you", "# do `some_namespace.endpoint_name(**params)`.", "#", "# @return [Hash,Array] Parsed, flattened and post-processed response", "# body.", "# Not catching in the next block" ]
[ { "param": "APIPath", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "APIPath", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
693
132
9ff850ac01783a378b241ff1681f502ee183a5b4
DigiByte-Core/digibytewallet-android
app/src/main/java/io/digibyte/presenter/customviews/BRDialogView.java
[ "MIT" ]
Java
BRDialogView
/** * BreadWallet * <p/> * Created by Mihail Gutan on <[email protected]> 3/15/17. * Copyright (c) 2017 breadwallet LLC * <p/> * 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: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * 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. */
BreadWallet Created by Mihail Gutan on 3/15/17. Copyright (c) 2017 breadwallet LLC 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.
[ "BreadWallet", "Created", "by", "Mihail", "Gutan", "on", "3", "/", "15", "/", "17", ".", "Copyright", "(", "c", ")", "2017", "breadwallet", "LLC", "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", "." ]
public class BRDialogView extends DialogFragment { private static final String TAG = BRDialogView.class.getName(); private String title = ""; private String message = ""; private String posButton = ""; private String negButton = ""; private BRDialogView.BROnClickListener posListener; private BRDialogView.BROnClickListener negListener; private DialogInterface.OnDismissListener dismissListener; private Button negativeButton; private LinearLayout buttonsLayout; private SpannableString spanMessage; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.bread_alert_dialog, null); TextView titleText = view.findViewById(R.id.dialog_title); TextView messageText = view.findViewById(R.id.dialog_text); Button positiveButton = view.findViewById(R.id.pos_button); negativeButton = view.findViewById(R.id.neg_button); buttonsLayout = view.findViewById(R.id.linearLayout3); titleText.setText(title); messageText.setText(message); if (spanMessage != null) { messageText.setText(spanMessage); messageText.setMovementMethod(LinkMovementMethod.getInstance()); } positiveButton.setText(posButton); positiveButton.setOnClickListener(v -> { if (posListener != null) posListener.onClick(BRDialogView.this); }); if (Utils.isNullOrEmpty(negButton)) { Log.e(TAG, "onCreateDialog: removing negative button"); buttonsLayout.removeView(negativeButton); buttonsLayout.requestLayout(); } negativeButton.setText(negButton); negativeButton.setOnClickListener(v -> { if (negListener != null) negListener.onClick(BRDialogView.this); }); builder.setView(view); Dialog dialog = builder.create(); dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); return dialog; } @Override public void onDestroyView() { super.onDestroyView(); //Because the callback is passed un-optimally, it's not view recreation safe especially //after activity recreation restoring from an activity saved state. Dismiss the dialog and //the user can just reinvoke it again by initiating the desired action try { dismissAllowingStateLoss(); } catch (IllegalStateException e) { Log.e(TAG, "onDestroyView: ", e); } } @Override public void onDismiss(DialogInterface dialog) { super.onDismiss(dialog); if (dismissListener != null) dismissListener.onDismiss(dialog); } public void setTitle(String title) { this.title = title; } public void setMessage(String message) { this.message = message; } public void setSpan(SpannableString message) { if (message == null) { BRReportsManager.reportBug(new NullPointerException("setSpan with null message")); return; } this.spanMessage = message; } public void setPosButton(@NonNull String posButton) { this.posButton = posButton; } public void setNegButton(String negButton) { this.negButton = negButton; } public void setPosListener(BRDialogView.BROnClickListener posListener) { this.posListener = posListener; } public void setNegListener(BRDialogView.BROnClickListener negListener) { this.negListener = negListener; } public void setDismissListener(DialogInterface.OnDismissListener dismissListener) { this.dismissListener = dismissListener; } public interface BROnClickListener { void onClick(BRDialogView brDialogView); } public void dismissWithAnimation() { try { dismissAllowingStateLoss(); } catch(IllegalArgumentException e) { Log.e(TAG, "dismissWithAnimation: ", e); } } }
[ "public", "class", "BRDialogView", "extends", "DialogFragment", "{", "private", "static", "final", "String", "TAG", "=", "BRDialogView", ".", "class", ".", "getName", "(", ")", ";", "private", "String", "title", "=", "\"", "\"", ";", "private", "String", "message", "=", "\"", "\"", ";", "private", "String", "posButton", "=", "\"", "\"", ";", "private", "String", "negButton", "=", "\"", "\"", ";", "private", "BRDialogView", ".", "BROnClickListener", "posListener", ";", "private", "BRDialogView", ".", "BROnClickListener", "negListener", ";", "private", "DialogInterface", ".", "OnDismissListener", "dismissListener", ";", "private", "Button", "negativeButton", ";", "private", "LinearLayout", "buttonsLayout", ";", "private", "SpannableString", "spanMessage", ";", "@", "Override", "public", "Dialog", "onCreateDialog", "(", "Bundle", "savedInstanceState", ")", "{", "AlertDialog", ".", "Builder", "builder", "=", "new", "AlertDialog", ".", "Builder", "(", "getActivity", "(", ")", ")", ";", "LayoutInflater", "inflater", "=", "getActivity", "(", ")", ".", "getLayoutInflater", "(", ")", ";", "View", "view", "=", "inflater", ".", "inflate", "(", "R", ".", "layout", ".", "bread_alert_dialog", ",", "null", ")", ";", "TextView", "titleText", "=", "view", ".", "findViewById", "(", "R", ".", "id", ".", "dialog_title", ")", ";", "TextView", "messageText", "=", "view", ".", "findViewById", "(", "R", ".", "id", ".", "dialog_text", ")", ";", "Button", "positiveButton", "=", "view", ".", "findViewById", "(", "R", ".", "id", ".", "pos_button", ")", ";", "negativeButton", "=", "view", ".", "findViewById", "(", "R", ".", "id", ".", "neg_button", ")", ";", "buttonsLayout", "=", "view", ".", "findViewById", "(", "R", ".", "id", ".", "linearLayout3", ")", ";", "titleText", ".", "setText", "(", "title", ")", ";", "messageText", ".", "setText", "(", "message", ")", ";", "if", "(", "spanMessage", "!=", "null", ")", "{", "messageText", ".", "setText", "(", "spanMessage", ")", ";", "messageText", ".", "setMovementMethod", "(", "LinkMovementMethod", ".", "getInstance", "(", ")", ")", ";", "}", "positiveButton", ".", "setText", "(", "posButton", ")", ";", "positiveButton", ".", "setOnClickListener", "(", "v", "->", "{", "if", "(", "posListener", "!=", "null", ")", "posListener", ".", "onClick", "(", "BRDialogView", ".", "this", ")", ";", "}", ")", ";", "if", "(", "Utils", ".", "isNullOrEmpty", "(", "negButton", ")", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "onCreateDialog: removing negative button", "\"", ")", ";", "buttonsLayout", ".", "removeView", "(", "negativeButton", ")", ";", "buttonsLayout", ".", "requestLayout", "(", ")", ";", "}", "negativeButton", ".", "setText", "(", "negButton", ")", ";", "negativeButton", ".", "setOnClickListener", "(", "v", "->", "{", "if", "(", "negListener", "!=", "null", ")", "negListener", ".", "onClick", "(", "BRDialogView", ".", "this", ")", ";", "}", ")", ";", "builder", ".", "setView", "(", "view", ")", ";", "Dialog", "dialog", "=", "builder", ".", "create", "(", ")", ";", "dialog", ".", "getWindow", "(", ")", ".", "setBackgroundDrawableResource", "(", "android", ".", "R", ".", "color", ".", "transparent", ")", ";", "return", "dialog", ";", "}", "@", "Override", "public", "void", "onDestroyView", "(", ")", "{", "super", ".", "onDestroyView", "(", ")", ";", "try", "{", "dismissAllowingStateLoss", "(", ")", ";", "}", "catch", "(", "IllegalStateException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "onDestroyView: ", "\"", ",", "e", ")", ";", "}", "}", "@", "Override", "public", "void", "onDismiss", "(", "DialogInterface", "dialog", ")", "{", "super", ".", "onDismiss", "(", "dialog", ")", ";", "if", "(", "dismissListener", "!=", "null", ")", "dismissListener", ".", "onDismiss", "(", "dialog", ")", ";", "}", "public", "void", "setTitle", "(", "String", "title", ")", "{", "this", ".", "title", "=", "title", ";", "}", "public", "void", "setMessage", "(", "String", "message", ")", "{", "this", ".", "message", "=", "message", ";", "}", "public", "void", "setSpan", "(", "SpannableString", "message", ")", "{", "if", "(", "message", "==", "null", ")", "{", "BRReportsManager", ".", "reportBug", "(", "new", "NullPointerException", "(", "\"", "setSpan with null message", "\"", ")", ")", ";", "return", ";", "}", "this", ".", "spanMessage", "=", "message", ";", "}", "public", "void", "setPosButton", "(", "@", "NonNull", "String", "posButton", ")", "{", "this", ".", "posButton", "=", "posButton", ";", "}", "public", "void", "setNegButton", "(", "String", "negButton", ")", "{", "this", ".", "negButton", "=", "negButton", ";", "}", "public", "void", "setPosListener", "(", "BRDialogView", ".", "BROnClickListener", "posListener", ")", "{", "this", ".", "posListener", "=", "posListener", ";", "}", "public", "void", "setNegListener", "(", "BRDialogView", ".", "BROnClickListener", "negListener", ")", "{", "this", ".", "negListener", "=", "negListener", ";", "}", "public", "void", "setDismissListener", "(", "DialogInterface", ".", "OnDismissListener", "dismissListener", ")", "{", "this", ".", "dismissListener", "=", "dismissListener", ";", "}", "public", "interface", "BROnClickListener", "{", "void", "onClick", "(", "BRDialogView", "brDialogView", ")", ";", "}", "public", "void", "dismissWithAnimation", "(", ")", "{", "try", "{", "dismissAllowingStateLoss", "(", ")", ";", "}", "catch", "(", "IllegalArgumentException", "e", ")", "{", "Log", ".", "e", "(", "TAG", ",", "\"", "dismissWithAnimation: ", "\"", ",", "e", ")", ";", "}", "}", "}" ]
BreadWallet <p/> Created by Mihail Gutan on <[email protected]> 3/15/17.
[ "BreadWallet", "<p", "/", ">", "Created", "by", "Mihail", "Gutan", "on", "<mihail@breadwallet", ".", "com", ">", "3", "/", "15", "/", "17", "." ]
[ "//Because the callback is passed un-optimally, it's not view recreation safe especially", "//after activity recreation restoring from an activity saved state. Dismiss the dialog and", "//the user can just reinvoke it again by initiating the desired action" ]
[ { "param": "DialogFragment", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "DialogFragment", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
false
15
799
280
4819ccad1c6fadbd76cfb35f9b7ae7ed2ee68d09
Four-Velocity/jb_test
utils/base58.py
[ "Unlicense" ]
Python
Encoder
Encode user id/company id/host integer/ to invitation URL, stores it in `self.encoded` The format of Invitation URL is 'URL/CODE', where code is 'XXXXXX_S': XXXXXX - encoded integer, S - one letter type Also generates qrcode with invitation link :param url: URL to which the invitation code will be added :param pk: Integer that will be encoded :param sort: Integer that indicates ownership of the code. 1 for Personal, 2 for Enterprise, 3 for owned by the Host :param path: path to qrcode >>> example = Encoder("http://example.com", 153, 1) >>> example.invitation_code '11113e_P' >>> example.encoded_url 'http://example.com/11113e_P' >>> example 'http://example.com/11113e_P'
Encode user id/company id/host integer/ to invitation URL, stores it in `self.encoded` The format of Invitation URL is 'URL/CODE', where code is 'XXXXXX_S': XXXXXX - encoded integer, S - one letter type Also generates qrcode with invitation link
[ "Encode", "user", "id", "/", "company", "id", "/", "host", "integer", "/", "to", "invitation", "URL", "stores", "it", "in", "`", "self", ".", "encoded", "`", "The", "format", "of", "Invitation", "URL", "is", "'", "URL", "/", "CODE", "'", "where", "code", "is", "'", "XXXXXX_S", "'", ":", "XXXXXX", "-", "encoded", "integer", "S", "-", "one", "letter", "type", "Also", "generates", "qrcode", "with", "invitation", "link" ]
class Encoder: """ Encode user id/company id/host integer/ to invitation URL, stores it in `self.encoded` The format of Invitation URL is 'URL/CODE', where code is 'XXXXXX_S': XXXXXX - encoded integer, S - one letter type Also generates qrcode with invitation link :param url: URL to which the invitation code will be added :param pk: Integer that will be encoded :param sort: Integer that indicates ownership of the code. 1 for Personal, 2 for Enterprise, 3 for owned by the Host :param path: path to qrcode >>> example = Encoder("http://example.com", 153, 1) >>> example.invitation_code '11113e_P' >>> example.encoded_url 'http://example.com/11113e_P' >>> example 'http://example.com/11113e_P' """ _template = dict(enumerate(symbols)) _sort_translator = {1: 'P', 2: 'E', 3: 'H'} def __init__(self, url: str, pk: int, sort: int, path: str = QR_FOLDER): self.url = url self.pk = pk self.sort = self._sort_translator[sort] self.folder = path self.invitation_code = self.encode() if self.url[-1] == '/': tmp_code = f'{self.invitation_code}/' else: tmp_code = f'/{self.invitation_code}/' self.encoded_url = self.url + tmp_code def __str__(self): return self.encoded_url def to_58(self, value: int = None) -> str: """ Converts an integer with from the decimal numeral system to the numeral system with safe base 58. Read more https://en.wikipedia.org/wiki/Base58 :param value: Integer in decimal numeral system. By default it's class `pk` attribute :return: Integer in numeral system with base 58 >>> self.to_58(641835) '4Ho8' """ if value is None: value = self.pk if value <= 57: return self._template[value] else: total = value // 58 reminder = value % 58 return self.to_58(total) + self._template[reminder] def encode(self): """ Encode pk and sort into invitation code :return: Invitation code with a format XXXXXX_S, where 'XXXXXX' is encoded pk and 'S' is sort integer """ code = self.to_58().rjust(6, "1") return f'{code}_{self.sort}' def qr(self): """ Generates qr code in svg format with invitation link :return: path to qr code """ factory = qrcode.image.svg.SvgPathImage img = qrcode.make(self.encoded_url, image_factory=factory) destination = os.path.join(self.folder, f'{self.invitation_code}.svg') relative_path = os.path.join(self.folder.split('/')[-1], f'{self.invitation_code}.svg') create_folder(self.folder) img.save(destination) return destination, relative_path
[ "class", "Encoder", ":", "_template", "=", "dict", "(", "enumerate", "(", "symbols", ")", ")", "_sort_translator", "=", "{", "1", ":", "'P'", ",", "2", ":", "'E'", ",", "3", ":", "'H'", "}", "def", "__init__", "(", "self", ",", "url", ":", "str", ",", "pk", ":", "int", ",", "sort", ":", "int", ",", "path", ":", "str", "=", "QR_FOLDER", ")", ":", "self", ".", "url", "=", "url", "self", ".", "pk", "=", "pk", "self", ".", "sort", "=", "self", ".", "_sort_translator", "[", "sort", "]", "self", ".", "folder", "=", "path", "self", ".", "invitation_code", "=", "self", ".", "encode", "(", ")", "if", "self", ".", "url", "[", "-", "1", "]", "==", "'/'", ":", "tmp_code", "=", "f'{self.invitation_code}/'", "else", ":", "tmp_code", "=", "f'/{self.invitation_code}/'", "self", ".", "encoded_url", "=", "self", ".", "url", "+", "tmp_code", "def", "__str__", "(", "self", ")", ":", "return", "self", ".", "encoded_url", "def", "to_58", "(", "self", ",", "value", ":", "int", "=", "None", ")", "->", "str", ":", "\"\"\"\n Converts an integer with from the decimal numeral system to the numeral system with safe base 58.\n Read more https://en.wikipedia.org/wiki/Base58\n\n :param value: Integer in decimal numeral system. By default it's class `pk` attribute\n :return: Integer in numeral system with base 58\n\n >>> self.to_58(641835)\n '4Ho8'\n \"\"\"", "if", "value", "is", "None", ":", "value", "=", "self", ".", "pk", "if", "value", "<=", "57", ":", "return", "self", ".", "_template", "[", "value", "]", "else", ":", "total", "=", "value", "//", "58", "reminder", "=", "value", "%", "58", "return", "self", ".", "to_58", "(", "total", ")", "+", "self", ".", "_template", "[", "reminder", "]", "def", "encode", "(", "self", ")", ":", "\"\"\"\n Encode pk and sort into invitation code\n\n :return: Invitation code with a format XXXXXX_S, where 'XXXXXX' is encoded pk and 'S' is sort integer\n \"\"\"", "code", "=", "self", ".", "to_58", "(", ")", ".", "rjust", "(", "6", ",", "\"1\"", ")", "return", "f'{code}_{self.sort}'", "def", "qr", "(", "self", ")", ":", "\"\"\"\n Generates qr code in svg format with invitation link\n\n :return: path to qr code\n \"\"\"", "factory", "=", "qrcode", ".", "image", ".", "svg", ".", "SvgPathImage", "img", "=", "qrcode", ".", "make", "(", "self", ".", "encoded_url", ",", "image_factory", "=", "factory", ")", "destination", "=", "os", ".", "path", ".", "join", "(", "self", ".", "folder", ",", "f'{self.invitation_code}.svg'", ")", "relative_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "folder", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ",", "f'{self.invitation_code}.svg'", ")", "create_folder", "(", "self", ".", "folder", ")", "img", ".", "save", "(", "destination", ")", "return", "destination", ",", "relative_path" ]
Encode user id/company id/host integer/ to invitation URL, stores it in `self.encoded` The format of Invitation URL is 'URL/CODE', where code is 'XXXXXX_S': XXXXXX - encoded integer, S - one letter type Also generates qrcode with invitation link
[ "Encode", "user", "id", "/", "company", "id", "/", "host", "integer", "/", "to", "invitation", "URL", "stores", "it", "in", "`", "self", ".", "encoded", "`", "The", "format", "of", "Invitation", "URL", "is", "'", "URL", "/", "CODE", "'", "where", "code", "is", "'", "XXXXXX_S", "'", ":", "XXXXXX", "-", "encoded", "integer", "S", "-", "one", "letter", "type", "Also", "generates", "qrcode", "with", "invitation", "link" ]
[ "\"\"\"\n Encode user id/company id/host integer/ to invitation URL, stores it in `self.encoded`\n The format of Invitation URL is 'URL/CODE', where code is 'XXXXXX_S': XXXXXX - encoded integer, S - one letter type\n Also generates qrcode with invitation link\n\n :param url: URL to which the invitation code will be added\n :param pk: Integer that will be encoded\n :param sort: Integer that indicates ownership of the code. 1 for Personal, 2 for Enterprise, 3 for owned by the Host\n :param path: path to qrcode\n\n >>> example = Encoder(\"http://example.com\", 153, 1)\n >>> example.invitation_code\n '11113e_P'\n >>> example.encoded_url\n 'http://example.com/11113e_P'\n >>> example\n 'http://example.com/11113e_P'\n \"\"\"", "\"\"\"\n Converts an integer with from the decimal numeral system to the numeral system with safe base 58.\n Read more https://en.wikipedia.org/wiki/Base58\n\n :param value: Integer in decimal numeral system. By default it's class `pk` attribute\n :return: Integer in numeral system with base 58\n\n >>> self.to_58(641835)\n '4Ho8'\n \"\"\"", "\"\"\"\n Encode pk and sort into invitation code\n\n :return: Invitation code with a format XXXXXX_S, where 'XXXXXX' is encoded pk and 'S' is sort integer\n \"\"\"", "\"\"\"\n Generates qr code in svg format with invitation link\n\n :return: path to qr code\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [ { "identifier": "url", "type": null, "docstring": "URL to which the invitation code will be added", "docstring_tokens": [ "URL", "to", "which", "the", "invitation", "code", "will", "be", "added" ], "default": null, "is_optional": null }, { "identifier": "pk", "type": null, "docstring": "Integer that will be encoded", "docstring_tokens": [ "Integer", "that", "will", "be", "encoded" ], "default": null, "is_optional": null }, { "identifier": "sort", "type": null, "docstring": "Integer that indicates ownership of the code. 1 for Personal, 2 for Enterprise, 3 for owned by the Host", "docstring_tokens": [ "Integer", "that", "indicates", "ownership", "of", "the", "code", ".", "1", "for", "Personal", "2", "for", "Enterprise", "3", "for", "owned", "by", "the", "Host" ], "default": null, "is_optional": null }, { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [ "None" ], "default": null, "is_optional": null } ], "others": [] }
false
13
739
208