repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
m-m-m/util
version/src/main/java/net/sf/mmm/util/version/impl/VersionIdentifierImpl.java
VersionIdentifierImpl.validate
private void validate() { if ((this.segments.length < 0) && (!this.snapshot)) { throw new IllegalArgumentException("segments.length:" + Integer.valueOf(this.segments.length)); } for (int i = 0; i < this.segments.length; i++) { if (this.segments[i] < 0) { throw new IllegalArgumentException("segments[" + i + "]:" + Integer.valueOf(this.segments[i])); } } if (this.phaseNumber != null) { if (this.phaseNumber.intValue() < 0) { throw new IllegalArgumentException("phaseNumber:" + this.phaseNumber); } if (this.phase == null) { throw new IllegalArgumentException("phaseNumber (phase==null):" + this.phaseNumber); } if ((this.phase == DevelopmentPhase.RELEASE) && (this.phaseNumber.intValue() != 0)) { throw new IllegalArgumentException("phaseNumber (phase==RELEASE):" + this.phaseNumber); } } }
java
private void validate() { if ((this.segments.length < 0) && (!this.snapshot)) { throw new IllegalArgumentException("segments.length:" + Integer.valueOf(this.segments.length)); } for (int i = 0; i < this.segments.length; i++) { if (this.segments[i] < 0) { throw new IllegalArgumentException("segments[" + i + "]:" + Integer.valueOf(this.segments[i])); } } if (this.phaseNumber != null) { if (this.phaseNumber.intValue() < 0) { throw new IllegalArgumentException("phaseNumber:" + this.phaseNumber); } if (this.phase == null) { throw new IllegalArgumentException("phaseNumber (phase==null):" + this.phaseNumber); } if ((this.phase == DevelopmentPhase.RELEASE) && (this.phaseNumber.intValue() != 0)) { throw new IllegalArgumentException("phaseNumber (phase==RELEASE):" + this.phaseNumber); } } }
[ "private", "void", "validate", "(", ")", "{", "if", "(", "(", "this", ".", "segments", ".", "length", "<", "0", ")", "&&", "(", "!", "this", ".", "snapshot", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"segments.length:\"", "+", "...
This method validates the consistency of this version identifier.
[ "This", "method", "validates", "the", "consistency", "of", "this", "version", "identifier", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/version/src/main/java/net/sf/mmm/util/version/impl/VersionIdentifierImpl.java#L98-L119
train
jMotif/GI
src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java
RulePrunerFactory.computeGrammarSize
public static Integer computeGrammarSize(GrammarRules rules, Integer paaSize) { // The final grammar's size in BYTES // int res = 0; // The final size is the sum of the sizes of all rules // for (GrammarRuleRecord r : rules) { String ruleStr = r.getRuleString(); String[] tokens = ruleStr.split("\\s+"); int ruleSize = computeRuleSize(paaSize, tokens); res += ruleSize; } return res; }
java
public static Integer computeGrammarSize(GrammarRules rules, Integer paaSize) { // The final grammar's size in BYTES // int res = 0; // The final size is the sum of the sizes of all rules // for (GrammarRuleRecord r : rules) { String ruleStr = r.getRuleString(); String[] tokens = ruleStr.split("\\s+"); int ruleSize = computeRuleSize(paaSize, tokens); res += ruleSize; } return res; }
[ "public", "static", "Integer", "computeGrammarSize", "(", "GrammarRules", "rules", ",", "Integer", "paaSize", ")", "{", "// The final grammar's size in BYTES", "//", "int", "res", "=", "0", ";", "// The final size is the sum of the sizes of all rules", "//", "for", "(", ...
Computes the size of a normal, i.e. unpruned grammar. @param rules the grammar rules. @param paaSize the SAX transform word size. @return the grammar size, in BYTES.
[ "Computes", "the", "size", "of", "a", "normal", "i", ".", "e", ".", "unpruned", "grammar", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java#L26-L42
train
jMotif/GI
src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java
RulePrunerFactory.performPruning
public static GrammarRules performPruning(double[] ts, GrammarRules grammarRules) { RulePruningAlgorithm pruner = new RulePruningAlgorithm(grammarRules, ts.length); pruner.pruneRules(); return pruner.regularizePrunedRules(); }
java
public static GrammarRules performPruning(double[] ts, GrammarRules grammarRules) { RulePruningAlgorithm pruner = new RulePruningAlgorithm(grammarRules, ts.length); pruner.pruneRules(); return pruner.regularizePrunedRules(); }
[ "public", "static", "GrammarRules", "performPruning", "(", "double", "[", "]", "ts", ",", "GrammarRules", "grammarRules", ")", "{", "RulePruningAlgorithm", "pruner", "=", "new", "RulePruningAlgorithm", "(", "grammarRules", ",", "ts", ".", "length", ")", ";", "pr...
Performs pruning. @param ts the input time series. @param grammarRules the grammar. @return pruned ruleset.
[ "Performs", "pruning", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java#L68-L72
train
jMotif/GI
src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java
RulePrunerFactory.computeCover
public static double computeCover(boolean[] cover) { int covered = 0; for (boolean i : cover) { if (i) { covered++; } } return (double) covered / (double) cover.length; }
java
public static double computeCover(boolean[] cover) { int covered = 0; for (boolean i : cover) { if (i) { covered++; } } return (double) covered / (double) cover.length; }
[ "public", "static", "double", "computeCover", "(", "boolean", "[", "]", "cover", ")", "{", "int", "covered", "=", "0", ";", "for", "(", "boolean", "i", ":", "cover", ")", "{", "if", "(", "i", ")", "{", "covered", "++", ";", "}", "}", "return", "(...
Compute the covered percentage. @param cover the cover array. @return coverage percentage.
[ "Compute", "the", "covered", "percentage", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/rulepruner/RulePrunerFactory.java#L214-L222
train
protegeproject/jpaul
src/main/java/jpaul/RegExps/NFASimplifier.java
NFASimplifier.compatible
private boolean compatible(int i, int j, Set<Integer> T[][]) { if(s2comp[i] != s2comp[j]) return false; for(int k = 0; k < nbLabels; k++) { if(! T[i][k].equals(T[j][k])) return false; } return true; }
java
private boolean compatible(int i, int j, Set<Integer> T[][]) { if(s2comp[i] != s2comp[j]) return false; for(int k = 0; k < nbLabels; k++) { if(! T[i][k].equals(T[j][k])) return false; } return true; }
[ "private", "boolean", "compatible", "(", "int", "i", ",", "int", "j", ",", "Set", "<", "Integer", ">", "T", "[", "]", "[", "]", ")", "{", "if", "(", "s2comp", "[", "i", "]", "!=", "s2comp", "[", "j", "]", ")", "return", "false", ";", "for", "...
transition in the same components
[ "transition", "in", "the", "same", "components" ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/RegExps/NFASimplifier.java#L179-L185
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/view/NamingService.java
NamingService.register
public boolean register(E e, String name) { if (resolve.containsKey(name)) { return false; } resolve.put(name, e); rev.put(e, name); return true; }
java
public boolean register(E e, String name) { if (resolve.containsKey(name)) { return false; } resolve.put(name, e); rev.put(e, name); return true; }
[ "public", "boolean", "register", "(", "E", "e", ",", "String", "name", ")", "{", "if", "(", "resolve", ".", "containsKey", "(", "name", ")", ")", "{", "return", "false", ";", "}", "resolve", ".", "put", "(", "name", ",", "e", ")", ";", "rev", "."...
Register the name of an element. @param e the element to register @param name the element name. Must be globally unique @return {@code true} if the association has been established, {@code false} if the name is already used for another element
[ "Register", "the", "name", "of", "an", "element", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/NamingService.java#L84-L91
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/view/NamingService.java
NamingService.substituteVM
@Override public boolean substituteVM(VM curId, VM nextId) { if (VM.TYPE.equals(elemId)) { if (rev.containsKey(nextId)) { //the new id already exists. It is a failure scenario. return false; } String fqn = rev.remove(curId); if (fqn != null) { //new resolution, with the substitution of the old one. rev.put((E) nextId, fqn); resolve.put(fqn, (E) nextId); } } return true; }
java
@Override public boolean substituteVM(VM curId, VM nextId) { if (VM.TYPE.equals(elemId)) { if (rev.containsKey(nextId)) { //the new id already exists. It is a failure scenario. return false; } String fqn = rev.remove(curId); if (fqn != null) { //new resolution, with the substitution of the old one. rev.put((E) nextId, fqn); resolve.put(fqn, (E) nextId); } } return true; }
[ "@", "Override", "public", "boolean", "substituteVM", "(", "VM", "curId", ",", "VM", "nextId", ")", "{", "if", "(", "VM", ".", "TYPE", ".", "equals", "(", "elemId", ")", ")", "{", "if", "(", "rev", ".", "containsKey", "(", "nextId", ")", ")", "{", ...
Re-associate the name of a registered VM to a new VM. @param curId the current VM identifier @param nextId the new VM identifier @return {@code true} if the re-association succeeded or if there is no VM {@code curId} registered. {@code false} if {@code nextId} is already associated to a name
[ "Re", "-", "associate", "the", "name", "of", "a", "registered", "VM", "to", "a", "new", "VM", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/NamingService.java#L130-L146
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/view/NamingService.java
NamingService.getVMNames
@SuppressWarnings("unchecked") public static NamingService<VM> getVMNames(Model mo) { return (NamingService<VM>) mo.getView(ID + VM.TYPE); }
java
@SuppressWarnings("unchecked") public static NamingService<VM> getVMNames(Model mo) { return (NamingService<VM>) mo.getView(ID + VM.TYPE); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "NamingService", "<", "VM", ">", "getVMNames", "(", "Model", "mo", ")", "{", "return", "(", "NamingService", "<", "VM", ">", ")", "mo", ".", "getView", "(", "ID", "+", "VM", ".", "...
Get the naming service for the VMs associated to a model. @param mo the model to look at @return the view if attached. {@code null} otherwise
[ "Get", "the", "naming", "service", "for", "the", "VMs", "associated", "to", "a", "model", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/NamingService.java#L213-L216
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/view/NamingService.java
NamingService.getNodeNames
@SuppressWarnings("unchecked") public static NamingService<Node> getNodeNames(Model mo) { return (NamingService<Node>) mo.getView(ID + Node.TYPE); }
java
@SuppressWarnings("unchecked") public static NamingService<Node> getNodeNames(Model mo) { return (NamingService<Node>) mo.getView(ID + Node.TYPE); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "NamingService", "<", "Node", ">", "getNodeNames", "(", "Model", "mo", ")", "{", "return", "(", "NamingService", "<", "Node", ">", ")", "mo", ".", "getView", "(", "ID", "+", "Node", ...
Get the naming service for the nodes associated to a model. @param mo the model to look at @return the view if attached. {@code null} otherwise
[ "Get", "the", "naming", "service", "for", "the", "nodes", "associated", "to", "a", "model", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/view/NamingService.java#L224-L227
train
btrplace/scheduler
api/src/main/java/org/btrplace/plan/event/Action.java
Action.applyEvents
public boolean applyEvents(Hook k, Model i) { for (Event n : getEvents(k)) { if (!n.apply(i)) { return false; } } return true; }
java
public boolean applyEvents(Hook k, Model i) { for (Event n : getEvents(k)) { if (!n.apply(i)) { return false; } } return true; }
[ "public", "boolean", "applyEvents", "(", "Hook", "k", ",", "Model", "i", ")", "{", "for", "(", "Event", "n", ":", "getEvents", "(", "k", ")", ")", "{", "if", "(", "!", "n", ".", "apply", "(", "i", ")", ")", "{", "return", "false", ";", "}", "...
Apply the events attached to a given hook. @param k the hook @param i the model to modify with the application of the events @return {@code true} iff all the events were applied successfully
[ "Apply", "the", "events", "attached", "to", "a", "given", "hook", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/plan/event/Action.java#L107-L114
train
btrplace/scheduler
api/src/main/java/org/btrplace/plan/event/Action.java
Action.addEvent
public boolean addEvent(Hook k, Event n) { Set<Event> l = events.get(k); if (l == null) { l = new HashSet<>(); events.put(k, l); } return l.add(n); }
java
public boolean addEvent(Hook k, Event n) { Set<Event> l = events.get(k); if (l == null) { l = new HashSet<>(); events.put(k, l); } return l.add(n); }
[ "public", "boolean", "addEvent", "(", "Hook", "k", ",", "Event", "n", ")", "{", "Set", "<", "Event", ">", "l", "=", "events", ".", "get", "(", "k", ")", ";", "if", "(", "l", "==", "null", ")", "{", "l", "=", "new", "HashSet", "<>", "(", ")", ...
Add an event to the action. The moment the event will be executed depends on its hook. @param k the hook @param n the event to attach @return {@code true} iff the event was added
[ "Add", "an", "event", "to", "the", "action", ".", "The", "moment", "the", "event", "will", "be", "executed", "depends", "on", "its", "hook", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/plan/event/Action.java#L151-L158
train
btrplace/scheduler
api/src/main/java/org/btrplace/plan/event/Action.java
Action.getEvents
public Set<Event> getEvents(Hook k) { Set<Event> l = events.get(k); return l == null ? Collections.emptySet() : l; }
java
public Set<Event> getEvents(Hook k) { Set<Event> l = events.get(k); return l == null ? Collections.emptySet() : l; }
[ "public", "Set", "<", "Event", ">", "getEvents", "(", "Hook", "k", ")", "{", "Set", "<", "Event", ">", "l", "=", "events", ".", "get", "(", "k", ")", ";", "return", "l", "==", "null", "?", "Collections", ".", "emptySet", "(", ")", ":", "l", ";"...
Get the events attached to a specific hook. @param k the hook @return a list of events that may be empty
[ "Get", "the", "events", "attached", "to", "a", "specific", "hook", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/plan/event/Action.java#L166-L169
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/DefaultAliasedCumulatives.java
DefaultAliasedCumulatives.addDim
@Override public void addDim(int c, int[] cUse, IntVar[] dUse, int[] alias) { capacities.add(c); cUsages.add(cUse); dUsages.add(dUse); aliases.add(alias); }
java
@Override public void addDim(int c, int[] cUse, IntVar[] dUse, int[] alias) { capacities.add(c); cUsages.add(cUse); dUsages.add(dUse); aliases.add(alias); }
[ "@", "Override", "public", "void", "addDim", "(", "int", "c", ",", "int", "[", "]", "cUse", ",", "IntVar", "[", "]", "dUse", ",", "int", "[", "]", "alias", ")", "{", "capacities", ".", "add", "(", "c", ")", ";", "cUsages", ".", "add", "(", "cUs...
Add a constraint @param c the cumulative capacity of the aliased resources @param cUse the usage of each of the c-slices @param dUse the usage of each of the d-slices @param alias the resource identifiers that compose the alias
[ "Add", "a", "constraint" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/DefaultAliasedCumulatives.java#L68-L74
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/DefaultAliasedCumulatives.java
DefaultAliasedCumulatives.beforeSolve
@Override public boolean beforeSolve(ReconfigurationProblem r) { super.beforeSolve(r); for (int i = 0; i < aliases.size(); i++) { int capa = capacities.get(i); int[] alias = aliases.get(i); int[] cUse = cUsages.get(i); int[] dUses = new int[dUsages.get(i).length]; for (IntVar dUseDim : dUsages.get(i)) { dUses[i++] = dUseDim.getLB(); } r.getModel().post(new AliasedCumulatives(alias, new int[]{capa}, cHosts, new int[][]{cUse}, cEnds, dHosts, new int[][]{dUses}, dStarts, associations)); } return true; }
java
@Override public boolean beforeSolve(ReconfigurationProblem r) { super.beforeSolve(r); for (int i = 0; i < aliases.size(); i++) { int capa = capacities.get(i); int[] alias = aliases.get(i); int[] cUse = cUsages.get(i); int[] dUses = new int[dUsages.get(i).length]; for (IntVar dUseDim : dUsages.get(i)) { dUses[i++] = dUseDim.getLB(); } r.getModel().post(new AliasedCumulatives(alias, new int[]{capa}, cHosts, new int[][]{cUse}, cEnds, dHosts, new int[][]{dUses}, dStarts, associations)); } return true; }
[ "@", "Override", "public", "boolean", "beforeSolve", "(", "ReconfigurationProblem", "r", ")", "{", "super", ".", "beforeSolve", "(", "r", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "aliases", ".", "size", "(", ")", ";", "i", "++", "...
Get the generated constraints. @return a list of constraint that may be empty.
[ "Get", "the", "generated", "constraints", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/DefaultAliasedCumulatives.java#L81-L100
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/ChocoViews.java
ChocoViews.resolveDependencies
public static List<ChocoView> resolveDependencies(Model mo, List<ChocoView> views, Collection<String> base) throws SchedulerException { Set<String> done = new HashSet<>(base); List<ChocoView> remaining = new ArrayList<>(views); List<ChocoView> solved = new ArrayList<>(); while (!remaining.isEmpty()) { ListIterator<ChocoView> ite = remaining.listIterator(); boolean blocked = true; while (ite.hasNext()) { ChocoView s = ite.next(); if (done.containsAll(s.getDependencies())) { ite.remove(); done.add(s.getIdentifier()); solved.add(s); blocked = false; } } if (blocked) { throw new SchedulerModelingException(mo, "Missing dependencies or cyclic dependencies prevent from using: " + remaining); } } return solved; }
java
public static List<ChocoView> resolveDependencies(Model mo, List<ChocoView> views, Collection<String> base) throws SchedulerException { Set<String> done = new HashSet<>(base); List<ChocoView> remaining = new ArrayList<>(views); List<ChocoView> solved = new ArrayList<>(); while (!remaining.isEmpty()) { ListIterator<ChocoView> ite = remaining.listIterator(); boolean blocked = true; while (ite.hasNext()) { ChocoView s = ite.next(); if (done.containsAll(s.getDependencies())) { ite.remove(); done.add(s.getIdentifier()); solved.add(s); blocked = false; } } if (blocked) { throw new SchedulerModelingException(mo, "Missing dependencies or cyclic dependencies prevent from using: " + remaining); } } return solved; }
[ "public", "static", "List", "<", "ChocoView", ">", "resolveDependencies", "(", "Model", "mo", ",", "List", "<", "ChocoView", ">", "views", ",", "Collection", "<", "String", ">", "base", ")", "throws", "SchedulerException", "{", "Set", "<", "String", ">", "...
Flatten the views while considering their dependencies. Operations over the views that respect the iteration order, satisfies the dependencies. @param mo the model @param views the associated solver views @return the list of views, dependency-free @throws SchedulerException if there is a cyclic dependency
[ "Flatten", "the", "views", "while", "considering", "their", "dependencies", ".", "Operations", "over", "the", "views", "that", "respect", "the", "iteration", "order", "satisfies", "the", "dependencies", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/ChocoViews.java#L52-L73
train
jMotif/GI
src/main/java/net/seninp/gi/logic/GIUtils.java
GIUtils.getZeroIntervals
public static List<RuleInterval> getZeroIntervals(int[] coverageArray) { ArrayList<RuleInterval> res = new ArrayList<RuleInterval>(); int start = -1; boolean inInterval = false; int intervalsCounter = -1; // slide over the array from left to the right // for (int i = 0; i < coverageArray.length; i++) { if (0 == coverageArray[i] && !inInterval) { start = i; inInterval = true; } if (coverageArray[i] > 0 && inInterval) { res.add(new RuleInterval(intervalsCounter, start, i, 0)); inInterval = false; intervalsCounter--; } } // we need to check for the last interval here // if (inInterval) { res.add(new RuleInterval(intervalsCounter, start, coverageArray.length, 0)); } return res; }
java
public static List<RuleInterval> getZeroIntervals(int[] coverageArray) { ArrayList<RuleInterval> res = new ArrayList<RuleInterval>(); int start = -1; boolean inInterval = false; int intervalsCounter = -1; // slide over the array from left to the right // for (int i = 0; i < coverageArray.length; i++) { if (0 == coverageArray[i] && !inInterval) { start = i; inInterval = true; } if (coverageArray[i] > 0 && inInterval) { res.add(new RuleInterval(intervalsCounter, start, i, 0)); inInterval = false; intervalsCounter--; } } // we need to check for the last interval here // if (inInterval) { res.add(new RuleInterval(intervalsCounter, start, coverageArray.length, 0)); } return res; }
[ "public", "static", "List", "<", "RuleInterval", ">", "getZeroIntervals", "(", "int", "[", "]", "coverageArray", ")", "{", "ArrayList", "<", "RuleInterval", ">", "res", "=", "new", "ArrayList", "<", "RuleInterval", ">", "(", ")", ";", "int", "start", "=", ...
Run a quick scan along the time series coverage to find a zeroed intervals. @param coverageArray the coverage to analyze. @return set of zeroed intervals (if found).
[ "Run", "a", "quick", "scan", "along", "the", "time", "series", "coverage", "to", "find", "a", "zeroed", "intervals", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/logic/GIUtils.java#L42-L74
train
jMotif/GI
src/main/java/net/seninp/gi/logic/GIUtils.java
GIUtils.getCoverAsFraction
public static double getCoverAsFraction(int seriesLength, GrammarRules rules) { boolean[] coverageArray = new boolean[seriesLength]; for (GrammarRuleRecord rule : rules) { if (0 == rule.ruleNumber()) { continue; } ArrayList<RuleInterval> arrPos = rule.getRuleIntervals(); for (RuleInterval saxPos : arrPos) { int startPos = saxPos.getStart(); int endPos = saxPos.getEnd(); for (int j = startPos; j < endPos; j++) { coverageArray[j] = true; } } } int coverSum = 0; for (int i = 0; i < seriesLength; i++) { if (coverageArray[i]) { coverSum++; } } return (double) coverSum / (double) seriesLength; }
java
public static double getCoverAsFraction(int seriesLength, GrammarRules rules) { boolean[] coverageArray = new boolean[seriesLength]; for (GrammarRuleRecord rule : rules) { if (0 == rule.ruleNumber()) { continue; } ArrayList<RuleInterval> arrPos = rule.getRuleIntervals(); for (RuleInterval saxPos : arrPos) { int startPos = saxPos.getStart(); int endPos = saxPos.getEnd(); for (int j = startPos; j < endPos; j++) { coverageArray[j] = true; } } } int coverSum = 0; for (int i = 0; i < seriesLength; i++) { if (coverageArray[i]) { coverSum++; } } return (double) coverSum / (double) seriesLength; }
[ "public", "static", "double", "getCoverAsFraction", "(", "int", "seriesLength", ",", "GrammarRules", "rules", ")", "{", "boolean", "[", "]", "coverageArray", "=", "new", "boolean", "[", "seriesLength", "]", ";", "for", "(", "GrammarRuleRecord", "rule", ":", "r...
Computes which fraction of the time series is covered by the rules set. @param seriesLength the time series length. @param rules the grammar rules set. @return a fraction covered by the rules.
[ "Computes", "which", "fraction", "of", "the", "time", "series", "is", "covered", "by", "the", "rules", "set", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/logic/GIUtils.java#L83-L108
train
jMotif/GI
src/main/java/net/seninp/gi/logic/GIUtils.java
GIUtils.getMeanRuleCoverage
public static double getMeanRuleCoverage(int length, GrammarRules rules) { // get the coverage array // int[] coverageArray = new int[length]; for (GrammarRuleRecord rule : rules) { if (0 == rule.ruleNumber()) { continue; } ArrayList<RuleInterval> arrPos = rule.getRuleIntervals(); for (RuleInterval saxPos : arrPos) { int startPos = saxPos.getStart(); int endPos = saxPos.getEnd(); for (int j = startPos; j < endPos; j++) { coverageArray[j] = coverageArray[j] + 1; } } } // int minCoverage = 0; // int maxCoverage = 0; int coverageSum = 0; for (int i : coverageArray) { coverageSum += i; // if (i < minCoverage) { // minCoverage = i; // } // if (i > maxCoverage) { // maxCoverage = i; // } } return (double) coverageSum / (double) length; }
java
public static double getMeanRuleCoverage(int length, GrammarRules rules) { // get the coverage array // int[] coverageArray = new int[length]; for (GrammarRuleRecord rule : rules) { if (0 == rule.ruleNumber()) { continue; } ArrayList<RuleInterval> arrPos = rule.getRuleIntervals(); for (RuleInterval saxPos : arrPos) { int startPos = saxPos.getStart(); int endPos = saxPos.getEnd(); for (int j = startPos; j < endPos; j++) { coverageArray[j] = coverageArray[j] + 1; } } } // int minCoverage = 0; // int maxCoverage = 0; int coverageSum = 0; for (int i : coverageArray) { coverageSum += i; // if (i < minCoverage) { // minCoverage = i; // } // if (i > maxCoverage) { // maxCoverage = i; // } } return (double) coverageSum / (double) length; }
[ "public", "static", "double", "getMeanRuleCoverage", "(", "int", "length", ",", "GrammarRules", "rules", ")", "{", "// get the coverage array", "//", "int", "[", "]", "coverageArray", "=", "new", "int", "[", "length", "]", ";", "for", "(", "GrammarRuleRecord", ...
Gets the mean rule coverage. @param length the original time-series length. @param rules the grammar rules set. @return the mean rule coverage.
[ "Gets", "the", "mean", "rule", "coverage", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/logic/GIUtils.java#L117-L147
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/layer/LayerBuildsAccessor.java
LayerBuildsAccessor.removeLayerFromCache
public void removeLayerFromCache(LayerImpl layer) { if (layer.getId() != layerId) { throw new IllegalStateException(); } LayerCacheImpl layerCache = layerCacheRef.get(); if (layerCache != null) { layerCache.remove(layer.getKey(), layer); } }
java
public void removeLayerFromCache(LayerImpl layer) { if (layer.getId() != layerId) { throw new IllegalStateException(); } LayerCacheImpl layerCache = layerCacheRef.get(); if (layerCache != null) { layerCache.remove(layer.getKey(), layer); } }
[ "public", "void", "removeLayerFromCache", "(", "LayerImpl", "layer", ")", "{", "if", "(", "layer", ".", "getId", "(", ")", "!=", "layerId", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "LayerCacheImpl", "layerCache", "=", "layerCach...
Convenience method to remove the layer that this class is associated with from the layer cache. @param layer The layer to remove. The id of the specified layer must be the same as <code>layerId</code> or else a {@link IllegalStateException} is thrown
[ "Convenience", "method", "to", "remove", "the", "layer", "that", "this", "class", "is", "associated", "with", "from", "the", "layer", "cache", "." ]
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/layer/LayerBuildsAccessor.java#L288-L296
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.put
public final V put(K key, V value) { BinTreeNode<K,V> prev = null; BinTreeNode<K,V> node = root; int key_hash_code = key.hashCode(); while(node != null) { prev = node; if(key_hash_code < node.keyHashCode) { node = node.left; } else { if((key_hash_code > node.keyHashCode) || !node.key.equals(key)) { node = node.right; } else { cachedHashCode -= node.hashCode(); V temp = node.value; node.value = value; cachedHashCode += node.hashCode(); return temp; } } } size++; BinTreeNode<K,V> new_node = new BinTreeNode<K,V>(key, value); cachedHashCode += new_node.hashCode(); // invalidate the cached hash code if(prev == null) { root = new_node; return null; } if(key_hash_code < prev.keyHashCode) { prev.left = new_node; } else { prev.right = new_node; } return null; }
java
public final V put(K key, V value) { BinTreeNode<K,V> prev = null; BinTreeNode<K,V> node = root; int key_hash_code = key.hashCode(); while(node != null) { prev = node; if(key_hash_code < node.keyHashCode) { node = node.left; } else { if((key_hash_code > node.keyHashCode) || !node.key.equals(key)) { node = node.right; } else { cachedHashCode -= node.hashCode(); V temp = node.value; node.value = value; cachedHashCode += node.hashCode(); return temp; } } } size++; BinTreeNode<K,V> new_node = new BinTreeNode<K,V>(key, value); cachedHashCode += new_node.hashCode(); // invalidate the cached hash code if(prev == null) { root = new_node; return null; } if(key_hash_code < prev.keyHashCode) { prev.left = new_node; } else { prev.right = new_node; } return null; }
[ "public", "final", "V", "put", "(", "K", "key", ",", "V", "value", ")", "{", "BinTreeNode", "<", "K", ",", "V", ">", "prev", "=", "null", ";", "BinTreeNode", "<", "K", ",", "V", ">", "node", "=", "root", ";", "int", "key_hash_code", "=", "key", ...
Associates the specified value with the specified key in this map.
[ "Associates", "the", "specified", "value", "with", "the", "specified", "key", "in", "this", "map", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L103-L145
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.remove_semi_leaf
private final V remove_semi_leaf(BinTreeNode<K,V> node, BinTreeNode<K,V> prev, int son, BinTreeNode<K,V> m) { if(prev == null) { root = m; } else { if(son == 0) prev.left = m; else prev.right = m; } return node.value; }
java
private final V remove_semi_leaf(BinTreeNode<K,V> node, BinTreeNode<K,V> prev, int son, BinTreeNode<K,V> m) { if(prev == null) { root = m; } else { if(son == 0) prev.left = m; else prev.right = m; } return node.value; }
[ "private", "final", "V", "remove_semi_leaf", "(", "BinTreeNode", "<", "K", ",", "V", ">", "node", ",", "BinTreeNode", "<", "K", ",", "V", ">", "prev", ",", "int", "son", ",", "BinTreeNode", "<", "K", ",", "V", ">", "m", ")", "{", "if", "(", "prev...
to the only predecessor of node that could exist.
[ "to", "the", "only", "predecessor", "of", "node", "that", "could", "exist", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L204-L217
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.finish_removal
private final V finish_removal(BinTreeNode<K,V> node, BinTreeNode<K,V> prev, int son, BinTreeNode<K,V> m) { if(m != null) { // set up the links for m m.left = node.left; m.right = node.right; } if(prev == null) root = m; else { if(son == 0) prev.left = m; else prev.right = m; } return node.value; }
java
private final V finish_removal(BinTreeNode<K,V> node, BinTreeNode<K,V> prev, int son, BinTreeNode<K,V> m) { if(m != null) { // set up the links for m m.left = node.left; m.right = node.right; } if(prev == null) root = m; else { if(son == 0) prev.left = m; else prev.right = m; } return node.value; }
[ "private", "final", "V", "finish_removal", "(", "BinTreeNode", "<", "K", ",", "V", ">", "node", ",", "BinTreeNode", "<", "K", ",", "V", ">", "prev", ",", "int", "son", ",", "BinTreeNode", "<", "K", ",", "V", ">", "m", ")", "{", "if", "(", "m", ...
BinTreeNode that should replace node in the tree.
[ "BinTreeNode", "that", "should", "replace", "node", "in", "the", "tree", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L223-L239
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.extract_next
private final BinTreeNode<K,V> extract_next(BinTreeNode<K,V> node) { BinTreeNode<K,V> prev = node.right; BinTreeNode<K,V> curr = prev.left; if(curr == null) { node.right = node.right.right; return prev; } while(curr.left != null) { prev = curr; curr = curr.left; } prev.left = curr.right; return curr; }
java
private final BinTreeNode<K,V> extract_next(BinTreeNode<K,V> node) { BinTreeNode<K,V> prev = node.right; BinTreeNode<K,V> curr = prev.left; if(curr == null) { node.right = node.right.right; return prev; } while(curr.left != null) { prev = curr; curr = curr.left; } prev.left = curr.right; return curr; }
[ "private", "final", "BinTreeNode", "<", "K", ",", "V", ">", "extract_next", "(", "BinTreeNode", "<", "K", ",", "V", ">", "node", ")", "{", "BinTreeNode", "<", "K", ",", "V", ">", "prev", "=", "node", ".", "right", ";", "BinTreeNode", "<", "K", ",",...
removes it from that subtree and returns it.
[ "removes", "it", "from", "that", "subtree", "and", "returns", "it", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L243-L259
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.values
public final Collection<V> values() { return new AbstractCollection<V>() { public Iterator<V> iterator() { final Iterator<Map.Entry<K,V>> ite = entryIterator(); return new Iterator<V>() { public boolean hasNext() { return ite.hasNext(); } public void remove() { ite.remove(); } public V next() { return ite.next().getValue(); } }; } public int size() { return size; } }; }
java
public final Collection<V> values() { return new AbstractCollection<V>() { public Iterator<V> iterator() { final Iterator<Map.Entry<K,V>> ite = entryIterator(); return new Iterator<V>() { public boolean hasNext() { return ite.hasNext(); } public void remove() { ite.remove(); } public V next() { return ite.next().getValue(); } }; } public int size() { return size; } }; }
[ "public", "final", "Collection", "<", "V", ">", "values", "(", ")", "{", "return", "new", "AbstractCollection", "<", "V", ">", "(", ")", "{", "public", "Iterator", "<", "V", ">", "iterator", "(", ")", "{", "final", "Iterator", "<", "Map", ".", "Entry...
Returns an unmodifiable collection view of the values from this map.
[ "Returns", "an", "unmodifiable", "collection", "view", "of", "the", "values", "from", "this", "map", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L298-L312
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.entrySet
public final Set<Map.Entry<K,V>> entrySet() { return new AbstractSet<Map.Entry<K,V>>() { public Iterator<Map.Entry<K,V>> iterator() { return entryIterator(); } public int size() { return size; } }; }
java
public final Set<Map.Entry<K,V>> entrySet() { return new AbstractSet<Map.Entry<K,V>>() { public Iterator<Map.Entry<K,V>> iterator() { return entryIterator(); } public int size() { return size; } }; }
[ "public", "final", "Set", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ">", "entrySet", "(", ")", "{", "return", "new", "AbstractSet", "<", "Map", ".", "Entry", "<", "K", ",", "V", ">", ">", "(", ")", "{", "public", "Iterator", "<", "Map"...
Returns an unmodifiable set view of the map entries.
[ "Returns", "an", "unmodifiable", "set", "view", "of", "the", "map", "entries", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L321-L331
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/NoCompTreeMap.java
NoCompTreeMap.keySet
public final Set<K> keySet() { return new AbstractSet<K>() { public Iterator<K> iterator() { final Iterator<Map.Entry<K,V>> ite = entryIterator(); return new Iterator<K>() { public boolean hasNext() { return ite.hasNext(); } public void remove() { ite.remove(); } public K next() { return ite.next().getKey(); } }; } public int size() { return size; } }; }
java
public final Set<K> keySet() { return new AbstractSet<K>() { public Iterator<K> iterator() { final Iterator<Map.Entry<K,V>> ite = entryIterator(); return new Iterator<K>() { public boolean hasNext() { return ite.hasNext(); } public void remove() { ite.remove(); } public K next() { return ite.next().getKey(); } }; } public int size() { return size; } }; }
[ "public", "final", "Set", "<", "K", ">", "keySet", "(", ")", "{", "return", "new", "AbstractSet", "<", "K", ">", "(", ")", "{", "public", "Iterator", "<", "K", ">", "iterator", "(", ")", "{", "final", "Iterator", "<", "Map", ".", "Entry", "<", "K...
Returns an unmodifiable set view of the keys contained in this map.
[ "Returns", "an", "unmodifiable", "set", "view", "of", "the", "keys", "contained", "in", "this", "map", "." ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/NoCompTreeMap.java#L334-L348
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/modulebuilder/javascript/ExportModuleNameCompilerPass.java
ExportModuleNameCompilerPass.processChildren
public void processChildren(Node node) { for (Node cursor = node.getFirstChild(); cursor != null; cursor = cursor.getNext()) { if (cursor.getType() == Token.CALL) { // The node is a function or method call Node name = cursor.getFirstChild(); if (name != null && name.getType() == Token.NAME && // named function call name.getString().equals("define")) { // name is "define" //$NON-NLS-1$ Node param = name.getNext(); if (param != null && param.getType() != Token.STRING) { String expname = name.getProp(Node.SOURCENAME_PROP).toString(); if (source != null) { PositionLocator locator = source.locate(name.getLineno(), name.getCharno()+6); char tok = locator.findNextJSToken(); // move cursor to the open paren if (tok == '(') { // Try to insert the module name immediately following the open paren for the // define call because the param location will be off if the argument list is parenthesized. source.insert("\"" + expname + "\",", locator.getLineno(), locator.getCharno()+1); //$NON-NLS-1$ //$NON-NLS-2$ } else { // First token following 'define' name is not a paren, so fall back to inserting // before the first parameter. source.insert("\"" + expname + "\",", param.getLineno(), param.getCharno()); //$NON-NLS-1$ //$NON-NLS-2$ } } param.getParent().addChildBefore(Node.newString(expname), param); } } } // Recursively call this method to process the child nodes if (cursor.hasChildren()) processChildren(cursor); } }
java
public void processChildren(Node node) { for (Node cursor = node.getFirstChild(); cursor != null; cursor = cursor.getNext()) { if (cursor.getType() == Token.CALL) { // The node is a function or method call Node name = cursor.getFirstChild(); if (name != null && name.getType() == Token.NAME && // named function call name.getString().equals("define")) { // name is "define" //$NON-NLS-1$ Node param = name.getNext(); if (param != null && param.getType() != Token.STRING) { String expname = name.getProp(Node.SOURCENAME_PROP).toString(); if (source != null) { PositionLocator locator = source.locate(name.getLineno(), name.getCharno()+6); char tok = locator.findNextJSToken(); // move cursor to the open paren if (tok == '(') { // Try to insert the module name immediately following the open paren for the // define call because the param location will be off if the argument list is parenthesized. source.insert("\"" + expname + "\",", locator.getLineno(), locator.getCharno()+1); //$NON-NLS-1$ //$NON-NLS-2$ } else { // First token following 'define' name is not a paren, so fall back to inserting // before the first parameter. source.insert("\"" + expname + "\",", param.getLineno(), param.getCharno()); //$NON-NLS-1$ //$NON-NLS-2$ } } param.getParent().addChildBefore(Node.newString(expname), param); } } } // Recursively call this method to process the child nodes if (cursor.hasChildren()) processChildren(cursor); } }
[ "public", "void", "processChildren", "(", "Node", "node", ")", "{", "for", "(", "Node", "cursor", "=", "node", ".", "getFirstChild", "(", ")", ";", "cursor", "!=", "null", ";", "cursor", "=", "cursor", ".", "getNext", "(", ")", ")", "{", "if", "(", ...
Recursively called to process AST nodes looking for anonymous define calls. If an anonymous define call is found, then change it be a named define call, specifying the module name for the file being processed. @param node The node being processed
[ "Recursively", "called", "to", "process", "AST", "nodes", "looking", "for", "anonymous", "define", "calls", ".", "If", "an", "anonymous", "define", "call", "is", "found", "then", "change", "it", "be", "a", "named", "define", "call", "specifying", "the", "mod...
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/modulebuilder/javascript/ExportModuleNameCompilerPass.java#L50-L81
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/constraint/mttr/MovementGraph.java
MovementGraph.getIncoming
public List<IntVar> getIncoming(Node n) { List<IntVar> l = incoming.get(n); if (l == null) { l = Collections.emptyList(); } return l; }
java
public List<IntVar> getIncoming(Node n) { List<IntVar> l = incoming.get(n); if (l == null) { l = Collections.emptyList(); } return l; }
[ "public", "List", "<", "IntVar", ">", "getIncoming", "(", "Node", "n", ")", "{", "List", "<", "IntVar", ">", "l", "=", "incoming", ".", "get", "(", "n", ")", ";", "if", "(", "l", "==", "null", ")", "{", "l", "=", "Collections", ".", "emptyList", ...
Get the start moment of the movements that terminate on a given node @param n the destination node @return a list of start moment. May be empty
[ "Get", "the", "start", "moment", "of", "the", "movements", "that", "terminate", "on", "a", "given", "node" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/constraint/mttr/MovementGraph.java#L101-L107
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/constraint/mttr/MovementGraph.java
MovementGraph.getOutgoing
public List<IntVar> getOutgoing(Node n) { List<IntVar> l = outgoings.get(n); if (l == null) { l = Collections.emptyList(); } return l; }
java
public List<IntVar> getOutgoing(Node n) { List<IntVar> l = outgoings.get(n); if (l == null) { l = Collections.emptyList(); } return l; }
[ "public", "List", "<", "IntVar", ">", "getOutgoing", "(", "Node", "n", ")", "{", "List", "<", "IntVar", ">", "l", "=", "outgoings", ".", "get", "(", "n", ")", ";", "if", "(", "l", "==", "null", ")", "{", "l", "=", "Collections", ".", "emptyList",...
Get the start moment of the movements that leave from a given node @param n the source node @return a list of start moment. May be empty
[ "Get", "the", "start", "moment", "of", "the", "movements", "that", "leave", "from", "a", "given", "node" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/constraint/mttr/MovementGraph.java#L116-L123
train
btrplace/scheduler
api/src/main/java/org/btrplace/plan/ReconfigurationPlanChecker.java
ReconfigurationPlanChecker.checkModel
private void checkModel(Model mo, boolean start) throws SatConstraintViolationException { for (SatConstraintChecker<?> c : checkers) { if (start && !c.startsWith(mo)) { SatConstraint cs = c.getConstraint(); if (cs != null) { throw new DiscreteViolationException(c.getConstraint(), mo); } } else if (!start && !c.endsWith(mo)) { SatConstraint cs = c.getConstraint(); if (cs != null) { throw new DiscreteViolationException(c.getConstraint(), mo); } } } }
java
private void checkModel(Model mo, boolean start) throws SatConstraintViolationException { for (SatConstraintChecker<?> c : checkers) { if (start && !c.startsWith(mo)) { SatConstraint cs = c.getConstraint(); if (cs != null) { throw new DiscreteViolationException(c.getConstraint(), mo); } } else if (!start && !c.endsWith(mo)) { SatConstraint cs = c.getConstraint(); if (cs != null) { throw new DiscreteViolationException(c.getConstraint(), mo); } } } }
[ "private", "void", "checkModel", "(", "Model", "mo", ",", "boolean", "start", ")", "throws", "SatConstraintViolationException", "{", "for", "(", "SatConstraintChecker", "<", "?", ">", "c", ":", "checkers", ")", "{", "if", "(", "start", "&&", "!", "c", ".",...
Check for the validity of a model. @param mo the model to check @param start {@code true} iff the model corresponds to the origin model. Otherwise it is considered to be the resulting model @throws SatConstraintViolationException if at least one constraint is violated.
[ "Check", "for", "the", "validity", "of", "a", "model", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/plan/ReconfigurationPlanChecker.java#L339-L353
train
btrplace/scheduler
json/src/main/java/org/btrplace/json/model/ModelConverter.java
ModelConverter.toJSON
private static JSONObject toJSON(Mapping c) { JSONObject o = new JSONObject(); o.put("offlineNodes", nodesToJSON(c.getOfflineNodes())); o.put("readyVMs", vmsToJSON(c.getReadyVMs())); JSONObject ons = new JSONObject(); for (Node n : c.getOnlineNodes()) { JSONObject w = new JSONObject(); w.put("runningVMs", vmsToJSON(c.getRunningVMs(n))); w.put("sleepingVMs", vmsToJSON(c.getSleepingVMs(n))); ons.put(Integer.toString(n.id()), w); } o.put("onlineNodes", ons); return o; }
java
private static JSONObject toJSON(Mapping c) { JSONObject o = new JSONObject(); o.put("offlineNodes", nodesToJSON(c.getOfflineNodes())); o.put("readyVMs", vmsToJSON(c.getReadyVMs())); JSONObject ons = new JSONObject(); for (Node n : c.getOnlineNodes()) { JSONObject w = new JSONObject(); w.put("runningVMs", vmsToJSON(c.getRunningVMs(n))); w.put("sleepingVMs", vmsToJSON(c.getSleepingVMs(n))); ons.put(Integer.toString(n.id()), w); } o.put("onlineNodes", ons); return o; }
[ "private", "static", "JSONObject", "toJSON", "(", "Mapping", "c", ")", "{", "JSONObject", "o", "=", "new", "JSONObject", "(", ")", ";", "o", ".", "put", "(", "\"offlineNodes\"", ",", "nodesToJSON", "(", "c", ".", "getOfflineNodes", "(", ")", ")", ")", ...
Serialise the mapping. @param c the mapping @return the resulting JSONObject
[ "Serialise", "the", "mapping", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/model/ModelConverter.java#L120-L134
train
btrplace/scheduler
json/src/main/java/org/btrplace/json/model/ModelConverter.java
ModelConverter.fillMapping
public void fillMapping(Model mo, JSONObject o) throws JSONConverterException { Mapping c = mo.getMapping(); for (Node u : newNodes(mo, o, "offlineNodes")) { c.addOfflineNode(u); } for (VM u : newVMs(mo, o, "readyVMs")) { c.addReadyVM(u); } JSONObject ons = (JSONObject) o.get("onlineNodes"); for (Map.Entry<String, Object> e : ons.entrySet()) { int id = Integer.parseInt(e.getKey()); Node u = mo.newNode(id); if (u == null) { throw JSONConverterException.nodeAlreadyDeclared(id); } JSONObject on = (JSONObject) e.getValue(); c.addOnlineNode(u); for (VM vm : newVMs(mo, on, "runningVMs")) { c.addRunningVM(vm, u); } for (VM vm : newVMs(mo, on, "sleepingVMs")) { c.addSleepingVM(vm, u); } } }
java
public void fillMapping(Model mo, JSONObject o) throws JSONConverterException { Mapping c = mo.getMapping(); for (Node u : newNodes(mo, o, "offlineNodes")) { c.addOfflineNode(u); } for (VM u : newVMs(mo, o, "readyVMs")) { c.addReadyVM(u); } JSONObject ons = (JSONObject) o.get("onlineNodes"); for (Map.Entry<String, Object> e : ons.entrySet()) { int id = Integer.parseInt(e.getKey()); Node u = mo.newNode(id); if (u == null) { throw JSONConverterException.nodeAlreadyDeclared(id); } JSONObject on = (JSONObject) e.getValue(); c.addOnlineNode(u); for (VM vm : newVMs(mo, on, "runningVMs")) { c.addRunningVM(vm, u); } for (VM vm : newVMs(mo, on, "sleepingVMs")) { c.addSleepingVM(vm, u); } } }
[ "public", "void", "fillMapping", "(", "Model", "mo", ",", "JSONObject", "o", ")", "throws", "JSONConverterException", "{", "Mapping", "c", "=", "mo", ".", "getMapping", "(", ")", ";", "for", "(", "Node", "u", ":", "newNodes", "(", "mo", ",", "o", ",", ...
Create the elements inside the model and fill the mapping. @param mo the model where to attach the elements @param o the json describing the mapping @throws JSONConverterException
[ "Create", "the", "elements", "inside", "the", "model", "and", "fill", "the", "mapping", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/model/ModelConverter.java#L143-L167
train
btrplace/scheduler
json/src/main/java/org/btrplace/json/model/ModelConverter.java
ModelConverter.newNodes
private static Set<Node> newNodes(Model mo, JSONObject o, String key) throws JSONConverterException { checkKeys(o, key); Object x = o.get(key); if (!(x instanceof JSONArray)) { throw new JSONConverterException("array expected at key '" + key + "'"); } Set<Node> s = new HashSet<>(((JSONArray) x).size()); for (Object i : (JSONArray) x) { int id = (Integer) i; Node n = mo.newNode(id); if (n == null) { throw JSONConverterException.nodeAlreadyDeclared(id); } s.add(n); } return s; }
java
private static Set<Node> newNodes(Model mo, JSONObject o, String key) throws JSONConverterException { checkKeys(o, key); Object x = o.get(key); if (!(x instanceof JSONArray)) { throw new JSONConverterException("array expected at key '" + key + "'"); } Set<Node> s = new HashSet<>(((JSONArray) x).size()); for (Object i : (JSONArray) x) { int id = (Integer) i; Node n = mo.newNode(id); if (n == null) { throw JSONConverterException.nodeAlreadyDeclared(id); } s.add(n); } return s; }
[ "private", "static", "Set", "<", "Node", ">", "newNodes", "(", "Model", "mo", ",", "JSONObject", "o", ",", "String", "key", ")", "throws", "JSONConverterException", "{", "checkKeys", "(", "o", ",", "key", ")", ";", "Object", "x", "=", "o", ".", "get", ...
Build nodes from a key. @param mo the model to build @param o the object that contains the node @param key the key associated to the nodes @return the resulting set of nodes @throws JSONConverterException if at least one of the parsed node already exists
[ "Build", "nodes", "from", "a", "key", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/model/ModelConverter.java#L178-L194
train
btrplace/scheduler
json/src/main/java/org/btrplace/json/model/ModelConverter.java
ModelConverter.newVMs
private static Set<VM> newVMs(Model mo, JSONObject o, String key) throws JSONConverterException { checkKeys(o, key); Object x = o.get(key); if (!(x instanceof JSONArray)) { throw new JSONConverterException("array expected at key '" + key + "'"); } Set<VM> s = new HashSet<>(((JSONArray) x).size()); for (Object i : (JSONArray) x) { int id = (Integer) i; VM vm = mo.newVM(id); if (vm == null) { throw JSONConverterException.vmAlreadyDeclared(id); } s.add(vm); } return s; }
java
private static Set<VM> newVMs(Model mo, JSONObject o, String key) throws JSONConverterException { checkKeys(o, key); Object x = o.get(key); if (!(x instanceof JSONArray)) { throw new JSONConverterException("array expected at key '" + key + "'"); } Set<VM> s = new HashSet<>(((JSONArray) x).size()); for (Object i : (JSONArray) x) { int id = (Integer) i; VM vm = mo.newVM(id); if (vm == null) { throw JSONConverterException.vmAlreadyDeclared(id); } s.add(vm); } return s; }
[ "private", "static", "Set", "<", "VM", ">", "newVMs", "(", "Model", "mo", ",", "JSONObject", "o", ",", "String", "key", ")", "throws", "JSONConverterException", "{", "checkKeys", "(", "o", ",", "key", ")", ";", "Object", "x", "=", "o", ".", "get", "(...
Build VMs from a key. @param mo the model to build @param o the object that contains the vm @param key the key associated to the VMs @return the resulting set of VMs @throws JSONConverterException if at least one of the parsed VM already exists
[ "Build", "VMs", "from", "a", "key", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/model/ModelConverter.java#L205-L222
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java
ModuleDeps.add
public boolean add(String key, ModuleDepInfo info) { if (info == null) { throw new NullPointerException(); } boolean modified = false; ModuleDepInfo existing = get(key); if (!containsKey(key) || existing != info) { if (existing != null) { modified = existing.add(info); } else { super.put(key, info); modified = true; } } return modified; }
java
public boolean add(String key, ModuleDepInfo info) { if (info == null) { throw new NullPointerException(); } boolean modified = false; ModuleDepInfo existing = get(key); if (!containsKey(key) || existing != info) { if (existing != null) { modified = existing.add(info); } else { super.put(key, info); modified = true; } } return modified; }
[ "public", "boolean", "add", "(", "String", "key", ",", "ModuleDepInfo", "info", ")", "{", "if", "(", "info", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", ")", ";", "}", "boolean", "modified", "=", "false", ";", "ModuleDepInfo", "e...
Adds the specified pair to the map. If an entry for the key exists, then the specified module dep info is added to the existing module dep info. @param key The module name to associate with the dep info object @param info the ModuleDepInfo object @return true if the map was modified
[ "Adds", "the", "specified", "pair", "to", "the", "map", ".", "If", "an", "entry", "for", "the", "key", "exists", "then", "the", "specified", "module", "dep", "info", "is", "added", "to", "the", "existing", "module", "dep", "info", "." ]
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java#L66-L81
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java
ModuleDeps.addAll
public boolean addAll(ModuleDeps other) { boolean modified = false; for (Map.Entry<String, ModuleDepInfo> entry : other.entrySet()) { modified |= add(entry.getKey(), new ModuleDepInfo(entry.getValue())); } return modified; }
java
public boolean addAll(ModuleDeps other) { boolean modified = false; for (Map.Entry<String, ModuleDepInfo> entry : other.entrySet()) { modified |= add(entry.getKey(), new ModuleDepInfo(entry.getValue())); } return modified; }
[ "public", "boolean", "addAll", "(", "ModuleDeps", "other", ")", "{", "boolean", "modified", "=", "false", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "ModuleDepInfo", ">", "entry", ":", "other", ".", "entrySet", "(", ")", ")", "{", "modif...
Adds all of the map entries from other to this map @param other the map containing entries to add @return true if the map was modified
[ "Adds", "all", "of", "the", "map", "entries", "from", "other", "to", "this", "map" ]
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/deps/ModuleDeps.java#L90-L96
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java
CShareableResource.minVMAllocation
public int minVMAllocation(int vmIdx, int v) { int vv = Math.max(v, vmAllocation.get(vmIdx)); vmAllocation.set(vmIdx, vv); return vv; }
java
public int minVMAllocation(int vmIdx, int v) { int vv = Math.max(v, vmAllocation.get(vmIdx)); vmAllocation.set(vmIdx, vv); return vv; }
[ "public", "int", "minVMAllocation", "(", "int", "vmIdx", ",", "int", "v", ")", "{", "int", "vv", "=", "Math", ".", "max", "(", "v", ",", "vmAllocation", ".", "get", "(", "vmIdx", ")", ")", ";", "vmAllocation", ".", "set", "(", "vmIdx", ",", "vv", ...
Change the VM resource allocation. @param vmIdx the VM identifier @param v the amount to ask. @return the retained value. May be bigger than {@code v} if a previous call asks for more
[ "Change", "the", "VM", "resource", "allocation", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java#L221-L225
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java
CShareableResource.capOverbookRatio
public double capOverbookRatio(int nIdx, double d) { if (d < 1) { return ratios.get(nIdx); } double v = Math.min(ratios.get(nIdx), d); ratios.set(nIdx, v); return v; }
java
public double capOverbookRatio(int nIdx, double d) { if (d < 1) { return ratios.get(nIdx); } double v = Math.min(ratios.get(nIdx), d); ratios.set(nIdx, v); return v; }
[ "public", "double", "capOverbookRatio", "(", "int", "nIdx", ",", "double", "d", ")", "{", "if", "(", "d", "<", "1", ")", "{", "return", "ratios", ".", "get", "(", "nIdx", ")", ";", "}", "double", "v", "=", "Math", ".", "min", "(", "ratios", ".", ...
Cap the overbooking ratio for a given node. @param nIdx the node @param d the new ratio. {@code >= 1} @return the resulting ratio. Will be lower than {@code d} if a previous cap stated a lower value
[ "Cap", "the", "overbooking", "ratio", "for", "a", "given", "node", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java#L243-L250
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java
CShareableResource.beforeSolve
@Override public boolean beforeSolve(ReconfigurationProblem p) throws SchedulerException { for (VM vm : source.getMapping().getAllVMs()) { int vmId = p.getVM(vm); int v = getVMAllocation(vmId); if (v < 0) { int prevUsage = rc.getConsumption(vm); minVMAllocation(vmId, prevUsage); } } ChocoView v = rp.getView(Packing.VIEW_ID); if (v == null) { throw SchedulerModelingException.missingView(rp.getSourceModel(), Packing.VIEW_ID); } IntVar[] host = new IntVar[p.getFutureRunningVMs().size()]; int[] demand = new int[host.length]; int i = 0; for (VM vm : p.getFutureRunningVMs()) { host[i] = rp.getVMAction(vm).getDSlice().getHoster(); demand[i] = getVMAllocation(p.getVM(vm)); i++; } ((Packing) v).addDim(rc.getResourceIdentifier(), virtRcUsage, demand, host); return linkVirtualToPhysicalUsage(); }
java
@Override public boolean beforeSolve(ReconfigurationProblem p) throws SchedulerException { for (VM vm : source.getMapping().getAllVMs()) { int vmId = p.getVM(vm); int v = getVMAllocation(vmId); if (v < 0) { int prevUsage = rc.getConsumption(vm); minVMAllocation(vmId, prevUsage); } } ChocoView v = rp.getView(Packing.VIEW_ID); if (v == null) { throw SchedulerModelingException.missingView(rp.getSourceModel(), Packing.VIEW_ID); } IntVar[] host = new IntVar[p.getFutureRunningVMs().size()]; int[] demand = new int[host.length]; int i = 0; for (VM vm : p.getFutureRunningVMs()) { host[i] = rp.getVMAction(vm).getDSlice().getHoster(); demand[i] = getVMAllocation(p.getVM(vm)); i++; } ((Packing) v).addDim(rc.getResourceIdentifier(), virtRcUsage, demand, host); return linkVirtualToPhysicalUsage(); }
[ "@", "Override", "public", "boolean", "beforeSolve", "(", "ReconfigurationProblem", "p", ")", "throws", "SchedulerException", "{", "for", "(", "VM", "vm", ":", "source", ".", "getMapping", "(", ")", ".", "getAllVMs", "(", ")", ")", "{", "int", "vmId", "=",...
Set the resource usage for each of the VM. If the LB is < 0 , the previous consumption is used to maintain the resource usage. Otherwise, the usage is set to the variable lower bound. @return false if an operation leads to a problem without solution
[ "Set", "the", "resource", "usage", "for", "each", "of", "the", "VM", ".", "If", "the", "LB", "is", "<", "0", "the", "previous", "consumption", "is", "used", "to", "maintain", "the", "resource", "usage", ".", "Otherwise", "the", "usage", "is", "set", "t...
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java#L269-L300
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java
CShareableResource.capHosting
private boolean capHosting(int nIdx, int min, int nbZeroes) { Node n = rp.getNode(nIdx); double capa = getSourceResource().getCapacity(n) * getOverbookRatio(nIdx)/*.getLB()*/; int card = (int) (capa / min) + nbZeroes + 1; if (card < source.getMapping().getRunningVMs(n).size()) { // This shortcut is required to prevent a filtering issue in the scheduling phase: // At time 0, LocalTaskScheduler will complain and start to backtrack. // TODO: revise the notion of continuous constraint for the cardinality issue. return true; } try { //Restrict the hosting capacity. rp.getNbRunningVMs().get(nIdx).updateUpperBound(card, Cause.Null); } catch (ContradictionException ex) { rp.getLogger().error("Unable to cap the hosting capacity of '" + n + " ' to " + card, ex); return false; } return true; }
java
private boolean capHosting(int nIdx, int min, int nbZeroes) { Node n = rp.getNode(nIdx); double capa = getSourceResource().getCapacity(n) * getOverbookRatio(nIdx)/*.getLB()*/; int card = (int) (capa / min) + nbZeroes + 1; if (card < source.getMapping().getRunningVMs(n).size()) { // This shortcut is required to prevent a filtering issue in the scheduling phase: // At time 0, LocalTaskScheduler will complain and start to backtrack. // TODO: revise the notion of continuous constraint for the cardinality issue. return true; } try { //Restrict the hosting capacity. rp.getNbRunningVMs().get(nIdx).updateUpperBound(card, Cause.Null); } catch (ContradictionException ex) { rp.getLogger().error("Unable to cap the hosting capacity of '" + n + " ' to " + card, ex); return false; } return true; }
[ "private", "boolean", "capHosting", "(", "int", "nIdx", ",", "int", "min", ",", "int", "nbZeroes", ")", "{", "Node", "n", "=", "rp", ".", "getNode", "(", "nIdx", ")", ";", "double", "capa", "=", "getSourceResource", "(", ")", ".", "getCapacity", "(", ...
Reduce the cardinality wrt. the worst case scenario. @param nIdx the node index @param min the min (but > 0 ) consumption for a VM @param nbZeroes the number of VMs consuming 0 @return {@code false} if the problem no longer has a solution
[ "Reduce", "the", "cardinality", "wrt", ".", "the", "worst", "case", "scenario", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java#L372-L390
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java
CShareableResource.checkInitialSatisfaction
private void checkInitialSatisfaction() { //Seems to me we don't support ratio change for (Node n : rp.getSourceModel().getMapping().getOnlineNodes()) { int nIdx = rp.getNode(n); double ratio = getOverbookRatio(nIdx)/*.getLB()*/; double capa = getSourceResource().getCapacity(n) * ratio; int usage = 0; for (VM vm : rp.getSourceModel().getMapping().getRunningVMs(n)) { usage += getSourceResource().getConsumption(vm); if (usage > capa) { //Here, the problem is not feasible but we consider an exception //because such a situation does not physically makes sense (one cannot run at 110%) throw new SchedulerModelingException(rp.getSourceModel(), "Usage of virtual resource " + getResourceIdentifier() + " on node " + n + " (" + usage + ") exceeds its capacity (" + capa + ")"); } } } }
java
private void checkInitialSatisfaction() { //Seems to me we don't support ratio change for (Node n : rp.getSourceModel().getMapping().getOnlineNodes()) { int nIdx = rp.getNode(n); double ratio = getOverbookRatio(nIdx)/*.getLB()*/; double capa = getSourceResource().getCapacity(n) * ratio; int usage = 0; for (VM vm : rp.getSourceModel().getMapping().getRunningVMs(n)) { usage += getSourceResource().getConsumption(vm); if (usage > capa) { //Here, the problem is not feasible but we consider an exception //because such a situation does not physically makes sense (one cannot run at 110%) throw new SchedulerModelingException(rp.getSourceModel(), "Usage of virtual resource " + getResourceIdentifier() + " on node " + n + " (" + usage + ") exceeds its capacity (" + capa + ")"); } } } }
[ "private", "void", "checkInitialSatisfaction", "(", ")", "{", "//Seems to me we don't support ratio change", "for", "(", "Node", "n", ":", "rp", ".", "getSourceModel", "(", ")", ".", "getMapping", "(", ")", ".", "getOnlineNodes", "(", ")", ")", "{", "int", "nI...
Check if the initial capacity > sum current consumption The ratio is instantiated now so the computation is correct
[ "Check", "if", "the", "initial", "capacity", ">", "sum", "current", "consumption", "The", "ratio", "is", "instantiated", "now", "so", "the", "computation", "is", "correct" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java#L444-L460
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java
CShareableResource.getWeights
public static TObjectIntMap<VM> getWeights(ReconfigurationProblem rp, List<CShareableResource> rcs) { Model mo = rp.getSourceModel(); int[] capa = new int[rcs.size()]; int[] cons = new int[rcs.size()]; TObjectIntMap<VM> cost = new TObjectIntHashMap<>(); for (Node n : mo.getMapping().getAllNodes()) { for (int i = 0; i < rcs.size(); i++) { capa[i] += rcs.get(i).virtRcUsage.get(rp.getNode(n)).getUB() * rcs.get(i).ratios.get(rp.getNode(n))/*.getLB()*/; } } for (VM v : mo.getMapping().getAllVMs()) { for (int i = 0; i < rcs.size(); i++) { cons[i] += rcs.get(i).getVMAllocation(rp.getVM(v)); } } for (VM v : mo.getMapping().getAllVMs()) { double sum = 0; for (int i = 0; i < rcs.size(); i++) { double ratio = 0; if (cons[i] > 0) { ratio = 1.0 * rcs.get(i).getVMAllocation(rp.getVM(v)) / capa[i]; } sum += ratio; } cost.put(v, (int) (sum * 10000)); } return cost; }
java
public static TObjectIntMap<VM> getWeights(ReconfigurationProblem rp, List<CShareableResource> rcs) { Model mo = rp.getSourceModel(); int[] capa = new int[rcs.size()]; int[] cons = new int[rcs.size()]; TObjectIntMap<VM> cost = new TObjectIntHashMap<>(); for (Node n : mo.getMapping().getAllNodes()) { for (int i = 0; i < rcs.size(); i++) { capa[i] += rcs.get(i).virtRcUsage.get(rp.getNode(n)).getUB() * rcs.get(i).ratios.get(rp.getNode(n))/*.getLB()*/; } } for (VM v : mo.getMapping().getAllVMs()) { for (int i = 0; i < rcs.size(); i++) { cons[i] += rcs.get(i).getVMAllocation(rp.getVM(v)); } } for (VM v : mo.getMapping().getAllVMs()) { double sum = 0; for (int i = 0; i < rcs.size(); i++) { double ratio = 0; if (cons[i] > 0) { ratio = 1.0 * rcs.get(i).getVMAllocation(rp.getVM(v)) / capa[i]; } sum += ratio; } cost.put(v, (int) (sum * 10000)); } return cost; }
[ "public", "static", "TObjectIntMap", "<", "VM", ">", "getWeights", "(", "ReconfigurationProblem", "rp", ",", "List", "<", "CShareableResource", ">", "rcs", ")", "{", "Model", "mo", "=", "rp", ".", "getSourceModel", "(", ")", ";", "int", "[", "]", "capa", ...
Estimate the weight of each VMs with regards to multiple dimensions. In practice, it sums the normalised size of each VM against the total capacity @param rp the problem to solve @param rcs the resources to consider @return a weight per VM
[ "Estimate", "the", "weight", "of", "each", "VMs", "with", "regards", "to", "multiple", "dimensions", ".", "In", "practice", "it", "sums", "the", "normalised", "size", "of", "each", "VM", "against", "the", "total", "capacity" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/view/CShareableResource.java#L596-L626
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java
DefaultReconfigurationProblem.distinctVMStates
private boolean distinctVMStates() { boolean ok = vms.size() == running.size() + sleeping.size() + ready.size() + killed.size(); //It is sure there is no solution as a VM cannot have multiple destination state Map<VM, VMState> states = new HashMap<>(); for (VM v : running) { states.put(v, VMState.RUNNING); } for (VM v : ready) { VMState prev = states.put(v, VMState.READY); if (prev != null) { getLogger().debug("multiple destination state for {}: {} and {}", v, prev, VMState.READY); } } for (VM v : sleeping) { VMState prev = states.put(v, VMState.SLEEPING); if (prev != null) { getLogger().debug("multiple destination state for {}: {} and {}", v, prev, VMState.SLEEPING); } } for (VM v : killed) { VMState prev = states.put(v, VMState.KILLED); if (prev != null) { getLogger().debug("multiple destination state for {}: {} and {}", v, prev, VMState.KILLED); } } return ok; }
java
private boolean distinctVMStates() { boolean ok = vms.size() == running.size() + sleeping.size() + ready.size() + killed.size(); //It is sure there is no solution as a VM cannot have multiple destination state Map<VM, VMState> states = new HashMap<>(); for (VM v : running) { states.put(v, VMState.RUNNING); } for (VM v : ready) { VMState prev = states.put(v, VMState.READY); if (prev != null) { getLogger().debug("multiple destination state for {}: {} and {}", v, prev, VMState.READY); } } for (VM v : sleeping) { VMState prev = states.put(v, VMState.SLEEPING); if (prev != null) { getLogger().debug("multiple destination state for {}: {} and {}", v, prev, VMState.SLEEPING); } } for (VM v : killed) { VMState prev = states.put(v, VMState.KILLED); if (prev != null) { getLogger().debug("multiple destination state for {}: {} and {}", v, prev, VMState.KILLED); } } return ok; }
[ "private", "boolean", "distinctVMStates", "(", ")", "{", "boolean", "ok", "=", "vms", ".", "size", "(", ")", "==", "running", ".", "size", "(", ")", "+", "sleeping", ".", "size", "(", ")", "+", "ready", ".", "size", "(", ")", "+", "killed", ".", ...
Check if every VM has a single destination state @return {@code true} if states are distinct
[ "Check", "if", "every", "VM", "has", "a", "single", "destination", "state" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java#L244-L273
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java
DefaultReconfigurationProblem.buildReconfigurationPlan
@Override @SuppressWarnings("squid:S3346") public ReconfigurationPlan buildReconfigurationPlan(Solution s, Model src) throws SchedulerException { ReconfigurationPlan plan = new DefaultReconfigurationPlan(src); for (NodeTransition action : nodeActions) { action.insertActions(s, plan); } for (VMTransition action : vmActions) { action.insertActions(s, plan); } assert plan.isApplyable() : "The following plan cannot be applied:\n" + plan; assert checkConsistency(s, plan); return plan; }
java
@Override @SuppressWarnings("squid:S3346") public ReconfigurationPlan buildReconfigurationPlan(Solution s, Model src) throws SchedulerException { ReconfigurationPlan plan = new DefaultReconfigurationPlan(src); for (NodeTransition action : nodeActions) { action.insertActions(s, plan); } for (VMTransition action : vmActions) { action.insertActions(s, plan); } assert plan.isApplyable() : "The following plan cannot be applied:\n" + plan; assert checkConsistency(s, plan); return plan; }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"squid:S3346\"", ")", "public", "ReconfigurationPlan", "buildReconfigurationPlan", "(", "Solution", "s", ",", "Model", "src", ")", "throws", "SchedulerException", "{", "ReconfigurationPlan", "plan", "=", "new", "Default...
Build a plan for a solution. @param s the solution @param src the source model @return the resulting plan @throws SchedulerException if a error occurred
[ "Build", "a", "plan", "for", "a", "solution", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java#L304-L319
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java
DefaultReconfigurationProblem.defaultHeuristic
private void defaultHeuristic() { IntStrategy intStrat = Search.intVarSearch(new FirstFail(csp), new IntDomainMin(), csp.retrieveIntVars(true)); SetStrategy setStrat = new SetStrategy(csp.retrieveSetVars(), new InputOrder<>(csp), new SetDomainMin(), true); RealStrategy realStrat = new RealStrategy(csp.retrieveRealVars(), new Occurrence<>(), new RealDomainMiddle()); solver.setSearch(new StrategiesSequencer(intStrat, realStrat, setStrat)); }
java
private void defaultHeuristic() { IntStrategy intStrat = Search.intVarSearch(new FirstFail(csp), new IntDomainMin(), csp.retrieveIntVars(true)); SetStrategy setStrat = new SetStrategy(csp.retrieveSetVars(), new InputOrder<>(csp), new SetDomainMin(), true); RealStrategy realStrat = new RealStrategy(csp.retrieveRealVars(), new Occurrence<>(), new RealDomainMiddle()); solver.setSearch(new StrategiesSequencer(intStrat, realStrat, setStrat)); }
[ "private", "void", "defaultHeuristic", "(", ")", "{", "IntStrategy", "intStrat", "=", "Search", ".", "intVarSearch", "(", "new", "FirstFail", "(", "csp", ")", ",", "new", "IntDomainMin", "(", ")", ",", "csp", ".", "retrieveIntVars", "(", "true", ")", ")", ...
A naive heuristic to be sure every variables will be instantiated.
[ "A", "naive", "heuristic", "to", "be", "sure", "every", "variables", "will", "be", "instantiated", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java#L324-L329
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java
DefaultReconfigurationProblem.makeCardinalityVariables
private void makeCardinalityVariables() { vmsCountOnNodes = new ArrayList<>(nodes.size()); int nbVMs = vms.size(); for (Node n : nodes) { vmsCountOnNodes.add(csp.intVar(makeVarLabel("nbVMsOn('", n, "')"), 0, nbVMs, true)); } vmsCountOnNodes = Collections.unmodifiableList(vmsCountOnNodes); }
java
private void makeCardinalityVariables() { vmsCountOnNodes = new ArrayList<>(nodes.size()); int nbVMs = vms.size(); for (Node n : nodes) { vmsCountOnNodes.add(csp.intVar(makeVarLabel("nbVMsOn('", n, "')"), 0, nbVMs, true)); } vmsCountOnNodes = Collections.unmodifiableList(vmsCountOnNodes); }
[ "private", "void", "makeCardinalityVariables", "(", ")", "{", "vmsCountOnNodes", "=", "new", "ArrayList", "<>", "(", "nodes", ".", "size", "(", ")", ")", ";", "int", "nbVMs", "=", "vms", ".", "size", "(", ")", ";", "for", "(", "Node", "n", ":", "node...
Create the cardinality variables.
[ "Create", "the", "cardinality", "variables", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/DefaultReconfigurationProblem.java#L367-L374
train
btrplace/scheduler
api/src/main/java/org/btrplace/plan/DefaultReconfigurationPlan.java
DefaultReconfigurationPlan.iterator
@Override public Iterator<Action> iterator() { Set<Action> sorted = new TreeSet<>(startFirstComparator); sorted.addAll(actions); return sorted.iterator(); }
java
@Override public Iterator<Action> iterator() { Set<Action> sorted = new TreeSet<>(startFirstComparator); sorted.addAll(actions); return sorted.iterator(); }
[ "@", "Override", "public", "Iterator", "<", "Action", ">", "iterator", "(", ")", "{", "Set", "<", "Action", ">", "sorted", "=", "new", "TreeSet", "<>", "(", "startFirstComparator", ")", ";", "sorted", ".", "addAll", "(", "actions", ")", ";", "return", ...
Iterate over the actions. The action are automatically sorted increasingly by their starting moment. @return an iterator.
[ "Iterate", "over", "the", "actions", ".", "The", "action", "are", "automatically", "sorted", "increasingly", "by", "their", "starting", "moment", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/plan/DefaultReconfigurationPlan.java#L115-L120
train
InsightLab/graphast
core/src/main/java/br/ufc/insightlab/graphast/structure/MMapGraphStructure.java
MMapGraphStructure.addDirectionalEdge
private void addDirectionalEdge(Edge e) { if (edgeAccess.getCapacity() < getEdgeIndex(edgePos) + EDGE_SIZE) edgeAccess.ensureCapacity(edgeAccess.getCapacity() + INITIAL_EDGE_FILE_SIZE); long fromId = nodIdMapping.get(e.getFromNodeId()); long toId = nodIdMapping.get(e.getToNodeId()); long fromIndex = getNodeIndex(fromId); long toIndex = getNodeIndex(toId); long edgeIndex = getEdgeIndex(edgePos); edgeAccess.setLong ( edgeIndex , fromId ); edgeAccess.setLong ( edgeIndex + 8 , toId ); edgeAccess.setDouble ( edgeIndex + 16 , e.getWeight() ); edgeAccess.setLong ( edgeIndex + 24 , nodeAccess.getLong(fromIndex + 8) ); edgeAccess.setLong ( edgeIndex + 32 , nodeAccess.getLong(toIndex + 16) ); nodeAccess.setLong( fromIndex + 8 , edgePos); nodeAccess.setLong( toIndex + 16 , edgePos); edgeAccess.setLong( 0 , ++edgePos ); }
java
private void addDirectionalEdge(Edge e) { if (edgeAccess.getCapacity() < getEdgeIndex(edgePos) + EDGE_SIZE) edgeAccess.ensureCapacity(edgeAccess.getCapacity() + INITIAL_EDGE_FILE_SIZE); long fromId = nodIdMapping.get(e.getFromNodeId()); long toId = nodIdMapping.get(e.getToNodeId()); long fromIndex = getNodeIndex(fromId); long toIndex = getNodeIndex(toId); long edgeIndex = getEdgeIndex(edgePos); edgeAccess.setLong ( edgeIndex , fromId ); edgeAccess.setLong ( edgeIndex + 8 , toId ); edgeAccess.setDouble ( edgeIndex + 16 , e.getWeight() ); edgeAccess.setLong ( edgeIndex + 24 , nodeAccess.getLong(fromIndex + 8) ); edgeAccess.setLong ( edgeIndex + 32 , nodeAccess.getLong(toIndex + 16) ); nodeAccess.setLong( fromIndex + 8 , edgePos); nodeAccess.setLong( toIndex + 16 , edgePos); edgeAccess.setLong( 0 , ++edgePos ); }
[ "private", "void", "addDirectionalEdge", "(", "Edge", "e", ")", "{", "if", "(", "edgeAccess", ".", "getCapacity", "(", ")", "<", "getEdgeIndex", "(", "edgePos", ")", "+", "EDGE_SIZE", ")", "edgeAccess", ".", "ensureCapacity", "(", "edgeAccess", ".", "getCapa...
Add a new directional edge into the graph. @param e the edge that will be added into the graph.
[ "Add", "a", "new", "directional", "edge", "into", "the", "graph", "." ]
b81d10c1ea8378e1fb9fcb545dd75d5e6308fd24
https://github.com/InsightLab/graphast/blob/b81d10c1ea8378e1fb9fcb545dd75d5e6308fd24/core/src/main/java/br/ufc/insightlab/graphast/structure/MMapGraphStructure.java#L132-L156
train
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/constraint/DefaultConstraintsCatalog.java
DefaultConstraintsCatalog.newBundle
public static DefaultConstraintsCatalog newBundle() { DefaultConstraintsCatalog c = new DefaultConstraintsCatalog(); c.add(new AmongBuilder()); c.add(new BanBuilder()); c.add(new ResourceCapacityBuilder()); c.add(new RunningCapacityBuilder()); c.add(new FenceBuilder()); c.add(new GatherBuilder()); c.add(new KilledBuilder()); c.add(new LonelyBuilder()); c.add(new OfflineBuilder()); c.add(new OnlineBuilder()); c.add(new OverbookBuilder()); c.add(new PreserveBuilder()); c.add(new QuarantineBuilder()); c.add(new ReadyBuilder()); c.add(new RootBuilder()); c.add(new RunningBuilder()); c.add(new SleepingBuilder()); c.add(new SplitBuilder()); c.add(new SplitAmongBuilder()); c.add(new SpreadBuilder()); c.add(new SeqBuilder()); c.add(new MaxOnlineBuilder()); c.add(new NoDelayBuilder()); c.add(new BeforeBuilder()); c.add(new SerializeBuilder()); c.add(new SyncBuilder()); return c; }
java
public static DefaultConstraintsCatalog newBundle() { DefaultConstraintsCatalog c = new DefaultConstraintsCatalog(); c.add(new AmongBuilder()); c.add(new BanBuilder()); c.add(new ResourceCapacityBuilder()); c.add(new RunningCapacityBuilder()); c.add(new FenceBuilder()); c.add(new GatherBuilder()); c.add(new KilledBuilder()); c.add(new LonelyBuilder()); c.add(new OfflineBuilder()); c.add(new OnlineBuilder()); c.add(new OverbookBuilder()); c.add(new PreserveBuilder()); c.add(new QuarantineBuilder()); c.add(new ReadyBuilder()); c.add(new RootBuilder()); c.add(new RunningBuilder()); c.add(new SleepingBuilder()); c.add(new SplitBuilder()); c.add(new SplitAmongBuilder()); c.add(new SpreadBuilder()); c.add(new SeqBuilder()); c.add(new MaxOnlineBuilder()); c.add(new NoDelayBuilder()); c.add(new BeforeBuilder()); c.add(new SerializeBuilder()); c.add(new SyncBuilder()); return c; }
[ "public", "static", "DefaultConstraintsCatalog", "newBundle", "(", ")", "{", "DefaultConstraintsCatalog", "c", "=", "new", "DefaultConstraintsCatalog", "(", ")", ";", "c", ".", "add", "(", "new", "AmongBuilder", "(", ")", ")", ";", "c", ".", "add", "(", "new...
Build a catalog with a builder for every constraints in the current BtrPlace bundle. @return a fulfilled catalog
[ "Build", "a", "catalog", "with", "a", "builder", "for", "every", "constraints", "in", "the", "current", "BtrPlace", "bundle", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/constraint/DefaultConstraintsCatalog.java#L55-L84
train
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/constraint/DefaultConstraintsCatalog.java
DefaultConstraintsCatalog.add
public boolean add(SatConstraintBuilder c) { if (this.builders.containsKey(c.getIdentifier())) { return false; } this.builders.put(c.getIdentifier(), c); return true; }
java
public boolean add(SatConstraintBuilder c) { if (this.builders.containsKey(c.getIdentifier())) { return false; } this.builders.put(c.getIdentifier(), c); return true; }
[ "public", "boolean", "add", "(", "SatConstraintBuilder", "c", ")", "{", "if", "(", "this", ".", "builders", ".", "containsKey", "(", "c", ".", "getIdentifier", "(", ")", ")", ")", "{", "return", "false", ";", "}", "this", ".", "builders", ".", "put", ...
Add a constraint builder to the catalog. There must not be another builder with the same identifier in the catalog @param c the constraint to add @return true if the builder has been added.
[ "Add", "a", "constraint", "builder", "to", "the", "catalog", ".", "There", "must", "not", "be", "another", "builder", "with", "the", "same", "identifier", "in", "the", "catalog" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/constraint/DefaultConstraintsCatalog.java#L93-L99
train
protegeproject/jpaul
src/main/java/jpaul/Misc/UComp.java
UComp.compare
public int compare(T o1, T o2) { if(o1 == o2) return 0; String str1 = (o1 == null) ? "null" : o1.toString(); String str2 = (o2 == null) ? "null" : o2.toString(); return str1.compareTo(str2); }
java
public int compare(T o1, T o2) { if(o1 == o2) return 0; String str1 = (o1 == null) ? "null" : o1.toString(); String str2 = (o2 == null) ? "null" : o2.toString(); return str1.compareTo(str2); }
[ "public", "int", "compare", "(", "T", "o1", ",", "T", "o2", ")", "{", "if", "(", "o1", "==", "o2", ")", "return", "0", ";", "String", "str1", "=", "(", "o1", "==", "null", ")", "?", "\"null\"", ":", "o1", ".", "toString", "(", ")", ";", "Stri...
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the string representation of the first argument is less than, equal to, or greater to the string representation of the second.
[ "Compares", "its", "two", "arguments", "for", "order", ".", "Returns", "a", "negative", "integer", "zero", "or", "a", "positive", "integer", "as", "the", "string", "representation", "of", "the", "first", "argument", "is", "less", "than", "equal", "to", "or",...
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/Misc/UComp.java#L26-L31
train
m-m-m/util
lang/src/main/java/net/sf/mmm/util/lang/api/CaseSyntax.java
CaseSyntax.of
public static CaseSyntax of(Character separator, CaseConversion allCharCase) { return of(separator, allCharCase, allCharCase, allCharCase); }
java
public static CaseSyntax of(Character separator, CaseConversion allCharCase) { return of(separator, allCharCase, allCharCase, allCharCase); }
[ "public", "static", "CaseSyntax", "of", "(", "Character", "separator", ",", "CaseConversion", "allCharCase", ")", "{", "return", "of", "(", "separator", ",", "allCharCase", ",", "allCharCase", ",", "allCharCase", ")", ";", "}" ]
The constructor. @param separator - see {@link #getWordSeparator()}. @param allCharCase the {@link CaseConversion} used for {@link #getFirstCase() first}, {@link #getWordStartCase() word-start}, and all {@link #getOtherCase() other} alphabetic characters. @return the requested {@link CaseSyntax}.
[ "The", "constructor", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/lang/src/main/java/net/sf/mmm/util/lang/api/CaseSyntax.java#L382-L385
train
m-m-m/util
core/src/main/java/net/sf/mmm/util/lang/base/AbstractDatatypeDetector.java
AbstractDatatypeDetector.registerDefaultDatatypes
protected void registerDefaultDatatypes() { registerStandardDatatype(String.class); registerStandardDatatype(Boolean.class); registerStandardDatatype(Character.class); registerStandardDatatype(Currency.class); registerCustomDatatype(Datatype.class); // internal trick... registerNumberDatatypes(); registerJavaTimeDatatypes(); registerJavaUtilDateCalendarDatatypes(); }
java
protected void registerDefaultDatatypes() { registerStandardDatatype(String.class); registerStandardDatatype(Boolean.class); registerStandardDatatype(Character.class); registerStandardDatatype(Currency.class); registerCustomDatatype(Datatype.class); // internal trick... registerNumberDatatypes(); registerJavaTimeDatatypes(); registerJavaUtilDateCalendarDatatypes(); }
[ "protected", "void", "registerDefaultDatatypes", "(", ")", "{", "registerStandardDatatype", "(", "String", ".", "class", ")", ";", "registerStandardDatatype", "(", "Boolean", ".", "class", ")", ";", "registerStandardDatatype", "(", "Character", ".", "class", ")", ...
Registers the default datatypes.
[ "Registers", "the", "default", "datatypes", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/core/src/main/java/net/sf/mmm/util/lang/base/AbstractDatatypeDetector.java#L98-L108
train
m-m-m/util
core/src/main/java/net/sf/mmm/util/lang/base/AbstractDatatypeDetector.java
AbstractDatatypeDetector.setExtraDatatypes
public void setExtraDatatypes(List<String> datatypeList) { getInitializationState().requireNotInitilized(); for (String fqn : datatypeList) { registerCustomDatatype(fqn); } }
java
public void setExtraDatatypes(List<String> datatypeList) { getInitializationState().requireNotInitilized(); for (String fqn : datatypeList) { registerCustomDatatype(fqn); } }
[ "public", "void", "setExtraDatatypes", "(", "List", "<", "String", ">", "datatypeList", ")", "{", "getInitializationState", "(", ")", ".", "requireNotInitilized", "(", ")", ";", "for", "(", "String", "fqn", ":", "datatypeList", ")", "{", "registerCustomDatatype"...
Adds a list of additional datatypes to register. E.g. for easy spring configuration and custom extension. @param datatypeList is the {@link List} of {@link Class#getName() fully qualified names} of additional {@link Datatype}s to {@link #registerCustomDatatype(String) register}.
[ "Adds", "a", "list", "of", "additional", "datatypes", "to", "register", ".", "E", ".", "g", ".", "for", "easy", "spring", "configuration", "and", "custom", "extension", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/core/src/main/java/net/sf/mmm/util/lang/base/AbstractDatatypeDetector.java#L189-L195
train
ept/warc-hadoop
src/main/java/com/martinkl/warc/WARCFileWriter.java
WARCFileWriter.getGzipCodec
public static CompressionCodec getGzipCodec(Configuration conf) { try { return (CompressionCodec) ReflectionUtils.newInstance( conf.getClassByName("org.apache.hadoop.io.compress.GzipCodec").asSubclass(CompressionCodec.class), conf); } catch (ClassNotFoundException e) { logger.warn("GzipCodec could not be instantiated", e); return null; } }
java
public static CompressionCodec getGzipCodec(Configuration conf) { try { return (CompressionCodec) ReflectionUtils.newInstance( conf.getClassByName("org.apache.hadoop.io.compress.GzipCodec").asSubclass(CompressionCodec.class), conf); } catch (ClassNotFoundException e) { logger.warn("GzipCodec could not be instantiated", e); return null; } }
[ "public", "static", "CompressionCodec", "getGzipCodec", "(", "Configuration", "conf", ")", "{", "try", "{", "return", "(", "CompressionCodec", ")", "ReflectionUtils", ".", "newInstance", "(", "conf", ".", "getClassByName", "(", "\"org.apache.hadoop.io.compress.GzipCodec...
Instantiates a Hadoop codec for compressing and decompressing Gzip files. This is the most common compression applied to WARC files. @param conf The Hadoop configuration.
[ "Instantiates", "a", "Hadoop", "codec", "for", "compressing", "and", "decompressing", "Gzip", "files", ".", "This", "is", "the", "most", "common", "compression", "applied", "to", "WARC", "files", "." ]
f41cbb8002c29053eed9206e50ab9787de7da67f
https://github.com/ept/warc-hadoop/blob/f41cbb8002c29053eed9206e50ab9787de7da67f/src/main/java/com/martinkl/warc/WARCFileWriter.java#L95-L104
train
mapcode-foundation/mapcode-java
src/main/java/com/mapcode/MapcodeCodec.java
MapcodeCodec.isNearMultipleBorders
public static boolean isNearMultipleBorders(@Nonnull final Point point, @Nonnull final Territory territory) { checkDefined("point", point); if (territory != Territory.AAA) { final int territoryNumber = territory.getNumber(); if (territory.getParentTerritory() != null) { // There is a parent! check its borders as well... if (isNearMultipleBorders(point, territory.getParentTerritory())) { return true; } } int nrFound = 0; final int fromTerritoryRecord = DATA_MODEL.getDataFirstRecord(territoryNumber); final int uptoTerritoryRecord = DATA_MODEL.getDataLastRecord(territoryNumber); for (int territoryRecord = uptoTerritoryRecord; territoryRecord >= fromTerritoryRecord; territoryRecord--) { if (!Data.isRestricted(territoryRecord)) { final Boundary boundary = Boundary.createBoundaryForTerritoryRecord(territoryRecord); final int xdiv8 = Common.xDivider(boundary.getLatMicroDegMin(), boundary.getLatMicroDegMax()) / 4; if (boundary.extendBoundary(60, xdiv8).containsPoint(point)) { if (!boundary.extendBoundary(-60, -xdiv8).containsPoint(point)) { nrFound++; if (nrFound > 1) { return true; } } } } } } return false; }
java
public static boolean isNearMultipleBorders(@Nonnull final Point point, @Nonnull final Territory territory) { checkDefined("point", point); if (territory != Territory.AAA) { final int territoryNumber = territory.getNumber(); if (territory.getParentTerritory() != null) { // There is a parent! check its borders as well... if (isNearMultipleBorders(point, territory.getParentTerritory())) { return true; } } int nrFound = 0; final int fromTerritoryRecord = DATA_MODEL.getDataFirstRecord(territoryNumber); final int uptoTerritoryRecord = DATA_MODEL.getDataLastRecord(territoryNumber); for (int territoryRecord = uptoTerritoryRecord; territoryRecord >= fromTerritoryRecord; territoryRecord--) { if (!Data.isRestricted(territoryRecord)) { final Boundary boundary = Boundary.createBoundaryForTerritoryRecord(territoryRecord); final int xdiv8 = Common.xDivider(boundary.getLatMicroDegMin(), boundary.getLatMicroDegMax()) / 4; if (boundary.extendBoundary(60, xdiv8).containsPoint(point)) { if (!boundary.extendBoundary(-60, -xdiv8).containsPoint(point)) { nrFound++; if (nrFound > 1) { return true; } } } } } } return false; }
[ "public", "static", "boolean", "isNearMultipleBorders", "(", "@", "Nonnull", "final", "Point", "point", ",", "@", "Nonnull", "final", "Territory", "territory", ")", "{", "checkDefined", "(", "\"point\"", ",", "point", ")", ";", "if", "(", "territory", "!=", ...
Is coordinate near multiple territory borders? @param point Latitude/Longitude in degrees. @param territory Territory. @return true Iff the coordinate is near more than one territory border (and thus encode(decode(M)) may not produce M).
[ "Is", "coordinate", "near", "multiple", "territory", "borders?" ]
f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8
https://github.com/mapcode-foundation/mapcode-java/blob/f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8/src/main/java/com/mapcode/MapcodeCodec.java#L388-L417
train
jMotif/GI
src/main/java/net/seninp/gi/repair/RepairPriorityQueue.java
RepairPriorityQueue.enqueue
public void enqueue(RepairDigramRecord digramRecord) { // System.out.println("before == " + this.toString()); // if the same key element is in the queue - something went wrong with tracking... if (elements.containsKey(digramRecord.str)) { throw new IllegalArgumentException( "Element with payload " + digramRecord.str + " already exists in the queue..."); } else { // create a new node RepairQueueNode nn = new RepairQueueNode(digramRecord); // System.out.println(nn.payload); // place it into the queue if it's empty if (this.elements.isEmpty()) { this.head = nn; } // if new node has _higher than_ or _equal to_ the head frequency... this going to be the new head else if (nn.getFrequency() >= this.head.getFrequency()) { this.head.prev = nn; nn.next = this.head; this.head = nn; } // in all other cases find an appropriate place in the existing queue, starting from the head else { RepairQueueNode currentNode = head; while (null != currentNode.next) { // the intent is to slide down the list finding a place at new node is greater than a node // a tracking pointer points to... // ABOVE we just checked that at this loop start that the current node is greater than new // node // if (nn.getFrequency() >= currentNode.getFrequency()) { RepairQueueNode prevN = currentNode.prev; prevN.next = nn; nn.prev = prevN; currentNode.prev = nn; nn.next = currentNode; break; // the element has been placed } currentNode = currentNode.next; } // check if loop was broken by the TAIL condition, not by placement if (null == currentNode.next) { // so, currentNode points on the tail... if (nn.getFrequency() >= currentNode.getFrequency()) { // insert just before... RepairQueueNode prevN = currentNode.prev; prevN.next = nn; nn.prev = prevN; currentNode.prev = nn; nn.next = currentNode; } else { // or make a new tail nn.prev = currentNode; currentNode.next = nn; } } } // also save the element in the index store this.elements.put(nn.payload.str, nn); } // System.out.println("before == " + this.toString()); }
java
public void enqueue(RepairDigramRecord digramRecord) { // System.out.println("before == " + this.toString()); // if the same key element is in the queue - something went wrong with tracking... if (elements.containsKey(digramRecord.str)) { throw new IllegalArgumentException( "Element with payload " + digramRecord.str + " already exists in the queue..."); } else { // create a new node RepairQueueNode nn = new RepairQueueNode(digramRecord); // System.out.println(nn.payload); // place it into the queue if it's empty if (this.elements.isEmpty()) { this.head = nn; } // if new node has _higher than_ or _equal to_ the head frequency... this going to be the new head else if (nn.getFrequency() >= this.head.getFrequency()) { this.head.prev = nn; nn.next = this.head; this.head = nn; } // in all other cases find an appropriate place in the existing queue, starting from the head else { RepairQueueNode currentNode = head; while (null != currentNode.next) { // the intent is to slide down the list finding a place at new node is greater than a node // a tracking pointer points to... // ABOVE we just checked that at this loop start that the current node is greater than new // node // if (nn.getFrequency() >= currentNode.getFrequency()) { RepairQueueNode prevN = currentNode.prev; prevN.next = nn; nn.prev = prevN; currentNode.prev = nn; nn.next = currentNode; break; // the element has been placed } currentNode = currentNode.next; } // check if loop was broken by the TAIL condition, not by placement if (null == currentNode.next) { // so, currentNode points on the tail... if (nn.getFrequency() >= currentNode.getFrequency()) { // insert just before... RepairQueueNode prevN = currentNode.prev; prevN.next = nn; nn.prev = prevN; currentNode.prev = nn; nn.next = currentNode; } else { // or make a new tail nn.prev = currentNode; currentNode.next = nn; } } } // also save the element in the index store this.elements.put(nn.payload.str, nn); } // System.out.println("before == " + this.toString()); }
[ "public", "void", "enqueue", "(", "RepairDigramRecord", "digramRecord", ")", "{", "// System.out.println(\"before == \" + this.toString());", "// if the same key element is in the queue - something went wrong with tracking...", "if", "(", "elements", ".", "containsKey", "(", "digramR...
Places an element in the queue at the place based on its frequency. @param digramRecord the digram record to place into.
[ "Places", "an", "element", "in", "the", "queue", "at", "the", "place", "based", "on", "its", "frequency", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/repair/RepairPriorityQueue.java#L25-L97
train
jMotif/GI
src/main/java/net/seninp/gi/repair/RepairPriorityQueue.java
RepairPriorityQueue.get
public RepairDigramRecord get(String key) { RepairQueueNode el = this.elements.get(key); if (null != el) { return el.payload; } return null; }
java
public RepairDigramRecord get(String key) { RepairQueueNode el = this.elements.get(key); if (null != el) { return el.payload; } return null; }
[ "public", "RepairDigramRecord", "get", "(", "String", "key", ")", "{", "RepairQueueNode", "el", "=", "this", ".", "elements", ".", "get", "(", "key", ")", ";", "if", "(", "null", "!=", "el", ")", "{", "return", "el", ".", "payload", ";", "}", "return...
Gets an element in the queue given its key. @param key the key to look for. @return the element which corresponds to the key or null.
[ "Gets", "an", "element", "in", "the", "queue", "given", "its", "key", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/repair/RepairPriorityQueue.java#L155-L161
train
jMotif/GI
src/main/java/net/seninp/gi/repair/RepairPriorityQueue.java
RepairPriorityQueue.removeNodeFromList
private void removeNodeFromList(RepairQueueNode el) { // the head case // if (null == el.prev) { if (null != el.next) { this.head = el.next; this.head.prev = null; el=null; } else { // can't happen? yep. if there is only one element exists... this.head = null; } } // the tail case // else if (null == el.next) { if (null != el.prev) { el.prev.next = null; } else { // can't happen? throw new RuntimeException("Unrecognized situation here..."); } } // all others // else { el.prev.next = el.next; el.next.prev = el.prev; } }
java
private void removeNodeFromList(RepairQueueNode el) { // the head case // if (null == el.prev) { if (null != el.next) { this.head = el.next; this.head.prev = null; el=null; } else { // can't happen? yep. if there is only one element exists... this.head = null; } } // the tail case // else if (null == el.next) { if (null != el.prev) { el.prev.next = null; } else { // can't happen? throw new RuntimeException("Unrecognized situation here..."); } } // all others // else { el.prev.next = el.next; el.next.prev = el.prev; } }
[ "private", "void", "removeNodeFromList", "(", "RepairQueueNode", "el", ")", "{", "// the head case", "//", "if", "(", "null", "==", "el", ".", "prev", ")", "{", "if", "(", "null", "!=", "el", ".", "next", ")", "{", "this", ".", "head", "=", "el", "."...
Removes a node from the doubly linked list which backs the queue. @param el the element pointer.
[ "Removes", "a", "node", "from", "the", "doubly", "linked", "list", "which", "backs", "the", "queue", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/repair/RepairPriorityQueue.java#L321-L353
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/duration/DurationEvaluators.java
DurationEvaluators.evaluate
public int evaluate(Model mo, Class<? extends Action> a, Element e) throws SchedulerException { ActionDurationEvaluator<Element> ev = durations.get(a); if (ev == null) { throw new SchedulerModelingException(null, "Unable to estimate the duration of action '" + a.getSimpleName() + "' related to '" + e + "'"); } int d = ev.evaluate(mo, e); if (d <= 0) { throw new SchedulerModelingException(null, "The duration for action " + a.getSimpleName() + " over '" + e + "' has been evaluated to a negative value (" + d + "). Unsupported"); } return d; }
java
public int evaluate(Model mo, Class<? extends Action> a, Element e) throws SchedulerException { ActionDurationEvaluator<Element> ev = durations.get(a); if (ev == null) { throw new SchedulerModelingException(null, "Unable to estimate the duration of action '" + a.getSimpleName() + "' related to '" + e + "'"); } int d = ev.evaluate(mo, e); if (d <= 0) { throw new SchedulerModelingException(null, "The duration for action " + a.getSimpleName() + " over '" + e + "' has been evaluated to a negative value (" + d + "). Unsupported"); } return d; }
[ "public", "int", "evaluate", "(", "Model", "mo", ",", "Class", "<", "?", "extends", "Action", ">", "a", ",", "Element", "e", ")", "throws", "SchedulerException", "{", "ActionDurationEvaluator", "<", "Element", ">", "ev", "=", "durations", ".", "get", "(", ...
Evaluate the duration of given action on a given element. @param mo the model to consider @param a the action' class @param e the element identifier @return a positive number if the evaluation succeeded. A negative number otherwise
[ "Evaluate", "the", "duration", "of", "given", "action", "on", "a", "given", "element", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/duration/DurationEvaluators.java#L111-L121
train
m-m-m/util
cli/src/main/java/net/sf/mmm/util/cli/base/AbstractCliParser.java
AbstractCliParser.parseParameter
protected void parseParameter(String parameter, CliParserState parserState, CliParameterConsumer parameterConsumer) { if (parserState.isOptionsComplete()) { // no more options (e.g. --foo), only arguments from here List<CliArgumentContainer> argumentList = this.cliState.getArguments(parserState.requireCurrentMode(this.cliState)); int argumentIndex = parserState.getArgumentIndex(); if (argumentIndex >= argumentList.size()) { throw new NlsIllegalArgumentException(parameter); } else { parseArgument(parserState, parameter, argumentList.get(argumentIndex), parameterConsumer); } } else { CliOptionContainer optionContainer = this.cliState.getOption(parameter); if (optionContainer == null) { // no option found for argument... parseParameterUndefinedOption(parameter, parserState, parameterConsumer); } else { // mode handling... String modeId = optionContainer.getOption().mode(); CliModeObject newMode = this.cliState.getMode(modeId); if (newMode == null) { // should never happen! newMode = new CliModeContainer(modeId); } if (parserState.currentMode == null) { parserState.setCurrentMode(parameter, newMode); } else if (!modeId.equals(parserState.currentMode.getId())) { // mode already detected, but mode of current option differs... if (newMode.isDescendantOf(parserState.currentMode)) { // new mode extends current mode parserState.setCurrentMode(parameter, newMode); } else if (!newMode.isAncestorOf(parserState.currentMode)) { // current mode does NOT extend new mode and vice versa // --> incompatible modes throw new CliOptionIncompatibleModesException(parserState.modeOption, parameter); } } parseOption(parserState, parameter, optionContainer, parameterConsumer); } } }
java
protected void parseParameter(String parameter, CliParserState parserState, CliParameterConsumer parameterConsumer) { if (parserState.isOptionsComplete()) { // no more options (e.g. --foo), only arguments from here List<CliArgumentContainer> argumentList = this.cliState.getArguments(parserState.requireCurrentMode(this.cliState)); int argumentIndex = parserState.getArgumentIndex(); if (argumentIndex >= argumentList.size()) { throw new NlsIllegalArgumentException(parameter); } else { parseArgument(parserState, parameter, argumentList.get(argumentIndex), parameterConsumer); } } else { CliOptionContainer optionContainer = this.cliState.getOption(parameter); if (optionContainer == null) { // no option found for argument... parseParameterUndefinedOption(parameter, parserState, parameterConsumer); } else { // mode handling... String modeId = optionContainer.getOption().mode(); CliModeObject newMode = this.cliState.getMode(modeId); if (newMode == null) { // should never happen! newMode = new CliModeContainer(modeId); } if (parserState.currentMode == null) { parserState.setCurrentMode(parameter, newMode); } else if (!modeId.equals(parserState.currentMode.getId())) { // mode already detected, but mode of current option differs... if (newMode.isDescendantOf(parserState.currentMode)) { // new mode extends current mode parserState.setCurrentMode(parameter, newMode); } else if (!newMode.isAncestorOf(parserState.currentMode)) { // current mode does NOT extend new mode and vice versa // --> incompatible modes throw new CliOptionIncompatibleModesException(parserState.modeOption, parameter); } } parseOption(parserState, parameter, optionContainer, parameterConsumer); } } }
[ "protected", "void", "parseParameter", "(", "String", "parameter", ",", "CliParserState", "parserState", ",", "CliParameterConsumer", "parameterConsumer", ")", "{", "if", "(", "parserState", ".", "isOptionsComplete", "(", ")", ")", "{", "// no more options (e.g. --foo),...
This method parses a single command-line argument. @param parameter is the command-line argument. @param parserState is the {@link CliParserState}. @param parameterConsumer is the {@link CliParameterConsumer}.
[ "This", "method", "parses", "a", "single", "command", "-", "line", "argument", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/cli/src/main/java/net/sf/mmm/util/cli/base/AbstractCliParser.java#L270-L311
train
m-m-m/util
cli/src/main/java/net/sf/mmm/util/cli/base/AbstractCliParser.java
AbstractCliParser.printHelpOptions
private int printHelpOptions(CliOutputSettings settings, Map<CliOption, CliOptionHelpInfo> option2HelpMap, StringBuilder parameters, Collection<CliOptionContainer> modeOptions) { int maxOptionColumnWidth = 0; for (CliOptionContainer option : modeOptions) { CliOption cliOption = option.getOption(); if (parameters.length() > 0) { parameters.append(" "); } if (!cliOption.required()) { parameters.append("["); } parameters.append(cliOption.name()); if (!option.getSetter().getPropertyClass().equals(boolean.class)) { parameters.append(" "); parameters.append(cliOption.operand()); if (option.isArrayMapOrCollection()) { CliContainerStyle containerStyle = option.getContainerStyle(this.cliState.getCliStyle()); switch (containerStyle) { case COMMA_SEPARATED: parameters.append(",..."); break; case MULTIPLE_OCCURRENCE: parameters.append("*"); break; default : throw new IllegalCaseException(CliContainerStyle.class, containerStyle); } } } if (!cliOption.required()) { parameters.append("]"); } CliOptionHelpInfo helpInfo = option2HelpMap.get(cliOption); if (helpInfo == null) { helpInfo = new CliOptionHelpInfo(option, this.dependencies, settings); option2HelpMap.put(cliOption, helpInfo); } if (helpInfo.length > maxOptionColumnWidth) { maxOptionColumnWidth = helpInfo.length; } } return maxOptionColumnWidth; }
java
private int printHelpOptions(CliOutputSettings settings, Map<CliOption, CliOptionHelpInfo> option2HelpMap, StringBuilder parameters, Collection<CliOptionContainer> modeOptions) { int maxOptionColumnWidth = 0; for (CliOptionContainer option : modeOptions) { CliOption cliOption = option.getOption(); if (parameters.length() > 0) { parameters.append(" "); } if (!cliOption.required()) { parameters.append("["); } parameters.append(cliOption.name()); if (!option.getSetter().getPropertyClass().equals(boolean.class)) { parameters.append(" "); parameters.append(cliOption.operand()); if (option.isArrayMapOrCollection()) { CliContainerStyle containerStyle = option.getContainerStyle(this.cliState.getCliStyle()); switch (containerStyle) { case COMMA_SEPARATED: parameters.append(",..."); break; case MULTIPLE_OCCURRENCE: parameters.append("*"); break; default : throw new IllegalCaseException(CliContainerStyle.class, containerStyle); } } } if (!cliOption.required()) { parameters.append("]"); } CliOptionHelpInfo helpInfo = option2HelpMap.get(cliOption); if (helpInfo == null) { helpInfo = new CliOptionHelpInfo(option, this.dependencies, settings); option2HelpMap.put(cliOption, helpInfo); } if (helpInfo.length > maxOptionColumnWidth) { maxOptionColumnWidth = helpInfo.length; } } return maxOptionColumnWidth; }
[ "private", "int", "printHelpOptions", "(", "CliOutputSettings", "settings", ",", "Map", "<", "CliOption", ",", "CliOptionHelpInfo", ">", "option2HelpMap", ",", "StringBuilder", "parameters", ",", "Collection", "<", "CliOptionContainer", ">", "modeOptions", ")", "{", ...
Prints the options for the help usage output. @param settings are the {@link CliOutputSettings}. @param option2HelpMap is the {@link Map} with the {@link CliOptionHelpInfo}. @param parameters is the {@link StringBuilder} where to {@link StringBuilder#append(String) append} the options help output. @param modeOptions the {@link Collection} with the options to print for the current mode. @return the maximum width in characters of the option column in the text output.
[ "Prints", "the", "options", "for", "the", "help", "usage", "output", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/cli/src/main/java/net/sf/mmm/util/cli/base/AbstractCliParser.java#L454-L497
train
protegeproject/jpaul
src/main/java/jpaul/DataStructs/ArraySet.java
ArraySet.contains
public boolean contains(Object o) { for(T e : elemArray) { if((o == e) || ((o != null) && o.equals(e))) { return true; } } return false; }
java
public boolean contains(Object o) { for(T e : elemArray) { if((o == e) || ((o != null) && o.equals(e))) { return true; } } return false; }
[ "public", "boolean", "contains", "(", "Object", "o", ")", "{", "for", "(", "T", "e", ":", "elemArray", ")", "{", "if", "(", "(", "o", "==", "e", ")", "||", "(", "(", "o", "!=", "null", ")", "&&", "o", ".", "equals", "(", "e", ")", ")", ")",...
Re-implement the contains method from AbstractSet, for speed reasons
[ "Re", "-", "implement", "the", "contains", "method", "from", "AbstractSet", "for", "speed", "reasons" ]
db579ffb16faaa4b0c577ec82c246f7349427714
https://github.com/protegeproject/jpaul/blob/db579ffb16faaa4b0c577ec82c246f7349427714/src/main/java/jpaul/DataStructs/ArraySet.java#L126-L133
train
btrplace/scheduler
api/src/main/java/org/btrplace/plan/DependenciesExtractor.java
DependenciesExtractor.getDependencies
public Set<Action> getDependencies(Action a) { if (!demandingNodes.containsKey(a)) { return Collections.emptySet(); } Node n = demandingNodes.get(a); Set<Action> allActions = getFreeings(n); Set<Action> pre = new HashSet<>(); for (Action action : allActions) { if (!action.equals(a) && a.getStart() >= action.getEnd()) { pre.add(action); } } return pre; }
java
public Set<Action> getDependencies(Action a) { if (!demandingNodes.containsKey(a)) { return Collections.emptySet(); } Node n = demandingNodes.get(a); Set<Action> allActions = getFreeings(n); Set<Action> pre = new HashSet<>(); for (Action action : allActions) { if (!action.equals(a) && a.getStart() >= action.getEnd()) { pre.add(action); } } return pre; }
[ "public", "Set", "<", "Action", ">", "getDependencies", "(", "Action", "a", ")", "{", "if", "(", "!", "demandingNodes", ".", "containsKey", "(", "a", ")", ")", "{", "return", "Collections", ".", "emptySet", "(", ")", ";", "}", "Node", "n", "=", "dema...
Get the dependencies for an action. @param a the action to check @return its dependencies, may be empty
[ "Get", "the", "dependencies", "for", "an", "action", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/plan/DependenciesExtractor.java#L164-L177
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/util/RequestUtil.java
RequestUtil.isExplodeRequires
public static boolean isExplodeRequires(HttpServletRequest request) { if (isIncludeRequireDeps(request)) { // don't expand require deps if we're including them in the response. return false; } boolean result = false; IAggregator aggr = (IAggregator)request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME); IOptions options = aggr.getOptions(); IConfig config = aggr.getConfig(); Boolean reqattr = TypeUtil.asBoolean(request.getAttribute(IHttpTransport.EXPANDREQUIRELISTS_REQATTRNAME)); result = (options == null || !options.isDisableRequireListExpansion()) && (config == null || !isServerExpandedLayers(request)) && reqattr != null && reqattr; return result; }
java
public static boolean isExplodeRequires(HttpServletRequest request) { if (isIncludeRequireDeps(request)) { // don't expand require deps if we're including them in the response. return false; } boolean result = false; IAggregator aggr = (IAggregator)request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME); IOptions options = aggr.getOptions(); IConfig config = aggr.getConfig(); Boolean reqattr = TypeUtil.asBoolean(request.getAttribute(IHttpTransport.EXPANDREQUIRELISTS_REQATTRNAME)); result = (options == null || !options.isDisableRequireListExpansion()) && (config == null || !isServerExpandedLayers(request)) && reqattr != null && reqattr; return result; }
[ "public", "static", "boolean", "isExplodeRequires", "(", "HttpServletRequest", "request", ")", "{", "if", "(", "isIncludeRequireDeps", "(", "request", ")", ")", "{", "// don't expand require deps if we're including them in the response.\r", "return", "false", ";", "}", "b...
Static class method for determining if require list explosion should be performed. @param request The http request object @return True if require list explosion should be performed.
[ "Static", "class", "method", "for", "determining", "if", "require", "list", "explosion", "should", "be", "performed", "." ]
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/util/RequestUtil.java#L62-L76
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/util/RequestUtil.java
RequestUtil.isHasFiltering
public static boolean isHasFiltering(HttpServletRequest request) { IAggregator aggr = (IAggregator)request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME); IOptions options = aggr.getOptions(); return (options != null) ? !options.isDisableHasFiltering() : true; }
java
public static boolean isHasFiltering(HttpServletRequest request) { IAggregator aggr = (IAggregator)request.getAttribute(IAggregator.AGGREGATOR_REQATTRNAME); IOptions options = aggr.getOptions(); return (options != null) ? !options.isDisableHasFiltering() : true; }
[ "public", "static", "boolean", "isHasFiltering", "(", "HttpServletRequest", "request", ")", "{", "IAggregator", "aggr", "=", "(", "IAggregator", ")", "request", ".", "getAttribute", "(", "IAggregator", ".", "AGGREGATOR_REQATTRNAME", ")", ";", "IOptions", "options", ...
Static method for determining if has filtering should be performed. @param request The http request object @return True if has filtering should be performed
[ "Static", "method", "for", "determining", "if", "has", "filtering", "should", "be", "performed", "." ]
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/util/RequestUtil.java#L84-L88
train
mapcode-foundation/mapcode-java
src/main/java/com/mapcode/Boundary.java
Boundary.createBoundaryForTerritoryRecord
@Nonnull static Boundary createBoundaryForTerritoryRecord(final int territoryRecord) { return new Boundary( DATA_MODEL.getLatMicroDegMin(territoryRecord), DATA_MODEL.getLonMicroDegMin(territoryRecord), DATA_MODEL.getLatMicroDegMax(territoryRecord), DATA_MODEL.getLonMicroDegMax(territoryRecord) ); }
java
@Nonnull static Boundary createBoundaryForTerritoryRecord(final int territoryRecord) { return new Boundary( DATA_MODEL.getLatMicroDegMin(territoryRecord), DATA_MODEL.getLonMicroDegMin(territoryRecord), DATA_MODEL.getLatMicroDegMax(territoryRecord), DATA_MODEL.getLonMicroDegMax(territoryRecord) ); }
[ "@", "Nonnull", "static", "Boundary", "createBoundaryForTerritoryRecord", "(", "final", "int", "territoryRecord", ")", "{", "return", "new", "Boundary", "(", "DATA_MODEL", ".", "getLatMicroDegMin", "(", "territoryRecord", ")", ",", "DATA_MODEL", ".", "getLonMicroDegMi...
You have to use this factory method instead of a ctor.
[ "You", "have", "to", "use", "this", "factory", "method", "instead", "of", "a", "ctor", "." ]
f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8
https://github.com/mapcode-foundation/mapcode-java/blob/f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8/src/main/java/com/mapcode/Boundary.java#L45-L51
train
mapcode-foundation/mapcode-java
src/main/java/com/mapcode/Boundary.java
Boundary.containsPoint
boolean containsPoint(@Nonnull final Point p) { if (!p.isDefined()) { return false; } final int latMicroDeg = p.getLatMicroDeg(); if ((latMicroDegMin > latMicroDeg) || (latMicroDeg >= latMicroDegMax)) { return false; } final int lonMicroDeg = p.getLonMicroDeg(); // Longitude boundaries can extend (slightly) outside the [-180,180) range. if (lonMicroDeg < lonMicroDegMin) { return (lonMicroDegMin <= (lonMicroDeg + Point.MICRO_DEG_360)) && ((lonMicroDeg + Point.MICRO_DEG_360) < lonMicroDegMax); } else if (lonMicroDeg >= lonMicroDegMax) { return (lonMicroDegMin <= (lonMicroDeg - Point.MICRO_DEG_360)) && ((lonMicroDeg - Point.MICRO_DEG_360) < lonMicroDegMax); } else { return true; } }
java
boolean containsPoint(@Nonnull final Point p) { if (!p.isDefined()) { return false; } final int latMicroDeg = p.getLatMicroDeg(); if ((latMicroDegMin > latMicroDeg) || (latMicroDeg >= latMicroDegMax)) { return false; } final int lonMicroDeg = p.getLonMicroDeg(); // Longitude boundaries can extend (slightly) outside the [-180,180) range. if (lonMicroDeg < lonMicroDegMin) { return (lonMicroDegMin <= (lonMicroDeg + Point.MICRO_DEG_360)) && ((lonMicroDeg + Point.MICRO_DEG_360) < lonMicroDegMax); } else if (lonMicroDeg >= lonMicroDegMax) { return (lonMicroDegMin <= (lonMicroDeg - Point.MICRO_DEG_360)) && ((lonMicroDeg - Point.MICRO_DEG_360) < lonMicroDegMax); } else { return true; } }
[ "boolean", "containsPoint", "(", "@", "Nonnull", "final", "Point", "p", ")", "{", "if", "(", "!", "p", ".", "isDefined", "(", ")", ")", "{", "return", "false", ";", "}", "final", "int", "latMicroDeg", "=", "p", ".", "getLatMicroDeg", "(", ")", ";", ...
Check if a point falls within a boundary. Note that the "min" values are inclusive for a boundary and the "max" values are exclusive.\ Note: Points at the exact North pole with latitude 90 are never part of a boundary. @param p Point to check. @return True if the points falls within the boundary.
[ "Check", "if", "a", "point", "falls", "within", "a", "boundary", ".", "Note", "that", "the", "min", "values", "are", "inclusive", "for", "a", "boundary", "and", "the", "max", "values", "are", "exclusive", ".", "\\" ]
f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8
https://github.com/mapcode-foundation/mapcode-java/blob/f12d4d9fbd460472ac0fff1f702f2ac716bc0ab8/src/main/java/com/mapcode/Boundary.java#L87-L105
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/constraint/migration/Precedence.java
Precedence.newPrecedence
public static List<Precedence> newPrecedence(VM vmBefore, Collection<VM> vmsAfter) { return newPrecedence(Collections.singleton(vmBefore), vmsAfter); }
java
public static List<Precedence> newPrecedence(VM vmBefore, Collection<VM> vmsAfter) { return newPrecedence(Collections.singleton(vmBefore), vmsAfter); }
[ "public", "static", "List", "<", "Precedence", ">", "newPrecedence", "(", "VM", "vmBefore", ",", "Collection", "<", "VM", ">", "vmsAfter", ")", "{", "return", "newPrecedence", "(", "Collections", ".", "singleton", "(", "vmBefore", ")", ",", "vmsAfter", ")", ...
Instantiate discrete constraints to force a set of VMs to migrate after a single one. @param vmBefore the (single) VM to migrate before the others {@see vmsAfter} @param vmsAfter the VMs to migrate after the other one {@see vmBefore} @return the associated list of constraints
[ "Instantiate", "discrete", "constraints", "to", "force", "a", "set", "of", "VMs", "to", "migrate", "after", "a", "single", "one", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/constraint/migration/Precedence.java#L103-L105
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/constraint/migration/Precedence.java
Precedence.newPrecedence
public static List<Precedence> newPrecedence(Collection<VM> vmsBefore, VM vmAfter) { return newPrecedence(vmsBefore, Collections.singleton(vmAfter)); }
java
public static List<Precedence> newPrecedence(Collection<VM> vmsBefore, VM vmAfter) { return newPrecedence(vmsBefore, Collections.singleton(vmAfter)); }
[ "public", "static", "List", "<", "Precedence", ">", "newPrecedence", "(", "Collection", "<", "VM", ">", "vmsBefore", ",", "VM", "vmAfter", ")", "{", "return", "newPrecedence", "(", "vmsBefore", ",", "Collections", ".", "singleton", "(", "vmAfter", ")", ")", ...
Instantiate discrete constraints to force a single VM to migrate after a set of VMs. @param vmsBefore the VMs to migrate before the other one {@see vmAfter} @param vmAfter the (single) VM to migrate after the others {@see vmsBefore} @return the associated list of constraints
[ "Instantiate", "discrete", "constraints", "to", "force", "a", "single", "VM", "to", "migrate", "after", "a", "set", "of", "VMs", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/constraint/migration/Precedence.java#L114-L116
train
btrplace/scheduler
api/src/main/java/org/btrplace/model/constraint/migration/Precedence.java
Precedence.newPrecedence
public static List<Precedence> newPrecedence(Collection<VM> vmsBefore, Collection<VM> vmsAfter) { List<Precedence> l = new ArrayList<>(vmsBefore.size() * vmsAfter.size()); for (VM vmb : vmsBefore) { for (VM vma : vmsAfter) { l.add(new Precedence(vmb, vma)); } } return l; }
java
public static List<Precedence> newPrecedence(Collection<VM> vmsBefore, Collection<VM> vmsAfter) { List<Precedence> l = new ArrayList<>(vmsBefore.size() * vmsAfter.size()); for (VM vmb : vmsBefore) { for (VM vma : vmsAfter) { l.add(new Precedence(vmb, vma)); } } return l; }
[ "public", "static", "List", "<", "Precedence", ">", "newPrecedence", "(", "Collection", "<", "VM", ">", "vmsBefore", ",", "Collection", "<", "VM", ">", "vmsAfter", ")", "{", "List", "<", "Precedence", ">", "l", "=", "new", "ArrayList", "<>", "(", "vmsBef...
Instantiate discrete constraints to force a set of VMs to migrate after an other set of VMs. @param vmsBefore the VMs to migrate before the others {@see vmsAfter} @param vmsAfter the VMs to migrate after the others {@see vmsBefore} @return the associated list of constraints
[ "Instantiate", "discrete", "constraints", "to", "force", "a", "set", "of", "VMs", "to", "migrate", "after", "an", "other", "set", "of", "VMs", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/api/src/main/java/org/btrplace/model/constraint/migration/Precedence.java#L125-L133
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java
VectorPackingPropagator.isConsistent
private ESat isConsistent() { int[][] l = new int[nbDims][nbBins]; for (int i = 0; i < bins.length; i++) { if (bins[i].isInstantiated()) { for (int d = 0; d < nbDims; d++) { int v = bins[i].getValue(); l[d][v] += iSizes[d][i]; if (l[d][v] > loads[d][v].getUB()) { return ESat.FALSE; } } } } return ESat.TRUE; }
java
private ESat isConsistent() { int[][] l = new int[nbDims][nbBins]; for (int i = 0; i < bins.length; i++) { if (bins[i].isInstantiated()) { for (int d = 0; d < nbDims; d++) { int v = bins[i].getValue(); l[d][v] += iSizes[d][i]; if (l[d][v] > loads[d][v].getUB()) { return ESat.FALSE; } } } } return ESat.TRUE; }
[ "private", "ESat", "isConsistent", "(", ")", "{", "int", "[", "]", "[", "]", "l", "=", "new", "int", "[", "nbDims", "]", "[", "nbBins", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bins", ".", "length", ";", "i", "++", ")", "...
check the consistency of the constraint. @return false if the total size of the items assigned to a bin exceeds the bin load upper bound, true otherwise
[ "check", "the", "consistency", "of", "the", "constraint", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java#L160-L174
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java
VectorPackingPropagator.getPropagationConditions
@Override public int getPropagationConditions(int idx) { return idx < bins.length ? IntEventType.all() : IntEventType.BOUND.getMask() + IntEventType.INSTANTIATE.getMask(); }
java
@Override public int getPropagationConditions(int idx) { return idx < bins.length ? IntEventType.all() : IntEventType.BOUND.getMask() + IntEventType.INSTANTIATE.getMask(); }
[ "@", "Override", "public", "int", "getPropagationConditions", "(", "int", "idx", ")", "{", "return", "idx", "<", "bins", ".", "length", "?", "IntEventType", ".", "all", "(", ")", ":", "IntEventType", ".", "BOUND", ".", "getMask", "(", ")", "+", "IntEvent...
react on removal events on bins variables react on bound events on loads variables
[ "react", "on", "removal", "events", "on", "bins", "variables", "react", "on", "bound", "events", "on", "loads", "variables" ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java#L184-L187
train
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java
VectorPackingPropagator.computeSumItemSizes
private void computeSumItemSizes() { for (int d = 0; d < nbDims; d++) { long sum = 0; for (int i = 0; i < iSizes[d].length; i++) { sum += iSizes[d][i]; } this.sumISizes[d] = sum; } }
java
private void computeSumItemSizes() { for (int d = 0; d < nbDims; d++) { long sum = 0; for (int i = 0; i < iSizes[d].length; i++) { sum += iSizes[d][i]; } this.sumISizes[d] = sum; } }
[ "private", "void", "computeSumItemSizes", "(", ")", "{", "for", "(", "int", "d", "=", "0", ";", "d", "<", "nbDims", ";", "d", "++", ")", "{", "long", "sum", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "iSizes", "[", "d", ...
Compute the sum of the item sizes for each dimension.
[ "Compute", "the", "sum", "of", "the", "item", "sizes", "for", "each", "dimension", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/pack/VectorPackingPropagator.java#L459-L468
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/impl/module/ModuleImpl.java
ModuleImpl.clearCached
@Override public void clearCached(ICacheManager mgr) { Map<String, CacheEntry> moduleBuilds; synchronized (this) { moduleBuilds = _moduleBuilds; _moduleBuilds = null; } if (moduleBuilds != null) { for (Map.Entry<String, CacheEntry> entry : moduleBuilds.entrySet()) { entry.getValue().delete(mgr); } moduleBuilds.clear(); } }
java
@Override public void clearCached(ICacheManager mgr) { Map<String, CacheEntry> moduleBuilds; synchronized (this) { moduleBuilds = _moduleBuilds; _moduleBuilds = null; } if (moduleBuilds != null) { for (Map.Entry<String, CacheEntry> entry : moduleBuilds.entrySet()) { entry.getValue().delete(mgr); } moduleBuilds.clear(); } }
[ "@", "Override", "public", "void", "clearCached", "(", "ICacheManager", "mgr", ")", "{", "Map", "<", "String", ",", "CacheEntry", ">", "moduleBuilds", ";", "synchronized", "(", "this", ")", "{", "moduleBuilds", "=", "_moduleBuilds", ";", "_moduleBuilds", "=", ...
Asynchronously delete the set of cached files for this module.
[ "Asynchronously", "delete", "the", "set", "of", "cached", "files", "for", "this", "module", "." ]
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/impl/module/ModuleImpl.java#L612-L625
train
btrplace/scheduler
split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java
SplittableElementSet.newVMIndex
public static SplittableElementSet<VM> newVMIndex(Collection<VM> c, TIntIntHashMap idx) { return new SplittableElementSet<>(c, idx); }
java
public static SplittableElementSet<VM> newVMIndex(Collection<VM> c, TIntIntHashMap idx) { return new SplittableElementSet<>(c, idx); }
[ "public", "static", "SplittableElementSet", "<", "VM", ">", "newVMIndex", "(", "Collection", "<", "VM", ">", "c", ",", "TIntIntHashMap", "idx", ")", "{", "return", "new", "SplittableElementSet", "<>", "(", "c", ",", "idx", ")", ";", "}" ]
Make a new splittable set from a collection of VM. We consider the collection does not have duplicated elements. @param c the collection to wrap @param idx the partition for each VM @return the resulting set
[ "Make", "a", "new", "splittable", "set", "from", "a", "collection", "of", "VM", ".", "We", "consider", "the", "collection", "does", "not", "have", "duplicated", "elements", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java#L71-L73
train
btrplace/scheduler
split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java
SplittableElementSet.newNodeIndex
public static SplittableElementSet<Node> newNodeIndex(Collection<Node> c, TIntIntHashMap idx) { return new SplittableElementSet<>(c, idx); }
java
public static SplittableElementSet<Node> newNodeIndex(Collection<Node> c, TIntIntHashMap idx) { return new SplittableElementSet<>(c, idx); }
[ "public", "static", "SplittableElementSet", "<", "Node", ">", "newNodeIndex", "(", "Collection", "<", "Node", ">", "c", ",", "TIntIntHashMap", "idx", ")", "{", "return", "new", "SplittableElementSet", "<>", "(", "c", ",", "idx", ")", ";", "}" ]
Make a new splittable set from a collection of nodes. We consider the collection does not have duplicated elements. @param c the collection to wrap @param idx the partition for each node @return the resulting set
[ "Make", "a", "new", "splittable", "set", "from", "a", "collection", "of", "nodes", ".", "We", "consider", "the", "collection", "does", "not", "have", "duplicated", "elements", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java#L83-L85
train
btrplace/scheduler
split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java
SplittableElementSet.forEachPartition
public boolean forEachPartition(IterateProcedure<E> p) { int curIdx = index.get(values.get(0).id()); int from; int to; for (from = 0, to = 0; to < values.size(); to++) { int cIdx = index.get(values.get(to).id()); if (curIdx != cIdx) { if (!p.extract(this, curIdx, from, to)) { return false; } from = to; curIdx = cIdx; } } return p.extract(this, curIdx, from, to); }
java
public boolean forEachPartition(IterateProcedure<E> p) { int curIdx = index.get(values.get(0).id()); int from; int to; for (from = 0, to = 0; to < values.size(); to++) { int cIdx = index.get(values.get(to).id()); if (curIdx != cIdx) { if (!p.extract(this, curIdx, from, to)) { return false; } from = to; curIdx = cIdx; } } return p.extract(this, curIdx, from, to); }
[ "public", "boolean", "forEachPartition", "(", "IterateProcedure", "<", "E", ">", "p", ")", "{", "int", "curIdx", "=", "index", ".", "get", "(", "values", ".", "get", "(", "0", ")", ".", "id", "(", ")", ")", ";", "int", "from", ";", "int", "to", "...
Execute a procedure on each partition. The partition is indicated by its bounds on the backend array. @param p the procedure to execute
[ "Execute", "a", "procedure", "on", "each", "partition", ".", "The", "partition", "is", "indicated", "by", "its", "bounds", "on", "the", "backend", "array", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java#L108-L123
train
btrplace/scheduler
split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java
SplittableElementSet.getSubSet
public Set<E> getSubSet(int k) { int from = -1; //TODO: very bad. Bounds should be memorized for (int x = 0; x < values.size(); x++) { int cIdx = index.get(values.get(x).id()); if (cIdx == k && from == -1) { from = x; } if (from >= 0 && cIdx > k) { return new ElementSubSet<>(this, k, from, x); } } if (from >= 0) { return new ElementSubSet<>(this, k, from, values.size()); } return Collections.emptySet(); }
java
public Set<E> getSubSet(int k) { int from = -1; //TODO: very bad. Bounds should be memorized for (int x = 0; x < values.size(); x++) { int cIdx = index.get(values.get(x).id()); if (cIdx == k && from == -1) { from = x; } if (from >= 0 && cIdx > k) { return new ElementSubSet<>(this, k, from, x); } } if (from >= 0) { return new ElementSubSet<>(this, k, from, values.size()); } return Collections.emptySet(); }
[ "public", "Set", "<", "E", ">", "getSubSet", "(", "int", "k", ")", "{", "int", "from", "=", "-", "1", ";", "//TODO: very bad. Bounds should be memorized", "for", "(", "int", "x", "=", "0", ";", "x", "<", "values", ".", "size", "(", ")", ";", "x", "...
Get a subset for the given partition. @param k the partition key @return the resulting subset. Empty if no elements belong to the given partition.
[ "Get", "a", "subset", "for", "the", "given", "partition", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java#L131-L147
train
btrplace/scheduler
split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java
SplittableElementSet.getPartitions
public List<ElementSubSet<E>> getPartitions() { final List<ElementSubSet<E>> partitions = new ArrayList<>(); forEachPartition((idx, key, from, to) -> { partitions.add(new ElementSubSet<>(SplittableElementSet.this, key, from, to)); return true; }); return partitions; }
java
public List<ElementSubSet<E>> getPartitions() { final List<ElementSubSet<E>> partitions = new ArrayList<>(); forEachPartition((idx, key, from, to) -> { partitions.add(new ElementSubSet<>(SplittableElementSet.this, key, from, to)); return true; }); return partitions; }
[ "public", "List", "<", "ElementSubSet", "<", "E", ">", ">", "getPartitions", "(", ")", "{", "final", "List", "<", "ElementSubSet", "<", "E", ">", ">", "partitions", "=", "new", "ArrayList", "<>", "(", ")", ";", "forEachPartition", "(", "(", "idx", ",",...
Get all the partitions as subsets. @return a collection of {@link ElementSubSet}.
[ "Get", "all", "the", "partitions", "as", "subsets", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SplittableElementSet.java#L177-L184
train
OpenNTF/JavascriptAggregator
jaggr-core/src/main/java/com/ibm/jaggr/core/cachekeygenerator/AbstractCollectionCacheKeyGenerator.java
AbstractCollectionCacheKeyGenerator.combine
public ICacheKeyGenerator combine(ICacheKeyGenerator otherKeyGen) { if (this.equals(otherKeyGen)) { return this; } @SuppressWarnings("unchecked") AbstractCollectionCacheKeyGenerator<T> other = (AbstractCollectionCacheKeyGenerator<T>)otherKeyGen; if (isProvisional() && other.isProvisional()) { // should never happen throw new IllegalStateException(); } // If either generator is provisional, return a provisional result if (isProvisional()) { return other; } else if (other.isProvisional()) { return this; } if (getCollection() == null) { return this; } if (other.getCollection() == null) { return other; } // See if one of the keygens encompasses the other. This is the most likely // case and is more performant than always creating a new keygen. int size = getCollection().size(), otherSize = other.getCollection().size(); if (size > otherSize && getCollection().containsAll(other.getCollection())) { return this; } if (otherSize > size && other.getCollection().containsAll(getCollection())) { return other; } // Neither keygen encompasses the other, so create a new one that is a combination // of the both of them. Set<T> combined = new HashSet<T>(); combined.addAll(getCollection()); combined.addAll(other.getCollection()); return newKeyGen(combined, false); }
java
public ICacheKeyGenerator combine(ICacheKeyGenerator otherKeyGen) { if (this.equals(otherKeyGen)) { return this; } @SuppressWarnings("unchecked") AbstractCollectionCacheKeyGenerator<T> other = (AbstractCollectionCacheKeyGenerator<T>)otherKeyGen; if (isProvisional() && other.isProvisional()) { // should never happen throw new IllegalStateException(); } // If either generator is provisional, return a provisional result if (isProvisional()) { return other; } else if (other.isProvisional()) { return this; } if (getCollection() == null) { return this; } if (other.getCollection() == null) { return other; } // See if one of the keygens encompasses the other. This is the most likely // case and is more performant than always creating a new keygen. int size = getCollection().size(), otherSize = other.getCollection().size(); if (size > otherSize && getCollection().containsAll(other.getCollection())) { return this; } if (otherSize > size && other.getCollection().containsAll(getCollection())) { return other; } // Neither keygen encompasses the other, so create a new one that is a combination // of the both of them. Set<T> combined = new HashSet<T>(); combined.addAll(getCollection()); combined.addAll(other.getCollection()); return newKeyGen(combined, false); }
[ "public", "ICacheKeyGenerator", "combine", "(", "ICacheKeyGenerator", "otherKeyGen", ")", "{", "if", "(", "this", ".", "equals", "(", "otherKeyGen", ")", ")", "{", "return", "this", ";", "}", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "AbstractCollectio...
Returns a cache key generator that is the combination of this cache key generator and the specified cache key generator (i.e. the cache keys generated by the returned object vary according to the conditions honored by this generator and the specified generator. @param otherKeyGen the key generator to combine with this key generator @return the combined cache key generator. Can be this object or {@code otherKeyGen} if either one already encompasses the other.
[ "Returns", "a", "cache", "key", "generator", "that", "is", "the", "combination", "of", "this", "cache", "key", "generator", "and", "the", "specified", "cache", "key", "generator", "(", "i", ".", "e", ".", "the", "cache", "keys", "generated", "by", "the", ...
9f47a96d778251638b1df9a368462176216d5b29
https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/cachekeygenerator/AbstractCollectionCacheKeyGenerator.java#L56-L93
train
berkesa/datatree
src/main/java/io/datatree/dom/TreeReaderRegistry.java
TreeReaderRegistry.setReader
public static final void setReader(String format, TreeReader reader) { String key = format.toLowerCase(); readers.put(key, reader); if (JSON.equals(key)) { cachedJsonReader = reader; } }
java
public static final void setReader(String format, TreeReader reader) { String key = format.toLowerCase(); readers.put(key, reader); if (JSON.equals(key)) { cachedJsonReader = reader; } }
[ "public", "static", "final", "void", "setReader", "(", "String", "format", ",", "TreeReader", "reader", ")", "{", "String", "key", "=", "format", ".", "toLowerCase", "(", ")", ";", "readers", ".", "put", "(", "key", ",", "reader", ")", ";", "if", "(", ...
Binds the given TreeReader instance to the specified data format. @param format name of the format (eg. "json", "xml", "csv", etc.) @param reader TreeReader instance for parsing the specified format
[ "Binds", "the", "given", "TreeReader", "instance", "to", "the", "specified", "data", "format", "." ]
79aea9b45c7b46ab28af0a09310bc01c421c6b3a
https://github.com/berkesa/datatree/blob/79aea9b45c7b46ab28af0a09310bc01c421c6b3a/src/main/java/io/datatree/dom/TreeReaderRegistry.java#L62-L68
train
m-m-m/util
xml/src/main/java/net/sf/mmm/util/xml/impl/stax/XIncludeStreamReader.java
XIncludeStreamReader.resolveInclude
protected int resolveInclude() throws XMLStreamException { // we are no more in fallback mode this.fallback = false; this.depth++; int eventType = -1; // read attributes... String href = getAttributeValue(null, "href"); LOGGER.trace("Resolving xi:include to href {}", href); String xpointer = getAttributeValue(null, "xpointer"); // get the included resource... DataResource includeResource = this.resource.navigate(href); // and try to include it... boolean success = false; if (includeResource.isAvailable()) { // determine inclusion format type... String parse = getAttributeValue(null, "parse"); if ((parse == null) || ("xml".equals(parse))) { this.includeReader = new XIncludeStreamReader(this.factory, includeResource, this); if (xpointer != null) { // shorthand form: id // scheme-based form: e.g. element(/1/*) this.includeReader = new XPointerStreamReader(this.includeReader, xpointer); } eventType = this.includeReader.nextTag(); setParent(this.includeReader); // we ascend the XML until the initial include is closed. closeInitialInclude(); success = true; } else if ("text".equals(parse)) { String encoding = getAttributeValue(null, "encoding"); Charset charset; if (encoding == null) { charset = Charset.defaultCharset(); } else { charset = Charset.forName(encoding); } InputStream textInputStream = includeResource.openStream(); Reader reader = new InputStreamReader(textInputStream, charset); this.includeText = read(reader); // we ascend the XML until the initial include is closed. closeInitialInclude(); return XMLStreamConstants.CHARACTERS; } else { throw new XMLStreamException("Unsupported XInclude parse type:" + parse); } } if (!success) { // search for fallback do { eventType = super.next(); } while ((eventType != XMLStreamConstants.START_ELEMENT) && (eventType != XMLStreamConstants.END_ELEMENT)); if (eventType == XMLStreamConstants.START_ELEMENT) { if ((XmlUtil.NAMESPACE_URI_XINCLUDE.equals(getNamespaceURI())) && ("fallback".equals(getLocalName()))) { // found fallback this.fallback = true; return next(); } } // no fallback available, ignore include... closeInitialInclude(); return next(); } return eventType; }
java
protected int resolveInclude() throws XMLStreamException { // we are no more in fallback mode this.fallback = false; this.depth++; int eventType = -1; // read attributes... String href = getAttributeValue(null, "href"); LOGGER.trace("Resolving xi:include to href {}", href); String xpointer = getAttributeValue(null, "xpointer"); // get the included resource... DataResource includeResource = this.resource.navigate(href); // and try to include it... boolean success = false; if (includeResource.isAvailable()) { // determine inclusion format type... String parse = getAttributeValue(null, "parse"); if ((parse == null) || ("xml".equals(parse))) { this.includeReader = new XIncludeStreamReader(this.factory, includeResource, this); if (xpointer != null) { // shorthand form: id // scheme-based form: e.g. element(/1/*) this.includeReader = new XPointerStreamReader(this.includeReader, xpointer); } eventType = this.includeReader.nextTag(); setParent(this.includeReader); // we ascend the XML until the initial include is closed. closeInitialInclude(); success = true; } else if ("text".equals(parse)) { String encoding = getAttributeValue(null, "encoding"); Charset charset; if (encoding == null) { charset = Charset.defaultCharset(); } else { charset = Charset.forName(encoding); } InputStream textInputStream = includeResource.openStream(); Reader reader = new InputStreamReader(textInputStream, charset); this.includeText = read(reader); // we ascend the XML until the initial include is closed. closeInitialInclude(); return XMLStreamConstants.CHARACTERS; } else { throw new XMLStreamException("Unsupported XInclude parse type:" + parse); } } if (!success) { // search for fallback do { eventType = super.next(); } while ((eventType != XMLStreamConstants.START_ELEMENT) && (eventType != XMLStreamConstants.END_ELEMENT)); if (eventType == XMLStreamConstants.START_ELEMENT) { if ((XmlUtil.NAMESPACE_URI_XINCLUDE.equals(getNamespaceURI())) && ("fallback".equals(getLocalName()))) { // found fallback this.fallback = true; return next(); } } // no fallback available, ignore include... closeInitialInclude(); return next(); } return eventType; }
[ "protected", "int", "resolveInclude", "(", ")", "throws", "XMLStreamException", "{", "// we are no more in fallback mode", "this", ".", "fallback", "=", "false", ";", "this", ".", "depth", "++", ";", "int", "eventType", "=", "-", "1", ";", "// read attributes...",...
This method is called when an include tag of the XInclude namespace was started. It resolves the include and finds a fallback on failure. @return the next event type. @throws XMLStreamException if the XML stream processing caused an error.
[ "This", "method", "is", "called", "when", "an", "include", "tag", "of", "the", "XInclude", "namespace", "was", "started", ".", "It", "resolves", "the", "include", "and", "finds", "a", "fallback", "on", "failure", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/xml/src/main/java/net/sf/mmm/util/xml/impl/stax/XIncludeStreamReader.java#L185-L249
train
m-m-m/util
xml/src/main/java/net/sf/mmm/util/xml/impl/stax/XIncludeStreamReader.java
XIncludeStreamReader.closeInitialInclude
protected void closeInitialInclude() throws XMLStreamException { LOGGER.trace("Closing xi:include"); int eventType = -1; // we ascend the XML until the initial include is closed. while (this.depth > 0) { eventType = this.mainReader.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { LOGGER.trace("Closing loop: Start {}", this.mainReader.getLocalName()); this.depth++; } else if (eventType == XMLStreamConstants.END_ELEMENT) { LOGGER.trace("Closing loop: End {}", this.mainReader.getLocalName()); this.depth--; } } LOGGER.trace("Closing xi:include complete"); }
java
protected void closeInitialInclude() throws XMLStreamException { LOGGER.trace("Closing xi:include"); int eventType = -1; // we ascend the XML until the initial include is closed. while (this.depth > 0) { eventType = this.mainReader.next(); if (eventType == XMLStreamConstants.START_ELEMENT) { LOGGER.trace("Closing loop: Start {}", this.mainReader.getLocalName()); this.depth++; } else if (eventType == XMLStreamConstants.END_ELEMENT) { LOGGER.trace("Closing loop: End {}", this.mainReader.getLocalName()); this.depth--; } } LOGGER.trace("Closing xi:include complete"); }
[ "protected", "void", "closeInitialInclude", "(", ")", "throws", "XMLStreamException", "{", "LOGGER", ".", "trace", "(", "\"Closing xi:include\"", ")", ";", "int", "eventType", "=", "-", "1", ";", "// we ascend the XML until the initial include is closed.", "while", "(",...
This method ascends the XML until the initial include is closed. @throws XMLStreamException if the XML stream processing caused an error.
[ "This", "method", "ascends", "the", "XML", "until", "the", "initial", "include", "is", "closed", "." ]
f0e4e084448f8dfc83ca682a9e1618034a094ce6
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/xml/src/main/java/net/sf/mmm/util/xml/impl/stax/XIncludeStreamReader.java#L274-L290
train
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/Message.java
Message.read
public boolean read() { if (state == State.READING_FRAME_SIZE) { // try to read the frame size completely if (!internalRead(frameSizeBuffer)) return false; // if the frame size has been read completely, then prepare to read the // actual frame. if (frameSizeBuffer.remaining() == 0) { // pull out the frame size as an integer. int frameSize = frameSizeBuffer.getInt(0); if (frameSize <= 0) { logger.error("Read an invalid frame size of " + frameSize + ". Are you using TFramedTransport on the client side?"); return false; } if (frameSize > thriftFactories.maxFrameSizeInBytes) { logger.error("Invalid frame size got (" + frameSize + "), maximum expected " + thriftFactories.maxFrameSizeInBytes); return false; } // reallocate to match frame size (if needed) reallocateDataBuffer(frameSize); frameSizeBuffer.clear(); // prepare it to the next round of reading (if any) state = State.READING_FRAME; } else { // this skips the check of READING_FRAME state below, since we can't // possibly go on to that state if there's data left to be read at // this one. state = State.READY_TO_READ_FRAME_SIZE; return true; } } // it is possible to fall through from the READING_FRAME_SIZE section // to READING_FRAME if there's already some frame data available once // READING_FRAME_SIZE is complete. if (state == State.READING_FRAME) { if (!internalRead(dataBuffer)) return false; state = (dataBuffer.remaining() == 0) ? State.READ_FRAME_COMPLETE : State.READY_TO_READ_FRAME; // Do not read until we finish processing request. if (state == State.READ_FRAME_COMPLETE) { switchMode(State.READ_FRAME_COMPLETE); } return true; } // if we fall through to this point, then the state must be invalid. logger.error("Read was called but state is invalid (" + state + ")"); return false; }
java
public boolean read() { if (state == State.READING_FRAME_SIZE) { // try to read the frame size completely if (!internalRead(frameSizeBuffer)) return false; // if the frame size has been read completely, then prepare to read the // actual frame. if (frameSizeBuffer.remaining() == 0) { // pull out the frame size as an integer. int frameSize = frameSizeBuffer.getInt(0); if (frameSize <= 0) { logger.error("Read an invalid frame size of " + frameSize + ". Are you using TFramedTransport on the client side?"); return false; } if (frameSize > thriftFactories.maxFrameSizeInBytes) { logger.error("Invalid frame size got (" + frameSize + "), maximum expected " + thriftFactories.maxFrameSizeInBytes); return false; } // reallocate to match frame size (if needed) reallocateDataBuffer(frameSize); frameSizeBuffer.clear(); // prepare it to the next round of reading (if any) state = State.READING_FRAME; } else { // this skips the check of READING_FRAME state below, since we can't // possibly go on to that state if there's data left to be read at // this one. state = State.READY_TO_READ_FRAME_SIZE; return true; } } // it is possible to fall through from the READING_FRAME_SIZE section // to READING_FRAME if there's already some frame data available once // READING_FRAME_SIZE is complete. if (state == State.READING_FRAME) { if (!internalRead(dataBuffer)) return false; state = (dataBuffer.remaining() == 0) ? State.READ_FRAME_COMPLETE : State.READY_TO_READ_FRAME; // Do not read until we finish processing request. if (state == State.READ_FRAME_COMPLETE) { switchMode(State.READ_FRAME_COMPLETE); } return true; } // if we fall through to this point, then the state must be invalid. logger.error("Read was called but state is invalid (" + state + ")"); return false; }
[ "public", "boolean", "read", "(", ")", "{", "if", "(", "state", "==", "State", ".", "READING_FRAME_SIZE", ")", "{", "// try to read the frame size completely", "if", "(", "!", "internalRead", "(", "frameSizeBuffer", ")", ")", "return", "false", ";", "// if the f...
Give this Message a chance to read. The selector loop should have received a read event for this Message. @return true if the connection should live on, false if it should be closed
[ "Give", "this", "Message", "a", "chance", "to", "read", ".", "The", "selector", "loop", "should", "have", "received", "a", "read", "event", "for", "this", "Message", "." ]
5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/Message.java#L178-L248
train
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/Message.java
Message.write
public boolean write() { assert state == State.WRITING; boolean writeFailed = false; try { if (response.streamTo(transport) < 0) { writeFailed = true; return false; } else if (!response.isFullyStreamed()) { // if socket couldn't accommodate whole write buffer, // continue writing when we get next write signal. switchToWrite(); return true; } } catch (IOException e) { logger.error("Got an IOException during write!", e); writeFailed = true; return false; } finally { if (writeFailed || response.isFullyStreamed()) response.close(); } // we're done writing. Now we need to switch back to reading. switchToRead(); return true; }
java
public boolean write() { assert state == State.WRITING; boolean writeFailed = false; try { if (response.streamTo(transport) < 0) { writeFailed = true; return false; } else if (!response.isFullyStreamed()) { // if socket couldn't accommodate whole write buffer, // continue writing when we get next write signal. switchToWrite(); return true; } } catch (IOException e) { logger.error("Got an IOException during write!", e); writeFailed = true; return false; } finally { if (writeFailed || response.isFullyStreamed()) response.close(); } // we're done writing. Now we need to switch back to reading. switchToRead(); return true; }
[ "public", "boolean", "write", "(", ")", "{", "assert", "state", "==", "State", ".", "WRITING", ";", "boolean", "writeFailed", "=", "false", ";", "try", "{", "if", "(", "response", ".", "streamTo", "(", "transport", ")", "<", "0", ")", "{", "writeFailed...
Give this Message a chance to write its output to the final client.
[ "Give", "this", "Message", "a", "chance", "to", "write", "its", "output", "to", "the", "final", "client", "." ]
5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/Message.java#L258-L298
train
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/Message.java
Message.changeSelectInterests
public void changeSelectInterests() { switch (state) { case READY_TO_WRITE: // set the OP_WRITE interest state = State.WRITING; break; case READY_TO_READ_FRAME_SIZE: state = State.READING_FRAME_SIZE; break; case READY_TO_READ_FRAME: state = State.READING_FRAME; break; case AWAITING_CLOSE: close(); selectionKey.cancel(); break; default: logger.error("changeSelectInterest was called, but state is invalid (" + state + ")"); } }
java
public void changeSelectInterests() { switch (state) { case READY_TO_WRITE: // set the OP_WRITE interest state = State.WRITING; break; case READY_TO_READ_FRAME_SIZE: state = State.READING_FRAME_SIZE; break; case READY_TO_READ_FRAME: state = State.READING_FRAME; break; case AWAITING_CLOSE: close(); selectionKey.cancel(); break; default: logger.error("changeSelectInterest was called, but state is invalid (" + state + ")"); } }
[ "public", "void", "changeSelectInterests", "(", ")", "{", "switch", "(", "state", ")", "{", "case", "READY_TO_WRITE", ":", "// set the OP_WRITE interest", "state", "=", "State", ".", "WRITING", ";", "break", ";", "case", "READY_TO_READ_FRAME_SIZE", ":", "state", ...
Give this Message a chance to change its interests.
[ "Give", "this", "Message", "a", "chance", "to", "change", "its", "interests", "." ]
5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/Message.java#L303-L327
train
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/Message.java
Message.invoke
public void invoke() { assert state == State.READ_FRAME_COMPLETE : "Invoke called in invalid state: " + state; TTransport inTrans = getInputTransport(); TProtocol inProt = thriftFactories.inputProtocolFactory.getProtocol(inTrans); TProtocol outProt = thriftFactories.outputProtocolFactory.getProtocol(getOutputTransport()); try { thriftFactories.processorFactory.getProcessor(inTrans).process(inProt, outProt); responseReady(); return; } catch (TException te) { logger.warn("Exception while invoking!", te); } catch (Throwable t) { logger.error("Unexpected throwable while invoking!", t); } // This will only be reached when there is a throwable. state = State.AWAITING_CLOSE; changeSelectInterests(); }
java
public void invoke() { assert state == State.READ_FRAME_COMPLETE : "Invoke called in invalid state: " + state; TTransport inTrans = getInputTransport(); TProtocol inProt = thriftFactories.inputProtocolFactory.getProtocol(inTrans); TProtocol outProt = thriftFactories.outputProtocolFactory.getProtocol(getOutputTransport()); try { thriftFactories.processorFactory.getProcessor(inTrans).process(inProt, outProt); responseReady(); return; } catch (TException te) { logger.warn("Exception while invoking!", te); } catch (Throwable t) { logger.error("Unexpected throwable while invoking!", t); } // This will only be reached when there is a throwable. state = State.AWAITING_CLOSE; changeSelectInterests(); }
[ "public", "void", "invoke", "(", ")", "{", "assert", "state", "==", "State", ".", "READ_FRAME_COMPLETE", ":", "\"Invoke called in invalid state: \"", "+", "state", ";", "TTransport", "inTrans", "=", "getInputTransport", "(", ")", ";", "TProtocol", "inProt", "=", ...
Actually invoke the method signified by this Message.
[ "Actually", "invoke", "the", "method", "signified", "by", "this", "Message", "." ]
5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/Message.java#L348-L374
train
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/Message.java
Message.internalRead
private boolean internalRead(Buffer buffer) { try { return !(buffer.readFrom(transport) < 0); } catch (IOException e) { logger.warn("Got an IOException in internalRead!", e); return false; } }
java
private boolean internalRead(Buffer buffer) { try { return !(buffer.readFrom(transport) < 0); } catch (IOException e) { logger.warn("Got an IOException in internalRead!", e); return false; } }
[ "private", "boolean", "internalRead", "(", "Buffer", "buffer", ")", "{", "try", "{", "return", "!", "(", "buffer", ".", "readFrom", "(", "transport", ")", "<", "0", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "logger", ".", "warn", "("...
Perform a read into dataBuffer. @return true if the read succeeded, false if there was an error or the connection closed.
[ "Perform", "a", "read", "into", "dataBuffer", "." ]
5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/Message.java#L400-L411
train
xedin/disruptor_thrift_server
src/main/java/com/thinkaurelius/thrift/Message.java
Message.close
public void close() { freeDataBuffer(); frameSizeBuffer.free(); transport.close(); if (response != null) response.close(); }
java
public void close() { freeDataBuffer(); frameSizeBuffer.free(); transport.close(); if (response != null) response.close(); }
[ "public", "void", "close", "(", ")", "{", "freeDataBuffer", "(", ")", ";", "frameSizeBuffer", ".", "free", "(", ")", ";", "transport", ".", "close", "(", ")", ";", "if", "(", "response", "!=", "null", ")", "response", ".", "close", "(", ")", ";", "...
Shut the connection down.
[ "Shut", "the", "connection", "down", "." ]
5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c
https://github.com/xedin/disruptor_thrift_server/blob/5bf0c3d6968e1ea79f5ea939dde7b8ced3d91a2c/src/main/java/com/thinkaurelius/thrift/Message.java#L475-L483
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.classifyMotifs
public ArrayList<SameLengthMotifs> classifyMotifs(double lengthThreshold, GrammarRules grammarRules) { // reset vars ArrayList<SameLengthMotifs> allClassifiedMotifs = new ArrayList<SameLengthMotifs>(); // down to business ArrayList<SAXMotif> allMotifs = getAllMotifs(grammarRules); // is this one better? int currentIndex = 0; for (SAXMotif tmpMotif : allMotifs) { currentIndex++; if (tmpMotif.isClassified()) { // this breaks the loop flow, so it goes to //for (SAXMotif // tempMotif : allMotifs) { continue; } SameLengthMotifs tmpSameLengthMotifs = new SameLengthMotifs(); int tmpMotifLen = tmpMotif.getPos().getEnd() - tmpMotif.getPos().getStart() + 1; int minLen = tmpMotifLen; int maxLen = tmpMotifLen; // TODO: assuming that this motif has not been processed, right? ArrayList<SAXMotif> newMotifClass = new ArrayList<SAXMotif>(); newMotifClass.add(tmpMotif); tmpMotif.setClassified(true); // TODO: this motif assumed to be the first one of it's class, // traverse the rest down for (int i = currentIndex; i < allMotifs.size(); i++) { SAXMotif anotherMotif = allMotifs.get(i); // if the two motifs are similar or not. int anotherMotifLen = anotherMotif.getPos().getEnd() - anotherMotif.getPos().getStart() + 1; // if they have the similar length. if (Math.abs(anotherMotifLen - tmpMotifLen) < (tmpMotifLen * lengthThreshold)) { newMotifClass.add(anotherMotif); anotherMotif.setClassified(true); if (anotherMotifLen > maxLen) { maxLen = anotherMotifLen; } else if (anotherMotifLen < minLen) { minLen = anotherMotifLen; } } } tmpSameLengthMotifs.setSameLenMotifs(newMotifClass); tmpSameLengthMotifs.setMinMotifLen(minLen); tmpSameLengthMotifs.setMaxMotifLen(maxLen); allClassifiedMotifs.add(tmpSameLengthMotifs); } return allClassifiedMotifs; // System.out.println(); }
java
public ArrayList<SameLengthMotifs> classifyMotifs(double lengthThreshold, GrammarRules grammarRules) { // reset vars ArrayList<SameLengthMotifs> allClassifiedMotifs = new ArrayList<SameLengthMotifs>(); // down to business ArrayList<SAXMotif> allMotifs = getAllMotifs(grammarRules); // is this one better? int currentIndex = 0; for (SAXMotif tmpMotif : allMotifs) { currentIndex++; if (tmpMotif.isClassified()) { // this breaks the loop flow, so it goes to //for (SAXMotif // tempMotif : allMotifs) { continue; } SameLengthMotifs tmpSameLengthMotifs = new SameLengthMotifs(); int tmpMotifLen = tmpMotif.getPos().getEnd() - tmpMotif.getPos().getStart() + 1; int minLen = tmpMotifLen; int maxLen = tmpMotifLen; // TODO: assuming that this motif has not been processed, right? ArrayList<SAXMotif> newMotifClass = new ArrayList<SAXMotif>(); newMotifClass.add(tmpMotif); tmpMotif.setClassified(true); // TODO: this motif assumed to be the first one of it's class, // traverse the rest down for (int i = currentIndex; i < allMotifs.size(); i++) { SAXMotif anotherMotif = allMotifs.get(i); // if the two motifs are similar or not. int anotherMotifLen = anotherMotif.getPos().getEnd() - anotherMotif.getPos().getStart() + 1; // if they have the similar length. if (Math.abs(anotherMotifLen - tmpMotifLen) < (tmpMotifLen * lengthThreshold)) { newMotifClass.add(anotherMotif); anotherMotif.setClassified(true); if (anotherMotifLen > maxLen) { maxLen = anotherMotifLen; } else if (anotherMotifLen < minLen) { minLen = anotherMotifLen; } } } tmpSameLengthMotifs.setSameLenMotifs(newMotifClass); tmpSameLengthMotifs.setMinMotifLen(minLen); tmpSameLengthMotifs.setMaxMotifLen(maxLen); allClassifiedMotifs.add(tmpSameLengthMotifs); } return allClassifiedMotifs; // System.out.println(); }
[ "public", "ArrayList", "<", "SameLengthMotifs", ">", "classifyMotifs", "(", "double", "lengthThreshold", ",", "GrammarRules", "grammarRules", ")", "{", "// reset vars\r", "ArrayList", "<", "SameLengthMotifs", ">", "allClassifiedMotifs", "=", "new", "ArrayList", "<", "...
Classify the motifs based on their length. It calls "getAllMotifs()" to get all the sub-sequences that were generated by Sequitur rules in ascending order. Then bins all the sub-sequences by length based on the length of the first sub-sequence in each class, that is, the shortest sub-sequence in each class. @param lengthThreshold the motif length threshold. @param grammarRules the rules set. @return the same length motifs.
[ "Classify", "the", "motifs", "based", "on", "their", "length", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L30-L90
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.getAllMotifs
protected ArrayList<SAXMotif> getAllMotifs(GrammarRules grammarRules) { // result ArrayList<SAXMotif> allMotifs = new ArrayList<SAXMotif>(); int ruleNumber = grammarRules.size(); // iterate over all rules for (int i = 0; i < ruleNumber; i++) { // iterate over all segments/motifs/sub-sequences which correspond // to the rule ArrayList<RuleInterval> arrPos = grammarRules.getRuleRecord(i).getRuleIntervals(); for (RuleInterval saxPos : arrPos) { SAXMotif motif = new SAXMotif(); motif.setPos(saxPos); motif.setRuleIndex(i); motif.setClassified(false); allMotifs.add(motif); } } // ascending order Collections.sort(allMotifs); return allMotifs; }
java
protected ArrayList<SAXMotif> getAllMotifs(GrammarRules grammarRules) { // result ArrayList<SAXMotif> allMotifs = new ArrayList<SAXMotif>(); int ruleNumber = grammarRules.size(); // iterate over all rules for (int i = 0; i < ruleNumber; i++) { // iterate over all segments/motifs/sub-sequences which correspond // to the rule ArrayList<RuleInterval> arrPos = grammarRules.getRuleRecord(i).getRuleIntervals(); for (RuleInterval saxPos : arrPos) { SAXMotif motif = new SAXMotif(); motif.setPos(saxPos); motif.setRuleIndex(i); motif.setClassified(false); allMotifs.add(motif); } } // ascending order Collections.sort(allMotifs); return allMotifs; }
[ "protected", "ArrayList", "<", "SAXMotif", ">", "getAllMotifs", "(", "GrammarRules", "grammarRules", ")", "{", "// result\r", "ArrayList", "<", "SAXMotif", ">", "allMotifs", "=", "new", "ArrayList", "<", "SAXMotif", ">", "(", ")", ";", "int", "ruleNumber", "="...
Stores all the sub-sequences that generated by Sequitur rules into an array list sorted by sub-sequence length in ascending order. @param grammarRules the set of grammar rules. @return the list of all sub-sequences sorted by length in ascending order.
[ "Stores", "all", "the", "sub", "-", "sequences", "that", "generated", "by", "Sequitur", "rules", "into", "an", "array", "list", "sorted", "by", "sub", "-", "sequence", "length", "in", "ascending", "order", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L99-L125
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.removeOverlappingInSimiliar
protected ArrayList<SameLengthMotifs> removeOverlappingInSimiliar( ArrayList<SameLengthMotifs> allClassifiedMotifs, GrammarRules grammarRules, double[] ts, double thresouldCom) { ArrayList<SAXMotif> motifsBeDeleted = new ArrayList<SAXMotif>(); SAXPointsNumber[] pointsNumberRemoveStrategy = countPointNumber(grammarRules, ts); for (SameLengthMotifs sameLenMotifs : allClassifiedMotifs) { outer: for (int j = 0; j < sameLenMotifs.getSameLenMotifs().size(); j++) { SAXMotif tempMotif = sameLenMotifs.getSameLenMotifs().get(j); int tempMotifLen = tempMotif.getPos().getEnd() - tempMotif.getPos().getStart() + 1; for (int i = j + 1; i < sameLenMotifs.getSameLenMotifs().size(); i++) { SAXMotif anotherMotif = sameLenMotifs.getSameLenMotifs().get(i); int anotherMotifLen = anotherMotif.getPos().getEnd() - anotherMotif.getPos().getStart() + 1; double minEndPos = Math.min(tempMotif.getPos().getEnd(), anotherMotif.getPos().getEnd()); double maxStartPos = Math.max(tempMotif.getPos().getStart(), anotherMotif.getPos().getStart()); // the length in common. double commonLen = minEndPos - maxStartPos + 1; // if they are overlapped motif, remove the shorter one if (commonLen > (tempMotifLen * thresouldCom)) { SAXMotif deletedMotif = new SAXMotif(); SAXMotif similarWith = new SAXMotif(); boolean isAnotherBetter; if (pointsNumberRemoveStrategy != null) { isAnotherBetter = decideRemove(anotherMotif, tempMotif, pointsNumberRemoveStrategy); } else { isAnotherBetter = anotherMotifLen > tempMotifLen; } if (isAnotherBetter) { deletedMotif = tempMotif; similarWith = anotherMotif; sameLenMotifs.getSameLenMotifs().remove(j); deletedMotif.setSimilarWith(similarWith); motifsBeDeleted.add(deletedMotif); j--; continue outer; } else { deletedMotif = anotherMotif; similarWith = tempMotif; sameLenMotifs.getSameLenMotifs().remove(i); deletedMotif.setSimilarWith(similarWith); motifsBeDeleted.add(deletedMotif); i--; } } } } int minLength = sameLenMotifs.getSameLenMotifs().get(0).getPos().endPos - sameLenMotifs.getSameLenMotifs().get(0).getPos().startPos + 1; int sameLenMotifsSize = sameLenMotifs.getSameLenMotifs().size(); int maxLength = sameLenMotifs.getSameLenMotifs().get(sameLenMotifsSize - 1).getPos().endPos - sameLenMotifs.getSameLenMotifs().get(sameLenMotifsSize - 1).getPos().startPos + 1; sameLenMotifs.setMinMotifLen(minLength); sameLenMotifs.setMaxMotifLen(maxLength); } return allClassifiedMotifs; }
java
protected ArrayList<SameLengthMotifs> removeOverlappingInSimiliar( ArrayList<SameLengthMotifs> allClassifiedMotifs, GrammarRules grammarRules, double[] ts, double thresouldCom) { ArrayList<SAXMotif> motifsBeDeleted = new ArrayList<SAXMotif>(); SAXPointsNumber[] pointsNumberRemoveStrategy = countPointNumber(grammarRules, ts); for (SameLengthMotifs sameLenMotifs : allClassifiedMotifs) { outer: for (int j = 0; j < sameLenMotifs.getSameLenMotifs().size(); j++) { SAXMotif tempMotif = sameLenMotifs.getSameLenMotifs().get(j); int tempMotifLen = tempMotif.getPos().getEnd() - tempMotif.getPos().getStart() + 1; for (int i = j + 1; i < sameLenMotifs.getSameLenMotifs().size(); i++) { SAXMotif anotherMotif = sameLenMotifs.getSameLenMotifs().get(i); int anotherMotifLen = anotherMotif.getPos().getEnd() - anotherMotif.getPos().getStart() + 1; double minEndPos = Math.min(tempMotif.getPos().getEnd(), anotherMotif.getPos().getEnd()); double maxStartPos = Math.max(tempMotif.getPos().getStart(), anotherMotif.getPos().getStart()); // the length in common. double commonLen = minEndPos - maxStartPos + 1; // if they are overlapped motif, remove the shorter one if (commonLen > (tempMotifLen * thresouldCom)) { SAXMotif deletedMotif = new SAXMotif(); SAXMotif similarWith = new SAXMotif(); boolean isAnotherBetter; if (pointsNumberRemoveStrategy != null) { isAnotherBetter = decideRemove(anotherMotif, tempMotif, pointsNumberRemoveStrategy); } else { isAnotherBetter = anotherMotifLen > tempMotifLen; } if (isAnotherBetter) { deletedMotif = tempMotif; similarWith = anotherMotif; sameLenMotifs.getSameLenMotifs().remove(j); deletedMotif.setSimilarWith(similarWith); motifsBeDeleted.add(deletedMotif); j--; continue outer; } else { deletedMotif = anotherMotif; similarWith = tempMotif; sameLenMotifs.getSameLenMotifs().remove(i); deletedMotif.setSimilarWith(similarWith); motifsBeDeleted.add(deletedMotif); i--; } } } } int minLength = sameLenMotifs.getSameLenMotifs().get(0).getPos().endPos - sameLenMotifs.getSameLenMotifs().get(0).getPos().startPos + 1; int sameLenMotifsSize = sameLenMotifs.getSameLenMotifs().size(); int maxLength = sameLenMotifs.getSameLenMotifs().get(sameLenMotifsSize - 1).getPos().endPos - sameLenMotifs.getSameLenMotifs().get(sameLenMotifsSize - 1).getPos().startPos + 1; sameLenMotifs.setMinMotifLen(minLength); sameLenMotifs.setMaxMotifLen(maxLength); } return allClassifiedMotifs; }
[ "protected", "ArrayList", "<", "SameLengthMotifs", ">", "removeOverlappingInSimiliar", "(", "ArrayList", "<", "SameLengthMotifs", ">", "allClassifiedMotifs", ",", "GrammarRules", "grammarRules", ",", "double", "[", "]", "ts", ",", "double", "thresouldCom", ")", "{", ...
Removes overlapping rules in similar rule set. @param allClassifiedMotifs the set of motifs classified as the same. @param grammarRules the grammar. @param ts the input time series. @param thresouldCom the threshold. @return a reduced set of the same length rules.
[ "Removes", "overlapping", "rules", "in", "similar", "rule", "set", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L136-L204
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.decideRemove
protected boolean decideRemove(SAXMotif motif1, SAXMotif motif2, SAXPointsNumber[] pointsNumberRemoveStrategy) { // motif1 details int motif1Start = motif1.getPos().getStart(); int motif1End = motif1.getPos().getEnd() - 1; int length1 = motif1End - motif1Start; // motif2 details int motif2Start = motif2.getPos().getStart(); int motif2End = motif1.getPos().getEnd() - 1; int length2 = motif2End - motif2Start; int countsMotif1 = 0; int countsMotif2 = 0; // compute the averageWeight double averageWeight = 1; int count = 0; for (int i = 0; i < pointsNumberRemoveStrategy.length; i++) { count += pointsNumberRemoveStrategy[i].getPointOccurenceNumber(); } averageWeight = (double) count / (double) pointsNumberRemoveStrategy.length; // compute counts for motif 1 for (int i = motif1Start; i <= motif1End; i++) { countsMotif1 += pointsNumberRemoveStrategy[i].getPointOccurenceNumber(); } // compute counts for motif 2 for (int i = motif2Start; i <= motif2End; i++) { countsMotif2 += pointsNumberRemoveStrategy[i].getPointOccurenceNumber(); } // get weights double weight1 = countsMotif1 / (averageWeight * length1); double weight2 = countsMotif2 / (averageWeight * length2); if (weight1 > weight2) { return true; } return false; }
java
protected boolean decideRemove(SAXMotif motif1, SAXMotif motif2, SAXPointsNumber[] pointsNumberRemoveStrategy) { // motif1 details int motif1Start = motif1.getPos().getStart(); int motif1End = motif1.getPos().getEnd() - 1; int length1 = motif1End - motif1Start; // motif2 details int motif2Start = motif2.getPos().getStart(); int motif2End = motif1.getPos().getEnd() - 1; int length2 = motif2End - motif2Start; int countsMotif1 = 0; int countsMotif2 = 0; // compute the averageWeight double averageWeight = 1; int count = 0; for (int i = 0; i < pointsNumberRemoveStrategy.length; i++) { count += pointsNumberRemoveStrategy[i].getPointOccurenceNumber(); } averageWeight = (double) count / (double) pointsNumberRemoveStrategy.length; // compute counts for motif 1 for (int i = motif1Start; i <= motif1End; i++) { countsMotif1 += pointsNumberRemoveStrategy[i].getPointOccurenceNumber(); } // compute counts for motif 2 for (int i = motif2Start; i <= motif2End; i++) { countsMotif2 += pointsNumberRemoveStrategy[i].getPointOccurenceNumber(); } // get weights double weight1 = countsMotif1 / (averageWeight * length1); double weight2 = countsMotif2 / (averageWeight * length2); if (weight1 > weight2) { return true; } return false; }
[ "protected", "boolean", "decideRemove", "(", "SAXMotif", "motif1", ",", "SAXMotif", "motif2", ",", "SAXPointsNumber", "[", "]", "pointsNumberRemoveStrategy", ")", "{", "// motif1 details\r", "int", "motif1Start", "=", "motif1", ".", "getPos", "(", ")", ".", "getSt...
Decide which one from overlapping subsequences should be removed. The decision rule is that each sub-sequence has a weight, the one with the smaller weight should be removed. The weight is S/(A * L). S is the sum of occurrence time of all data points in that sub-sequence, A is the average weight of the whole time series, and L is the length of that sub-sequence. @param motif1 the motif1. @param motif2 the motif2. @param pointsNumberRemoveStrategy the strategy for cleaning up. @return the decision.
[ "Decide", "which", "one", "from", "overlapping", "subsequences", "should", "be", "removed", ".", "The", "decision", "rule", "is", "that", "each", "sub", "-", "sequence", "has", "a", "weight", "the", "one", "with", "the", "smaller", "weight", "should", "be", ...
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L252-L295
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.refinePatternsByClustering
protected ArrayList<SameLengthMotifs> refinePatternsByClustering(GrammarRules grammarRules, double[] ts, ArrayList<SameLengthMotifs> allClassifiedMotifs, double fractionTopDist) { DistanceComputation dc = new DistanceComputation(); double[] origTS = ts; ArrayList<SameLengthMotifs> newAllClassifiedMotifs = new ArrayList<SameLengthMotifs>(); for (SameLengthMotifs sameLenMotifs : allClassifiedMotifs) { ArrayList<RuleInterval> arrPos = new ArrayList<RuleInterval>(); ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs(); for (SAXMotif ss : subsequences) { arrPos.add(ss.getPos()); } int patternNum = arrPos.size(); if (patternNum < 2) { continue; } double dt[][] = new double[patternNum][patternNum]; // Build distance matrix. for (int i = 0; i < patternNum; i++) { RuleInterval saxPos = arrPos.get(i); int start1 = saxPos.getStart(); int end1 = saxPos.getEnd(); double[] ts1 = Arrays.copyOfRange(origTS, start1, end1); for (int j = 0; j < arrPos.size(); j++) { RuleInterval saxPos2 = arrPos.get(j); if (dt[i][j] > 0) { continue; } double d = 0; dt[i][j] = d; if (i == j) { continue; } int start2 = saxPos2.getStart(); int end2 = saxPos2.getEnd(); double[] ts2 = Arrays.copyOfRange(origTS, start2, end2); if (ts1.length > ts2.length) d = dc.calcDistTSAndPattern(ts1, ts2); else d = dc.calcDistTSAndPattern(ts2, ts1); // DTW dtw = new DTW(ts1, ts2); // d = dtw.warpingDistance; dt[i][j] = d; } } String[] patternsName = new String[patternNum]; for (int i = 0; i < patternNum; i++) { patternsName[i] = String.valueOf(i); } ClusteringAlgorithm alg = new DefaultClusteringAlgorithm(); Cluster cluster = alg.performClustering(dt, patternsName, new AverageLinkageStrategy()); // int minPatternPerCls = (int) (0.3 * patternNum); // minPatternPerCls = minPatternPerCls > 0 ? minPatternPerCls : 1; int minPatternPerCls = 1; if (cluster.getDistance() == null) { // System.out.print(false); continue; } // TODO: refine hard coded threshold // double cutDist = cluster.getDistance() * 0.67; double cutDist = cluster.getDistanceValue() * fractionTopDist; ArrayList<String[]> clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls); while (clusterTSIdx.size() <= 0) { cutDist += cutDist / 2; clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls); } newAllClassifiedMotifs.addAll(SeparateMotifsByClustering(clusterTSIdx, sameLenMotifs)); } return newAllClassifiedMotifs; }
java
protected ArrayList<SameLengthMotifs> refinePatternsByClustering(GrammarRules grammarRules, double[] ts, ArrayList<SameLengthMotifs> allClassifiedMotifs, double fractionTopDist) { DistanceComputation dc = new DistanceComputation(); double[] origTS = ts; ArrayList<SameLengthMotifs> newAllClassifiedMotifs = new ArrayList<SameLengthMotifs>(); for (SameLengthMotifs sameLenMotifs : allClassifiedMotifs) { ArrayList<RuleInterval> arrPos = new ArrayList<RuleInterval>(); ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs(); for (SAXMotif ss : subsequences) { arrPos.add(ss.getPos()); } int patternNum = arrPos.size(); if (patternNum < 2) { continue; } double dt[][] = new double[patternNum][patternNum]; // Build distance matrix. for (int i = 0; i < patternNum; i++) { RuleInterval saxPos = arrPos.get(i); int start1 = saxPos.getStart(); int end1 = saxPos.getEnd(); double[] ts1 = Arrays.copyOfRange(origTS, start1, end1); for (int j = 0; j < arrPos.size(); j++) { RuleInterval saxPos2 = arrPos.get(j); if (dt[i][j] > 0) { continue; } double d = 0; dt[i][j] = d; if (i == j) { continue; } int start2 = saxPos2.getStart(); int end2 = saxPos2.getEnd(); double[] ts2 = Arrays.copyOfRange(origTS, start2, end2); if (ts1.length > ts2.length) d = dc.calcDistTSAndPattern(ts1, ts2); else d = dc.calcDistTSAndPattern(ts2, ts1); // DTW dtw = new DTW(ts1, ts2); // d = dtw.warpingDistance; dt[i][j] = d; } } String[] patternsName = new String[patternNum]; for (int i = 0; i < patternNum; i++) { patternsName[i] = String.valueOf(i); } ClusteringAlgorithm alg = new DefaultClusteringAlgorithm(); Cluster cluster = alg.performClustering(dt, patternsName, new AverageLinkageStrategy()); // int minPatternPerCls = (int) (0.3 * patternNum); // minPatternPerCls = minPatternPerCls > 0 ? minPatternPerCls : 1; int minPatternPerCls = 1; if (cluster.getDistance() == null) { // System.out.print(false); continue; } // TODO: refine hard coded threshold // double cutDist = cluster.getDistance() * 0.67; double cutDist = cluster.getDistanceValue() * fractionTopDist; ArrayList<String[]> clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls); while (clusterTSIdx.size() <= 0) { cutDist += cutDist / 2; clusterTSIdx = findCluster(cluster, cutDist, minPatternPerCls); } newAllClassifiedMotifs.addAll(SeparateMotifsByClustering(clusterTSIdx, sameLenMotifs)); } return newAllClassifiedMotifs; }
[ "protected", "ArrayList", "<", "SameLengthMotifs", ">", "refinePatternsByClustering", "(", "GrammarRules", "grammarRules", ",", "double", "[", "]", "ts", ",", "ArrayList", "<", "SameLengthMotifs", ">", "allClassifiedMotifs", ",", "double", "fractionTopDist", ")", "{",...
Refines patterns by clustering. @param grammarRules the set of grammar rules. @param ts the input time series. @param allClassifiedMotifs all the motifs in groups. @param fractionTopDist the fraction threshold. @return refined set of patterns.
[ "Refines", "patterns", "by", "clustering", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L352-L433
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.findCluster
private ArrayList<String[]> findCluster(Cluster cluster, double cutDist, int minPatternPerCls) { ArrayList<String[]> clusterTSIdx = new ArrayList<String[]>(); if (cluster.getDistance() != null) { // if (cluster.getDistance() > cutDist) { if (cluster.getDistanceValue() > cutDist) { if (cluster.getChildren().size() > 0) { clusterTSIdx.addAll(findCluster(cluster.getChildren().get(0), cutDist, minPatternPerCls)); clusterTSIdx.addAll(findCluster(cluster.getChildren().get(1), cutDist, minPatternPerCls)); } } else { // String[] idxes = cluster.getName().split("&"); ArrayList<String> itemsInCluster = getNameInCluster(cluster); String[] idxes = itemsInCluster.toArray(new String[itemsInCluster.size()]); if (idxes.length > minPatternPerCls) { clusterTSIdx.add(idxes); } } } return clusterTSIdx; }
java
private ArrayList<String[]> findCluster(Cluster cluster, double cutDist, int minPatternPerCls) { ArrayList<String[]> clusterTSIdx = new ArrayList<String[]>(); if (cluster.getDistance() != null) { // if (cluster.getDistance() > cutDist) { if (cluster.getDistanceValue() > cutDist) { if (cluster.getChildren().size() > 0) { clusterTSIdx.addAll(findCluster(cluster.getChildren().get(0), cutDist, minPatternPerCls)); clusterTSIdx.addAll(findCluster(cluster.getChildren().get(1), cutDist, minPatternPerCls)); } } else { // String[] idxes = cluster.getName().split("&"); ArrayList<String> itemsInCluster = getNameInCluster(cluster); String[] idxes = itemsInCluster.toArray(new String[itemsInCluster.size()]); if (idxes.length > minPatternPerCls) { clusterTSIdx.add(idxes); } } } return clusterTSIdx; }
[ "private", "ArrayList", "<", "String", "[", "]", ">", "findCluster", "(", "Cluster", "cluster", ",", "double", "cutDist", ",", "int", "minPatternPerCls", ")", "{", "ArrayList", "<", "String", "[", "]", ">", "clusterTSIdx", "=", "new", "ArrayList", "<", "St...
Finds clusters. @param cluster the Cluster. @param cutDist the cut distance threshold. @param minPatternPerCls the minimal patterns threshold. @return the clusters.
[ "Finds", "clusters", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L443-L466
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.getNameInCluster
private ArrayList<String> getNameInCluster(Cluster cluster) { ArrayList<String> itemsInCluster = new ArrayList<String>(); String nodeName; if (cluster.isLeaf()) { nodeName = cluster.getName(); itemsInCluster.add(nodeName); } else { // String[] clusterName = cluster.getName().split("#"); // nodeName = clusterName[1]; } for (Cluster child : cluster.getChildren()) { ArrayList<String> childrenNames = getNameInCluster(child); itemsInCluster.addAll(childrenNames); } return itemsInCluster; }
java
private ArrayList<String> getNameInCluster(Cluster cluster) { ArrayList<String> itemsInCluster = new ArrayList<String>(); String nodeName; if (cluster.isLeaf()) { nodeName = cluster.getName(); itemsInCluster.add(nodeName); } else { // String[] clusterName = cluster.getName().split("#"); // nodeName = clusterName[1]; } for (Cluster child : cluster.getChildren()) { ArrayList<String> childrenNames = getNameInCluster(child); itemsInCluster.addAll(childrenNames); } return itemsInCluster; }
[ "private", "ArrayList", "<", "String", ">", "getNameInCluster", "(", "Cluster", "cluster", ")", "{", "ArrayList", "<", "String", ">", "itemsInCluster", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "String", "nodeName", ";", "if", "(", "clust...
Finds out cluster names. @param cluster the cluster. @return pattern names.
[ "Finds", "out", "cluster", "names", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L474-L492
train
jMotif/GI
src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java
RuleOrganizer.SeparateMotifsByClustering
private ArrayList<SameLengthMotifs> SeparateMotifsByClustering(ArrayList<String[]> clusterTSIdx, SameLengthMotifs sameLenMotifs) { ArrayList<SameLengthMotifs> newResult = new ArrayList<SameLengthMotifs>(); if (clusterTSIdx.size() > 1) { ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs(); for (String[] idxesInCluster : clusterTSIdx) { SameLengthMotifs newIthSLM = new SameLengthMotifs(); ArrayList<SAXMotif> sameLenSS = new ArrayList<SAXMotif>(); int minL = sameLenMotifs.getMinMotifLen(); int maxL = sameLenMotifs.getMaxMotifLen(); for (String i : idxesInCluster) { SAXMotif ssI = subsequences.get(Integer.parseInt(i)); int len = ssI.getPos().getEnd() - ssI.getPos().getStart(); if (len < minL) { minL = len; } else if (len > maxL) { maxL = len; } sameLenSS.add(ssI); } newIthSLM.setSameLenMotifs(sameLenSS); newIthSLM.setMaxMotifLen(maxL); newIthSLM.setMinMotifLen(minL); newResult.add(newIthSLM); } } else { newResult.add(sameLenMotifs); } return newResult; }
java
private ArrayList<SameLengthMotifs> SeparateMotifsByClustering(ArrayList<String[]> clusterTSIdx, SameLengthMotifs sameLenMotifs) { ArrayList<SameLengthMotifs> newResult = new ArrayList<SameLengthMotifs>(); if (clusterTSIdx.size() > 1) { ArrayList<SAXMotif> subsequences = sameLenMotifs.getSameLenMotifs(); for (String[] idxesInCluster : clusterTSIdx) { SameLengthMotifs newIthSLM = new SameLengthMotifs(); ArrayList<SAXMotif> sameLenSS = new ArrayList<SAXMotif>(); int minL = sameLenMotifs.getMinMotifLen(); int maxL = sameLenMotifs.getMaxMotifLen(); for (String i : idxesInCluster) { SAXMotif ssI = subsequences.get(Integer.parseInt(i)); int len = ssI.getPos().getEnd() - ssI.getPos().getStart(); if (len < minL) { minL = len; } else if (len > maxL) { maxL = len; } sameLenSS.add(ssI); } newIthSLM.setSameLenMotifs(sameLenSS); newIthSLM.setMaxMotifLen(maxL); newIthSLM.setMinMotifLen(minL); newResult.add(newIthSLM); } } else { newResult.add(sameLenMotifs); } return newResult; }
[ "private", "ArrayList", "<", "SameLengthMotifs", ">", "SeparateMotifsByClustering", "(", "ArrayList", "<", "String", "[", "]", ">", "clusterTSIdx", ",", "SameLengthMotifs", "sameLenMotifs", ")", "{", "ArrayList", "<", "SameLengthMotifs", ">", "newResult", "=", "new"...
Separates motifs via clustering. @param clusterTSIdx The index. @param sameLenMotifs the motif groups. @return same length motifs.
[ "Separates", "motifs", "via", "clustering", "." ]
381212dd4f193246a6df82bd46f0d2bcd04a68d6
https://github.com/jMotif/GI/blob/381212dd4f193246a6df82bd46f0d2bcd04a68d6/src/main/java/net/seninp/gi/clusterrule/RuleOrganizer.java#L501-L535
train
btrplace/scheduler
btrpsl/src/main/java/org/btrplace/btrpsl/tree/ConstraintStatement.java
ConstraintStatement.go
@Override public BtrpOperand go(BtrPlaceTree parent) { String cname = getText(); if (catalog == null) { return ignoreError("No constraints available"); } SatConstraintBuilder b = catalog.getConstraint(cname); if (b == null) { ignoreError("Unknown constraint '" + cname + "'"); } //Get the params int i = 0; boolean discrete = false; if (">>".equals(getChild(0).getText())) { i = 1; discrete = true; } List<BtrpOperand> params = new ArrayList<>(); for (; i < getChildCount(); i++) { params.add(getChild(i).go(this)); } if (b != null) { List<? extends SatConstraint> constraints = b.buildConstraint(this, params); for (SatConstraint c : constraints) { if (c != null) { if (discrete) { if (!c.setContinuous(false)) { return ignoreError("Discrete restriction is not supported by constraint '" + cname + "'"); } } else { //force the continuous mode, if available c.setContinuous(true); } script.addConstraint(c); } } } return IgnorableOperand.getInstance(); }
java
@Override public BtrpOperand go(BtrPlaceTree parent) { String cname = getText(); if (catalog == null) { return ignoreError("No constraints available"); } SatConstraintBuilder b = catalog.getConstraint(cname); if (b == null) { ignoreError("Unknown constraint '" + cname + "'"); } //Get the params int i = 0; boolean discrete = false; if (">>".equals(getChild(0).getText())) { i = 1; discrete = true; } List<BtrpOperand> params = new ArrayList<>(); for (; i < getChildCount(); i++) { params.add(getChild(i).go(this)); } if (b != null) { List<? extends SatConstraint> constraints = b.buildConstraint(this, params); for (SatConstraint c : constraints) { if (c != null) { if (discrete) { if (!c.setContinuous(false)) { return ignoreError("Discrete restriction is not supported by constraint '" + cname + "'"); } } else { //force the continuous mode, if available c.setContinuous(true); } script.addConstraint(c); } } } return IgnorableOperand.getInstance(); }
[ "@", "Override", "public", "BtrpOperand", "go", "(", "BtrPlaceTree", "parent", ")", "{", "String", "cname", "=", "getText", "(", ")", ";", "if", "(", "catalog", "==", "null", ")", "{", "return", "ignoreError", "(", "\"No constraints available\"", ")", ";", ...
Build the constraint. The constraint is built if it exists in the catalog and if the parameters are compatible with the constraint signature. @param parent the parent of the root @return {@code Content.empty} if the constraint is successfully built. {@code Content.ignore} if an error occurred (the error is already reported)
[ "Build", "the", "constraint", ".", "The", "constraint", "is", "built", "if", "it", "exists", "in", "the", "catalog", "and", "if", "the", "parameters", "are", "compatible", "with", "the", "constraint", "signature", "." ]
611063aad0b47a016e57ebf36fa4dfdf24de09e8
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/btrpsl/src/main/java/org/btrplace/btrpsl/tree/ConstraintStatement.java#L67-L107
train
nikolavp/approval
approval-core/src/main/java/com/github/approval/reporters/ExecutableDifferenceReporter.java
ExecutableDifferenceReporter.runProcess
public static Process runProcess(String... cmdParts) throws IOException { return new ProcessBuilder(buildCommandline(cmdParts)) .inheritIO() .start(); }
java
public static Process runProcess(String... cmdParts) throws IOException { return new ProcessBuilder(buildCommandline(cmdParts)) .inheritIO() .start(); }
[ "public", "static", "Process", "runProcess", "(", "String", "...", "cmdParts", ")", "throws", "IOException", "{", "return", "new", "ProcessBuilder", "(", "buildCommandline", "(", "cmdParts", ")", ")", ".", "inheritIO", "(", ")", ".", "start", "(", ")", ";", ...
Execute a command with the following arguments. @param cmdParts the command parts @return the process for the command that was started @throws IOException if there were any I/O errors
[ "Execute", "a", "command", "with", "the", "following", "arguments", "." ]
5e32ecc3bc7f631e94a7049894fdd99a3aa5b1b8
https://github.com/nikolavp/approval/blob/5e32ecc3bc7f631e94a7049894fdd99a3aa5b1b8/approval-core/src/main/java/com/github/approval/reporters/ExecutableDifferenceReporter.java#L125-L129
train