code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public static String getXMLValidString(final String input,
final boolean replace, final char replacement) {
if (input == null) {
return null;
}
if ("".equals(input)) {
return "";
}
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
if (XMLStringUtil.isXMLValid(c)) {
sb.append(c);
} else if (replace) {
sb.append(replacement);
}
}
return sb.toString();
} | java |
public boolean release() {
if (this.released) {
// already (marked as) released...
return false;
}
this.released = true;
if (this.childCount == 0) {
if (this.parent == null) {
return true;
} else {
assert (this.parent.childCount > 0);
this.parent.childCount--;
if ((this.parent.childCount == 0) && (this.parent.released)) {
return true;
}
}
}
return false;
} | java |
@Nonnull
public static <T> ApprovalBuilder<T> of(Class<T> clazz) {
return new ApprovalBuilder<T>(clazz);
} | java |
@Nonnull
public static Path getApprovalPath(Path filePath) {
Pre.notNull(filePath, "filePath");
String s = filePath.toString();
int extensionIndex = s.lastIndexOf('.');
if (extensionIndex == -1) {
return Paths.get(s + FOR_APPROVAL_EXTENSION);
}
int lastPartOfPath = s.lastIndexOf('/');
if (lastPartOfPath != -1 && lastPartOfPath > extensionIndex) {
//there was no extension and the directory contains dots.
return Paths.get(s + FOR_APPROVAL_EXTENSION);
}
String firstPart = s.substring(0, extensionIndex);
String extension = s.substring(extensionIndex);
return Paths.get(firstPart + FOR_APPROVAL_EXTENSION + extension);
} | java |
@Nonnull
public static Point fromUniformlyDistributedRandomPoints(@Nonnull final Random randomGenerator) {
checkNonnull("randomGenerator", randomGenerator);
// Calculate uniformly distributed 3D point on sphere (radius = 1.0):
// http://mathproofs.blogspot.co.il/2005/04/uniform-random-distribution-on-sphere.html
final double unitRand1 = randomGenerator.nextDouble();
final double unitRand2 = randomGenerator.nextDouble();
final double theta0 = (2.0 * Math.PI) * unitRand1;
final double theta1 = Math.acos(1.0 - (2.0 * unitRand2));
final double x = Math.sin(theta0) * Math.sin(theta1);
final double y = Math.cos(theta0) * Math.sin(theta1);
final double z = Math.cos(theta1);
// Convert Carthesian 3D point into lat/lon (radius = 1.0):
// http://stackoverflow.com/questions/1185408/converting-from-longitude-latitude-to-cartesian-coordinates
final double latRad = Math.asin(z);
final double lonRad = Math.atan2(y, x);
// Convert radians to degrees.
assert !Double.isNaN(latRad);
assert !Double.isNaN(lonRad);
final double lat = latRad * (180.0 / Math.PI);
final double lon = lonRad * (180.0 / Math.PI);
return fromDeg(lat, lon);
} | java |
public static double distanceInMeters(@Nonnull final Point p1, @Nonnull final Point p2) {
checkNonnull("p1", p1);
checkNonnull("p2", p2);
final Point from;
final Point to;
if (p1.getLonDeg() <= p2.getLonDeg()) {
from = p1;
to = p2;
} else {
from = p2;
to = p1;
}
// Calculate mid point of 2 latitudes.
final double avgLat = (from.getLatDeg() + to.getLatDeg()) / 2.0;
final double deltaLatDeg = Math.abs(to.getLatDeg() - from.getLatDeg());
final double deltaLonDeg360 = Math.abs(to.getLonDeg() - from.getLonDeg());
final double deltaLonDeg = ((deltaLonDeg360 <= 180.0) ? deltaLonDeg360 : (360.0 - deltaLonDeg360));
// Meters per longitude is fixed; per latitude requires * cos(avg(lat)).
final double deltaXMeters = degreesLonToMetersAtLat(deltaLonDeg, avgLat);
final double deltaYMeters = degreesLatToMeters(deltaLatDeg);
// Calculate length through Earth. This is an approximation, but works fine for short distances.
return Math.sqrt((deltaXMeters * deltaXMeters) + (deltaYMeters * deltaYMeters));
} | java |
@Override
public List<? extends SatConstraint> buildConstraint(BtrPlaceTree t, List<BtrpOperand> args) {
if (!checkConformance(t, args)) {
return Collections.emptyList();
}
// Get the first parameter
@SuppressWarnings("unchecked")
List<VM> s = (List<VM>) params[0].transform(this, t, args.get(0));
if (s == null) {
return Collections.emptyList();
}
// Get param 'OneOf'
Object obj = params[1].transform(this, t, args.get(1));
if (obj == null) {
return Collections.emptyList();
}
if (obj instanceof List) {
@SuppressWarnings("unchecked")
List<VM> s2 = (List<VM>) obj;
if (s2.isEmpty()) {
t.ignoreError("Parameter '" + params[1].getName() + "' expects a non-empty list of VMs");
return Collections.emptyList();
}
return Precedence.newPrecedence(s, s2);
} else if (obj instanceof String) {
String timestamp = (String) obj;
if ("".equals(timestamp)) {
t.ignoreError("Parameter '" + params[1].getName() + "' expects a non-empty string");
return Collections.emptyList();
}
return Deadline.newDeadline(s, timestamp);
} else {
return Collections.emptyList();
}
} | java |
public void remove() {
BasicDoubleLinkedNode<V> next = getNext();
if (next != null) {
next.previous = this.previous;
}
if (this.previous != null) {
this.previous.setNext(next);
}
} | java |
@Override
public boolean applyAction(Model i) {
Mapping c = i.getMapping();
return c.isRunning(vm)
&& c.getVMLocation(vm).equals(src)
&& !src.equals(dst)
&& c.addRunningVM(vm, dst);
} | java |
public static void resetCaches(int size) {
nodesCache = new LinkedHashMap<String, List<Node>>() {
@Override
protected boolean removeEldestEntry(Map.Entry<String, List<Node>> foo) {
return size() == size;
}
};
vmsCache = new LinkedHashMap<String, List<VM>>() {
@Override
protected boolean removeEldestEntry(Map.Entry<String, List<VM>> foo) {
return size() == size;
}
};
} | java |
public static int requiredInt(JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
try {
return (Integer) o.get(id);
} catch (ClassCastException e) {
throw new JSONConverterException("Unable to read a int from string '" + id + "'", e);
}
} | java |
public static int optInt(JSONObject o, String id, int def) throws JSONConverterException {
if (o.containsKey(id)) {
try {
return (Integer) o.get(id);
} catch (ClassCastException e) {
throw new JSONConverterException("Unable to read a int from string '" + id + "'", e);
}
}
return def;
} | java |
public static void checkKeys(JSONObject o, String... keys) throws JSONConverterException {
for (String k : keys) {
if (!o.containsKey(k)) {
throw new JSONConverterException("Missing key '" + k + "'");
}
}
} | java |
public static String requiredString(JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
Object x = o.get(id);
return x.toString();
} | java |
public static double requiredDouble(JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
Object x = o.get(id);
if (!(x instanceof Number)) {
throw new JSONConverterException("Number expected at key '" + id + "' but was '" + x.getClass() + "'.");
}
return ((Number) x).doubleValue();
} | java |
public static boolean requiredBoolean(JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
Object x = o.get(id);
if (!(x instanceof Boolean)) {
throw new JSONConverterException("Boolean expected at key '" + id + "' but was '" + x.getClass() + "'.");
}
return (Boolean) x;
} | java |
public static List<VM> vmsFromJSON(Model mo, JSONArray a) throws JSONConverterException {
String json = a.toJSONString();
List<VM> s = vmsCache.get(json);
if (s != null) {
return s;
}
s = new ArrayList<>(a.size());
for (Object o : a) {
s.add(getVM(mo, (int) o));
}
vmsCache.put(json, s);
return s;
} | java |
public static List<Node> nodesFromJSON(Model mo, JSONArray a) throws JSONConverterException {
String json = a.toJSONString();
List<Node> s = nodesCache.get(json);
if (s != null) {
return s;
}
s = new ArrayList<>(a.size());
for (Object o : a) {
s.add(getNode(mo, (int) o));
}
nodesCache.put(json, s);
return s;
} | java |
public static JSONArray vmsToJSON(Collection<VM> s) {
JSONArray a = new JSONArray();
for (Element e : s) {
a.add(e.id());
}
return a;
} | java |
public static JSONArray nodesToJSON(Collection<Node> s) {
JSONArray a = new JSONArray();
for (Element e : s) {
a.add(e.id());
}
return a;
} | java |
public static List<VM> requiredVMs(Model mo, JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
Object x = o.get(id);
if (!(x instanceof JSONArray)) {
throw new JSONConverterException("integers expected at key '" + id + "'");
}
return vmsFromJSON(mo, (JSONArray) x);
} | java |
public static List<Node> requiredNodes(Model mo, JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
Object x = o.get(id);
if (!(x instanceof JSONArray)) {
throw new JSONConverterException("integers expected at key '" + id + "'");
}
return nodesFromJSON(mo, (JSONArray) x);
} | java |
public static Set<Collection<VM>> requiredVMPart(Model mo, JSONObject o, String id) throws JSONConverterException {
Set<Collection<VM>> vms = new HashSet<>();
Object x = o.get(id);
if (!(x instanceof JSONArray)) {
throw new JSONConverterException("Set of identifiers sets expected at key '" + id + "'");
}
for (Object obj : (JSONArray) x) {
vms.add(vmsFromJSON(mo, (JSONArray) obj));
}
return vms;
} | java |
public static Set<Collection<Node>> requiredNodePart(Model mo, JSONObject o, String id) throws JSONConverterException {
Set<Collection<Node>> nodes = new HashSet<>();
Object x = o.get(id);
if (!(x instanceof JSONArray)) {
throw new JSONConverterException("Set of identifiers sets expected at key '" + id + "'");
}
for (Object obj : (JSONArray) x) {
nodes.add(nodesFromJSON(mo, (JSONArray) obj));
}
return nodes;
} | java |
public static VM requiredVM(Model mo, JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
try {
return getVM(mo, (Integer) o.get(id));
} catch (ClassCastException e) {
throw new JSONConverterException("Unable to read a VM identifier from string at key '" + id + "'", e);
}
} | java |
public static Node requiredNode(Model mo, JSONObject o, String id) throws JSONConverterException {
checkKeys(o, id);
try {
return getNode(mo, (Integer) o.get(id));
} catch (ClassCastException e) {
throw new JSONConverterException("Unable to read a Node identifier from string at key '" + id + "'", e);
}
} | java |
public static VM getVM(Model mo, int vmID) throws JSONConverterException {
VM vm = new VM(vmID);
if (!mo.contains(vm)) {
throw new JSONConverterException("Undeclared vm '" + vmID + "'");
}
return vm;
} | java |
public static Node getNode(Model mo, int nodeID) throws JSONConverterException {
Node n = new Node(nodeID);
if (!mo.contains(n)) {
throw new JSONConverterException("Undeclared node '" + nodeID + "'");
}
return n;
} | java |
@Override
public void postCostConstraints() {
if (!costActivated) {
costActivated = true;
rp.getLogger().debug("Post the cost-oriented constraints");
List<IntVar> mttrs = Stream.concat(rp.getVMActions().stream(), rp.getNodeActions().stream())
.map(Transition::getEnd).collect(Collectors.toList());
rp.getModel().post(rp.getModel().sum(mttrs.toArray(new IntVar[0]), "=", cost));
}
} | java |
@SuppressWarnings("PointlessArithmeticExpression")
int getDataFirstRecord(final int territoryNumber) {
assert (0 <= territoryNumber) && (territoryNumber <= Territory.AAA.getNumber());
return index[territoryNumber + POS_INDEX_FIRST_RECORD];
} | java |
@Override
public List<Script> getScripts(String name) throws ScriptBuilderException {
List<Script> scripts = new ArrayList<>();
if (!name.endsWith(".*")) {
String toSearch = name.replaceAll("\\.", File.separator) + Script.EXTENSION;
for (File path : paths) {
File f = new File(path.getPath() + File.separator + toSearch);
if (f.exists()) {
scripts.add(builder.build(f));
break;
}
}
} else {
//We need to consolidate the errors in allEx and rethrow it at the end if necessary
ScriptBuilderException allEx = null;
String base = name.substring(0, name.length() - 2).replaceAll("\\.", File.separator);
for (File path : paths) {
File f = new File(path.getPath() + File.separator + base);
File[] files = f.listFiles();
if (f.isDirectory() && files != null) {
for (File sf : files) {
if (sf.getName().endsWith(Script.EXTENSION)) {
try {
scripts.add(builder.build(sf));
} catch (ScriptBuilderException ex) {
if (allEx == null) {
allEx = ex;
} else {
allEx.getErrorReporter().getErrors().addAll(ex.getErrorReporter().getErrors());
}
}
}
}
}
}
if (allEx != null) {
throw allEx;
}
}
return scripts;
} | java |
public VMConsumptionComparator append(ShareableResource r, boolean asc) {
rcs.add(r);
ascs.add(asc ? 1 : -1);
return this;
} | java |
public void register(RoutingConverter<? extends Routing> r) {
java2json.put(r.getSupportedRouting(), r);
json2java.put(r.getJSONId(), r);
} | java |
public JSONObject switchToJSON(Switch s) {
JSONObject o = new JSONObject();
o.put("id", s.id());
o.put(CAPACITY_LABEL, s.getCapacity());
return o;
} | java |
public JSONArray switchesToJSON(Collection<Switch> c) {
JSONArray a = new JSONArray();
for (Switch s : c) {
a.add(switchToJSON(s));
}
return a;
} | java |
public JSONObject physicalElementToJSON(PhysicalElement pe) {
JSONObject o = new JSONObject();
if (pe instanceof Node) {
o.put("type", NODE_LABEL);
o.put("id", ((Node) pe).id());
} else if (pe instanceof Switch) {
o.put("type", SWITCH_LABEL);
o.put("id", ((Switch) pe).id());
} else {
throw new IllegalArgumentException("Unsupported physical element '" + pe.getClass().toString() + "'");
}
return o;
} | java |
public JSONObject linkToJSON(Link s) {
JSONObject o = new JSONObject();
o.put("id", s.id());
o.put(CAPACITY_LABEL, s.getCapacity());
o.put(SWITCH_LABEL, s.getSwitch().id());
o.put("physicalElement", physicalElementToJSON(s.getElement()));
return o;
} | java |
public JSONArray linksToJSON(Collection<Link> c) {
JSONArray a = new JSONArray();
for (Link l : c) {
a.add(linkToJSON(l));
}
return a;
} | java |
public Routing routingFromJSON(Model mo, JSONObject o) throws JSONConverterException {
String type = requiredString(o, "type");
RoutingConverter<? extends Routing> c = json2java.get(type);
if (c == null) {
throw new JSONConverterException("No converter available for a routing of type '" + type + "'");
}
return c.fromJSON(mo, o);
} | java |
public Switch switchFromJSON(JSONObject o) throws JSONConverterException {
return new Switch(requiredInt(o, "id"), readCapacity(o));
} | java |
public void switchesFromJSON(Network net, JSONArray a) throws JSONConverterException {
for (Object o : a) {
net.newSwitch(requiredInt((JSONObject) o, "id"), readCapacity((JSONObject) o));
}
} | java |
public PhysicalElement physicalElementFromJSON(Model mo, Network net, JSONObject o) throws JSONConverterException {
String type = requiredString(o, "type");
switch (type) {
case NODE_LABEL:
return requiredNode(mo, o, "id");
case SWITCH_LABEL:
return getSwitch(net, requiredInt(o, "id"));
default:
throw new JSONConverterException("type '" + type + "' is not a physical element");
}
} | java |
public void linkFromJSON(Model mo, Network net, JSONObject o) throws JSONConverterException {
net.connect(requiredInt(o, "id"),
readCapacity(o),
getSwitch(net, requiredInt(o, SWITCH_LABEL)),
physicalElementFromJSON(mo, net, (JSONObject) o.get("physicalElement"))
);
} | java |
public void linksFromJSON(Model mo, Network net, JSONArray a) throws JSONConverterException {
for (Object o : a) {
linkFromJSON(mo, net, (JSONObject) o);
}
} | java |
public List<SatConstraint> makeConstraints() {
List<SatConstraint> cstrs = new ArrayList<>();
//VM1 and VM2 must be running on distinct nodes
cstrs.add(new Spread(new HashSet<>(Arrays.asList(vms.get(1), vms.get(2)))));
//VM0 must have at least 3 virtual CPU dedicated to it
cstrs.add(new Preserve(vms.get(0), "cpu", 3));
//N3 must be set offline
cstrs.add(new Offline(nodes.get(3)));
//VM4 must be running, It asks for 3 cpu and 2 mem resources
cstrs.add(new Running(vms.get(4)));
cstrs.add(new Preserve(vms.get(4), "cpu", 3));
cstrs.add(new Preserve(vms.get(4), "mem", 2));
//VM3 must be turned off, i.e. set back to the ready state
cstrs.add(new Ready(vms.get(3)));
return cstrs;
} | java |
private boolean verifyWithOfColumns(ColumnState[] columnStates, TextTableInfo tableInfo) {
int tableWidth = tableInfo.getWidth();
if (tableWidth != TextColumnInfo.WIDTH_AUTO_ADJUST) {
int calculatedWidth = 0;
for (ColumnState columnState : columnStates) {
if (columnState.width < 0) {
throw new AssertionError("columnWidth=" + columnState.width);
// return false;
}
calculatedWidth = calculatedWidth + columnState.width + columnState.getColumnInfo().getBorderWidth();
}
if (calculatedWidth != tableWidth) {
throw new AssertionError("with=" + tableWidth + ", sum-of-columns=" + calculatedWidth);
// return false;
}
}
return true;
} | java |
public Switch newSwitch(int id, int capacity) {
Switch s = swBuilder.newSwitch(id, capacity);
switches.add(s);
return s;
} | java |
public List<Link> connect(int bandwidth, Switch sw, Node... nodes) {
List<Link> l = new ArrayList<>();
for (Node n : nodes) {
l.add(connect(bandwidth, sw, n));
}
return l;
} | java |
public List<Link> getConnectedLinks(PhysicalElement pe) {
List<Link> myLinks = new ArrayList<>();
for (Link l : this.links) {
if (l.getElement().equals(pe)) {
myLinks.add(l);
} else if (l.getSwitch().equals(pe)) {
myLinks.add(l);
}
}
return myLinks;
} | java |
public List<Node> getConnectedNodes() {
List<Node> nodes = new ArrayList<>();
for (Link l : links) {
if (l.getElement() instanceof Node) {
nodes.add((Node) l.getElement());
}
}
return nodes;
} | java |
public void addInclusion(SVar<T> s1, SVar<T> s2) {
this.add(new LtConstraint<SVar<T>,Set<T>>(s1, s2));
} | java |
private int randomWithRankedValues(IntVar x) {
TIntArrayList[] values = new TIntArrayList[ranks.length];
DisposableValueIterator ite = x.getValueIterator(true);
try {
while (ite.hasNext()) {
int v = ite.next();
int i;
for (i = 0; i < ranks.length; i++) {
if (ranks[i].contains(v)) {
if (values[i] == null) {
values[i] = new TIntArrayList();
}
values[i].add(v);
}
}
}
} finally {
ite.dispose();
}
//We pick a random value in the first rank that is not empty (aka null here)
for (TIntArrayList rank : values) {
if (rank != null) {
int v = rnd.nextInt(rank.size());
return rank.get(v);
}
}
return -1;
} | java |
private int randomValue(IntVar x) {
int i = rnd.nextInt(x.getDomainSize());
DisposableValueIterator ite = x.getValueIterator(true);
int pos = -1;
try {
while (i >= 0) {
pos = ite.next();
i--;
}
} finally {
ite.dispose();
}
return pos;
} | java |
public static SAXRule runSequitur(String inputString) throws Exception {
LOGGER.trace("digesting the string " + inputString);
// clear global collections
//
SAXRule.numRules = new AtomicInteger(0);
SAXRule.theRules.clear();
SAXSymbol.theDigrams.clear();
SAXSymbol.theSubstituteTable.clear();
// init the top-level rule
//
SAXRule resRule = new SAXRule();
// tokenize the input string
//
StringTokenizer st = new StringTokenizer(inputString, " ");
// while there are tokens
int currentPosition = 0;
while (st.hasMoreTokens()) {
String token = st.nextToken();
// System.out.println(" processing the token " + token);
// extract next token
SAXTerminal symbol = new SAXTerminal(token, currentPosition);
// append to the end of the current sequitur string
// ... As each new input symbol is observed, append it to rule S....
resRule.last().insertAfter(symbol);
// once appended, check if the resulting digram is new or recurrent
//
// ... Each time a link is made between two symbols if the new digram is repeated elsewhere
// and the repetitions do not overlap, if the other occurrence is a complete rule,
// replace the new digram with the non-terminal symbol that heads the rule,
// otherwise,form a new rule and replace both digrams with the new non-terminal symbol
// otherwise, insert the digram into the index...
resRule.last().p.check();
currentPosition++;
// LOGGER.debug("Current grammar:\n" + SAXRule.getRules());
}
return resRule;
} | java |
public static GrammarRules series2SequiturRules(double[] timeseries, int saxWindowSize,
int saxPAASize, int saxAlphabetSize, NumerosityReductionStrategy numerosityReductionStrategy,
double normalizationThreshold) throws Exception, IOException {
LOGGER.debug("Discretizing time series...");
SAXRecords saxFrequencyData = sp.ts2saxViaWindow(timeseries, saxWindowSize, saxPAASize,
normalA.getCuts(saxAlphabetSize), numerosityReductionStrategy, normalizationThreshold);
LOGGER.debug("Inferring the grammar...");
// this is a string we are about to feed into Sequitur
//
String saxDisplayString = saxFrequencyData.getSAXString(" ");
// reset the Sequitur data structures
SAXRule.numRules = new AtomicInteger(0);
SAXRule.theRules.clear();
SAXSymbol.theDigrams.clear();
// bootstrap the grammar
SAXRule grammar = new SAXRule();
SAXRule.arrRuleRecords = new ArrayList<GrammarRuleRecord>();
// digest the string via the tokenizer and build the grammar
StringTokenizer st = new StringTokenizer(saxDisplayString, " ");
int currentPosition = 0;
while (st.hasMoreTokens()) {
grammar.last().insertAfter(new SAXTerminal(st.nextToken(), currentPosition));
grammar.last().p.check();
currentPosition++;
}
// bw.close();
LOGGER.debug("Collecting the grammar rules statistics and expanding the rules...");
GrammarRules rules = grammar.toGrammarRulesData();
LOGGER.debug("Mapping expanded rules to time-series intervals...");
SequiturFactory.updateRuleIntervals(rules, saxFrequencyData, true, timeseries, saxWindowSize,
saxPAASize);
return rules;
} | java |
public static ArrayList<RuleInterval> getRulePositionsByRuleNum(int ruleIdx, SAXRule grammar,
SAXRecords saxFrequencyData, double[] originalTimeSeries, int saxWindowSize) {
// this will be the result
ArrayList<RuleInterval> resultIntervals = new ArrayList<RuleInterval>();
// the rule container
GrammarRuleRecord ruleContainer = grammar.getRuleRecords().get(ruleIdx);
// the original indexes of all SAX words
ArrayList<Integer> saxWordsIndexes = new ArrayList<Integer>(saxFrequencyData.getAllIndices());
// debug printout
LOGGER.trace("Expanded rule: \"" + ruleContainer.getExpandedRuleString() + '\"');
LOGGER.trace("Indexes: " + ruleContainer.getOccurrences());
// array of all words of this expanded rule
String[] expandedRuleSplit = ruleContainer.getExpandedRuleString().trim().split(" ");
for (Integer currentIndex : ruleContainer.getOccurrences()) {
String extractedStr = "";
StringBuffer sb = new StringBuffer(expandedRuleSplit.length);
for (int i = 0; i < expandedRuleSplit.length; i++) {
LOGGER.trace("currentIndex " + currentIndex + ", i: " + i);
extractedStr = extractedStr.concat(" ").concat(String.valueOf(
saxFrequencyData.getByIndex(saxWordsIndexes.get(currentIndex + i)).getPayload()));
sb.append(saxWordsIndexes.get(currentIndex + i)).append(" ");
}
LOGGER.trace("Recovered string: " + extractedStr);
LOGGER.trace("Recovered positions: " + sb.toString());
int start = saxWordsIndexes.get(currentIndex);
int end = -1;
// need to care about bouncing beyond the all SAX words index array
if ((currentIndex + expandedRuleSplit.length) >= saxWordsIndexes.size()) {
// if we at the last index - then it's easy - end is the timeseries end
end = originalTimeSeries.length - 1;
}
else {
// if we OK with indexes, the Rule subsequence end is the start of the very next SAX word
// after the kast in this expanded rule
end = saxWordsIndexes.get(currentIndex + expandedRuleSplit.length) - 1 + saxWindowSize;
}
// save it
resultIntervals.add(new RuleInterval(start, end));
}
return resultIntervals;
} | java |
public static List<Preserve> newPreserve(Collection<VM> vms, String r, int q) {
return vms.stream().map(v -> new Preserve(v, r, q)).collect(Collectors.toList());
} | java |
private Node<E> _link(Node<E> node1, Node<E> node2) {
// maybe there is no real unification here
if(node1 == node2) return node2;
// from now on, we know that we unify really disjoint trees
if(node1.rank > node2.rank) {
node2.parent = node1;
node1.nbElems += node2.nbElems;
return node1;
}
else {
node1.parent = node2;
if (node1.rank == node2.rank) {
node2.rank++;
}
node2.nbElems += node1.nbElems;
return node2;
}
} | java |
public static void reset() {
SAXRule.numRules = new AtomicInteger(0);
SAXSymbol.theDigrams.clear();
SAXSymbol.theSubstituteTable.clear();
SAXRule.arrRuleRecords = new ArrayList<GrammarRuleRecord>();
} | java |
protected void assignLevel() {
int lvl = Integer.MAX_VALUE;
SAXSymbol sym;
for (sym = this.first(); (!sym.isGuard()); sym = sym.n) {
if (sym.isNonTerminal()) {
SAXRule referedTo = ((SAXNonTerminal) sym).r;
lvl = Math.min(referedTo.level + 1, lvl);
}
else {
level = 1;
return;
}
}
level = lvl;
} | java |
private static void expandRules() {
// long start = System.currentTimeMillis();
// iterate over all SAX containers
// ArrayList<SAXMapEntry<Integer, Integer>> recs = new ArrayList<SAXMapEntry<Integer, Integer>>(
// arrRuleRecords.size());
//
// for (GrammarRuleRecord ruleRecord : arrRuleRecords) {
// recs.add(new SAXMapEntry<Integer, Integer>(ruleRecord.getRuleLevel(), ruleRecord
// .getRuleNumber()));
// }
//
// Collections.sort(recs, new Comparator<SAXMapEntry<Integer, Integer>>() {
// @Override
// public int compare(SAXMapEntry<Integer, Integer> o1, SAXMapEntry<Integer, Integer> o2) {
// return o1.getKey().compareTo(o2.getKey());
// }
// });
// for (SAXMapEntry<Integer, Integer> entry : recs) {
for (GrammarRuleRecord ruleRecord : arrRuleRecords) {
if (ruleRecord.getRuleNumber() == 0) {
continue;
}
String curString = ruleRecord.getRuleString();
StringBuilder resultString = new StringBuilder(8192);
String[] split = curString.split(" ");
for (String s : split) {
if (s.startsWith("R")) {
resultString.append(" ").append(expandRule(Integer.valueOf(s.substring(1, s.length()))));
}
else {
resultString.append(" ").append(s);
}
}
// need to trim space at the very end
String rr = resultString.delete(0, 1).append(" ").toString();
ruleRecord.setExpandedRuleString(rr);
ruleRecord.setRuleYield(countSpaces(rr));
}
StringBuilder resultString = new StringBuilder(8192);
GrammarRuleRecord ruleRecord = arrRuleRecords.get(0);
resultString.append(ruleRecord.getRuleString());
int currentSearchStart = resultString.indexOf("R");
while (currentSearchStart >= 0) {
int spaceIdx = resultString.indexOf(" ", currentSearchStart);
String ruleName = resultString.substring(currentSearchStart, spaceIdx + 1);
Integer ruleId = Integer.valueOf(ruleName.substring(1, ruleName.length() - 1));
resultString.replace(spaceIdx - ruleName.length() + 1, spaceIdx + 1,
arrRuleRecords.get(ruleId).getExpandedRuleString());
currentSearchStart = resultString.indexOf("R");
}
ruleRecord.setExpandedRuleString(resultString.toString().trim());
// ruleRecord.setRuleYield(countSpaces(resultString));
// long end = System.currentTimeMillis();
// System.out.println("Rules expanded in " + SAXFactory.timeToString(start, end));
} | java |
private int[] getIndexes() {
int[] res = new int[this.indexes.size()];
int i = 0;
for (Integer idx : this.indexes) {
res[i] = idx;
i++;
}
return res;
} | java |
public Action fromJSON(JSONObject in) throws JSONConverterException {
String id = requiredString(in, ACTION_ID_LABEL);
Action a;
switch (id) {
case "bootVM":
a = bootVMFromJSON(in);
break;
case "shutdownVM":
a = shutdownVMFromJSON(in);
break;
case "shutdownNode":
a = shutdownNodeFromJSON(in);
break;
case "bootNode":
a = bootNodeFromJSON(in);
break;
case "forgeVM":
a = forgeVMFromJSON(in);
break;
case "killVM":
a = killVMFromJSON(in);
break;
case "migrateVM":
a = migrateVMFromJSON(in);
break;
case "resumeVM":
a = resumeVMFromJSON(in);
break;
case "suspendVM":
a = suspendVMFromJSON(in);
break;
case RC_ALLOCATE_LABEL:
a = allocateFromJSON(in);
break;
default:
throw new JSONConverterException("Unsupported action '" + id + "'");
}
attachEvents(a, in);
return a;
} | java |
private void attachEvents(Action a, JSONObject in) throws JSONConverterException {
if (in.containsKey(HOOK_LABEL)) {
JSONObject hooks = (JSONObject) in.get(HOOK_LABEL);
for (Map.Entry<String, Object> e : hooks.entrySet()) {
String k = e.getKey();
try {
Action.Hook h = Action.Hook.valueOf(k.toUpperCase());
for (Object o : (JSONArray) e.getValue()) {
a.addEvent(h, eventFromJSON((JSONObject) o));
}
} catch (IllegalArgumentException ex) {
throw new JSONConverterException("Unsupported hook type '" + k + "'", ex);
}
}
}
} | java |
private JSONObject makeActionSkeleton(Action a) {
JSONObject o = new JSONObject();
o.put(START_LABEL, a.getStart());
o.put(END_LABEL, a.getEnd());
JSONObject hooks = new JSONObject();
for (Action.Hook k : Action.Hook.values()) {
JSONArray arr = new JSONArray();
for (Event e : a.getEvents(k)) {
arr.add(toJSON(e));
}
hooks.put(k.toString(), arr);
}
o.put(HOOK_LABEL, hooks);
return o;
} | java |
public List<Action> listFromJSON(JSONArray in) throws JSONConverterException {
List<Action> l = new ArrayList<>(in.size());
for (Object o : in) {
if (!(o instanceof JSONObject)) {
throw new JSONConverterException("Expected an array of JSONObject but got an array of " + o.getClass().getName());
}
l.add(fromJSON((JSONObject) o));
}
return l;
} | java |
@Nonnull
static String decodeUTF16(@Nonnull final String mapcode) {
String result;
final StringBuilder asciiBuf = new StringBuilder();
for (final char ch : mapcode.toCharArray()) {
if (ch == '.') {
asciiBuf.append(ch);
} else if ((ch >= 1) && (ch <= 'z')) {
// normal ascii
asciiBuf.append(ch);
} else {
boolean found = false;
for (final Unicode2Ascii unicode2Ascii : UNICODE2ASCII) {
if ((ch >= unicode2Ascii.min) && (ch <= unicode2Ascii.max)) {
final int pos = ((int) ch) - (int) unicode2Ascii.min;
asciiBuf.append(unicode2Ascii.convert.charAt(pos));
found = true;
break;
}
}
if (!found) {
asciiBuf.append('?');
break;
}
}
}
result = asciiBuf.toString();
// Repack if this was a Greek 'alpha' code. This will have been converted to a regular 'A' after one iteration.
if (mapcode.startsWith(String.valueOf(GREEK_CAPITAL_ALPHA))) {
final String unpacked = aeuUnpack(result);
if (unpacked.isEmpty()) {
throw new AssertionError("decodeUTF16: cannot decode " + mapcode);
}
result = Encoder.aeuPack(unpacked, false);
}
if (isAbjadScript(mapcode)) {
return convertFromAbjad(result);
} else {
return result;
}
} | java |
private static int decodeBase31(@Nonnull final String code) {
int value = 0;
for (final char c : code.toCharArray()) {
if (c == '.') {
return value;
}
if (DECODE_CHARS[c] < 0) {
return -1;
}
value = (value * 31) + DECODE_CHARS[c];
}
return value;
} | java |
public boolean declareImmutable(String label, BtrpOperand t) {
if (isDeclared(label)) {
return false;
}
level.put(label, -1);
type.put(label, t);
return true;
} | java |
public boolean remove(String label) {
if (!isDeclared(label)) {
return false;
}
level.remove(label);
type.remove(label);
return true;
} | java |
public final boolean declare(String label, BtrpOperand t) {
if (isDeclared(label) && level.get(label) < 0) { //Disallow immutable value
return false;
}
if (!isDeclared(label)) {
level.put(label, currentLevel);
}
type.put(label, t);
return true;
} | java |
protected List<JSSourceFile> getJSSource(String mid, IResource resource, HttpServletRequest request, List<ICacheKeyGenerator> keyGens) throws IOException {
List<JSSourceFile> result = new ArrayList<JSSourceFile>(1);
InputStream in = resource.getInputStream();
JSSourceFile sf = JSSourceFile.fromInputStream(mid, in);
sf.setOriginalPath(resource.getURI().toString());
in.close();
result.add(sf);
return result;
} | java |
protected String moduleNameIdEncodingBeginLayer(HttpServletRequest request) {
StringBuffer sb = new StringBuffer();
if (request.getParameter(AbstractHttpTransport.SCRIPTS_REQPARAM) != null) {
// This is a request for a bootstrap layer with non-AMD script modules.
// Define the deps variable in global scope in case it's needed by
// the script modules.
sb.append("var " + EXPDEPS_VARNAME + ";"); //$NON-NLS-1$//$NON-NLS-2$
}
return sb.toString();
} | java |
protected String getTail() {
String tail = "";
if (this.offset < this.limit) {
tail = new String(this.buffer, this.offset, this.limit - this.offset + 1);
}
return tail;
} | java |
public String getOriginalString() {
if (this.string != null) {
this.string = new String(this.buffer, this.initialOffset, getLength());
}
return this.string;
} | java |
@Override
public boolean applyAction(Model m) {
Mapping map = m.getMapping();
return map.isRunning(vm) &&
map.getVMLocation(vm).equals(src) &&
map.addSleepingVM(vm, dst);
} | java |
public StaticRouting.NodesMap nodesMapFromJSON(Model mo, JSONObject o) throws JSONConverterException {
return new StaticRouting.NodesMap(requiredNode(mo, o, "src"), requiredNode(mo, o, "dst"));
} | java |
public static ConstraintSplitterMapper newBundle() {
ConstraintSplitterMapper mapper = new ConstraintSplitterMapper();
mapper.register(new AmongSplitter());
mapper.register(new BanSplitter());
mapper.register(new FenceSplitter());
mapper.register(new GatherSplitter());
mapper.register(new KilledSplitter());
mapper.register(new LonelySplitter());
mapper.register(new OfflineSplitter());
mapper.register(new OnlineSplitter());
mapper.register(new OverbookSplitter());
mapper.register(new PreserveSplitter());
mapper.register(new QuarantineSplitter());
mapper.register(new ReadySplitter());
mapper.register(new RootSplitter());
mapper.register(new RunningSplitter());
mapper.register(new SeqSplitter());
mapper.register(new SleepingSplitter());
mapper.register(new SplitSplitter());
mapper.register(new SpreadSplitter());
return mapper;
} | java |
public boolean register(ConstraintSplitter<? extends Constraint> ccb) {
return builders.put(ccb.getKey(), ccb) == null;
} | java |
protected void generateDefaultConstructor(SourceWriter sourceWriter, String simpleName) {
generateSourcePublicConstructorDeclaration(sourceWriter, simpleName);
sourceWriter.println("super();");
generateSourceCloseBlock(sourceWriter);
} | java |
protected final void generateSourcePublicMethodDeclaration(SourceWriter sourceWriter, JMethod method) {
StringBuilder arguments = new StringBuilder();
for (JParameter parameter : method.getParameters()) {
if (arguments.length() > 0) {
arguments.append(", ");
}
arguments.append(parameter.getType().getQualifiedSourceName());
arguments.append(" ");
arguments.append(parameter.getName());
}
generateSourcePublicMethodDeclaration(sourceWriter, method.getReturnType().getQualifiedSourceName(),
method.getName(), arguments.toString(), false);
} | java |
protected final void generateSourcePublicMethodDeclaration(SourceWriter sourceWriter, String returnType,
String methodName, String arguments, boolean override) {
if (override) {
sourceWriter.println("@Override");
}
sourceWriter.print("public ");
if (returnType != null) {
sourceWriter.print(returnType);
sourceWriter.print(" ");
}
sourceWriter.print(methodName);
sourceWriter.print("(");
sourceWriter.print(arguments);
sourceWriter.println(") {");
sourceWriter.indent();
} | java |
protected void notifyInit () {
final String sourceMethod = "notifyInit"; //$NON-NLS-1$
IServiceReference[] refs = null;
try {
if(_aggregator != null && _aggregator.getPlatformServices() != null){
refs = _aggregator.getPlatformServices().getServiceReferences(ICacheManagerListener.class.getName(),"(name=" + _aggregator.getName() + ")"); //$NON-NLS-1$ //$NON-NLS-2$
if (refs != null) {
for (IServiceReference ref : refs) {
ICacheManagerListener listener = (ICacheManagerListener)_aggregator.getPlatformServices().getService(ref);
if (listener != null) {
try {
listener.initialized(this);
} catch (Throwable t) {
if (log.isLoggable(Level.WARNING)) {
log.logp(Level.WARNING, CacheManagerImpl.class.getName(), sourceMethod, t.getMessage(), t);
}
} finally {
_aggregator.getPlatformServices().ungetService(ref);
}
}
}
}
}
} catch (PlatformServicesException e) {
if (log.isLoggable(Level.SEVERE)) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
} | java |
public int getStatus() {
int result = status;
if (status > 0) {
if (skip.getAndDecrement() <= 0) {
if (count.getAndDecrement() <= 0) {
result = status = -1;
}
} else {
result = 0;
}
}
return result;
} | java |
public static boolean deleteMMapGraph(String path) {
String directory = ensureDirectory(path);
File f = new File(directory);
boolean ok = true;
if (f.exists()) {
ok = new File(directory + "nodes.mmap").delete();
ok = new File(directory + "edges.mmap").delete() && ok;
ok = new File(directory + "treeMap.mmap").delete() && ok;
ok = f.delete() && ok;
}
return ok;
} | java |
public void mapConstraint(Class<? extends Constraint> c, Class<? extends ChocoConstraint> cc) {
constraints.put(c, cc);
} | java |
public void mapView(Class<? extends ModelView> c, Class<? extends ChocoView> cc) {
views.put(c, cc);
} | java |
public List<Link> getStaticRoute(NodesMap nm) {
Map<Link, Boolean> route = routes.get(nm);
if (route == null) {
return null;
}
return new ArrayList<>(route.keySet());
} | java |
public void setStaticRoute(NodesMap nm, Map<Link, Boolean> links) {
routes.put(nm, links); // Only one route between two nodes (replace the old route)
} | java |
private IntVar getMovingVM() {
//VMs that are moving
for (int i = move.nextSetBit(0); i >= 0; i = move.nextSetBit(i + 1)) {
if (starts[i] != null && !starts[i].isInstantiated() && oldPos[i] != hosts[i].getValue()) {
return starts[i];
}
}
return null;
} | java |
private IntVar getEarlyVar() {
IntVar earlyVar = null;
for (int i = stays.nextSetBit(0); i >= 0; i = stays.nextSetBit(i + 1)) {
if (starts[i] != null && !starts[i].isInstantiated()) {
if (earlyVar == null) {
earlyVar = starts[i];
} else {
if (earlyVar.getLB() > starts[i].getLB()) {
earlyVar = starts[i];
}
}
}
}
return earlyVar;
} | java |
private IntVar getVMtoLeafNode() {
for (int x = 0; x < outs.length; x++) {
if (outs[x].cardinality() == 0) {
//no outgoing VMs, can be launched directly.
BitSet in = ins[x];
for (int i = in.nextSetBit(0); i >= 0; i = in.nextSetBit(i + 1)) {
if (starts[i] != null && !starts[i].isInstantiated()) {
return starts[i];
}
}
}
}
return null;
} | java |
protected void initBytes(StringBuilder source) {
if (this.bytes == null) {
if (this.string != null) {
String encodingValue = getEncoding();
try {
this.bytes = this.string.getBytes(encodingValue);
} catch (UnsupportedEncodingException e) {
source.append(".encoding");
throw new NlsIllegalArgumentException(encodingValue, source.toString(), e);
}
} else if (this.hex != null) {
this.bytes = parseBytes(this.hex, "hex");
} else {
throw new XmlInvalidException(
new NlsParseException(XML_TAG, XML_ATTRIBUTE_HEX + "|" + XML_ATTRIBUTE_STRING, source.toString()));
}
}
} | java |
private void convertLink2Record(final Object iKey) {
if (status == MULTIVALUE_CONTENT_TYPE.ALL_RECORDS)
return;
final Object value;
if (iKey instanceof ORID)
value = iKey;
else
value = super.get(iKey);
if (value != null && value instanceof ORID) {
final ORID rid = (ORID) value;
marshalling = true;
try {
try {
// OVERWRITE IT
super.put(iKey, rid.getRecord());
} catch (ORecordNotFoundException e) {
// IGNORE THIS
}
} finally {
marshalling = false;
}
}
} | java |
public synchronized ODatabaseComplex<?> register(final ODatabaseComplex<?> db) {
instances.put(db, Thread.currentThread());
return db;
} | java |
public synchronized void unregister(final OStorage iStorage) {
for (ODatabaseComplex<?> db : new HashSet<ODatabaseComplex<?>>(instances.keySet())) {
if (db != null && db.getStorage() == iStorage) {
db.close();
instances.remove(db);
}
}
} | java |
public synchronized void shutdown() {
if (instances.size() > 0) {
OLogManager.instance().debug(null,
"Found %d databases opened during OrientDB shutdown. Assure to always close database instances after usage",
instances.size());
for (ODatabaseComplex<?> db : new HashSet<ODatabaseComplex<?>>(instances.keySet())) {
if (db != null && !db.isClosed()) {
db.close();
}
}
}
} | java |
public String digest2String(final String iInput, final boolean iIncludeAlgorithm) {
final StringBuilder buffer = new StringBuilder();
if (iIncludeAlgorithm)
buffer.append(ALGORITHM_PREFIX);
buffer.append(OSecurityManager.instance().digest2String(iInput));
return buffer.toString();
} | java |
private static Thread[] getThreads(ThreadGroup g) {
int mul = 1;
do {
Thread[] arr = new Thread[g.activeCount() * mul + 1];
if (g.enumerate(arr) < arr.length) {
return arr;
}
mul++;
} while (true);
} | java |
public int getThreadCount(ThreadGroup group, Status... s) {
Thread[] threads = getThreads(group);
int count = 0;
for (Thread t : threads) {
if (t instanceof MonitoredThread) {
Status status = getStatus((MonitoredThread) t);
if (status != null) {
for (Status x : s) {
if (x == status) {
count++;
}
}
}
}
}
return count;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.