code
stringlengths 73
34.1k
| label
stringclasses 1
value |
---|---|
public static int[] Concatenate(int[] array, int[] array2) {
int[] all = new int[array.length + array2.length];
int idx = 0;
//First array
for (int i = 0; i < array.length; i++)
all[idx++] = array[i];
//Second array
for (int i = 0; i < array2.length; i++)
all[idx++] = array2[i];
return all;
} | java |
public static int[] ConcatenateInt(List<int[]> arrays) {
int size = 0;
for (int i = 0; i < arrays.size(); i++) {
size += arrays.get(i).length;
}
int[] all = new int[size];
int idx = 0;
for (int i = 0; i < arrays.size(); i++) {
int[] v = arrays.get(i);
for (int j = 0; j < v.length; j++) {
all[idx++] = v[i];
}
}
return all;
} | java |
public static <T extends Number> int[] asArray(final T... array) {
int[] b = new int[array.length];
for (int i = 0; i < b.length; i++) {
b[i] = array[i].intValue();
}
return b;
} | java |
public static void Shuffle(double[] array, long seed) {
Random random = new Random();
if (seed != 0) random.setSeed(seed);
for (int i = array.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
double temp = array[index];
array[index] = array[i];
array[i] = temp;
}
} | java |
public static float[] toFloat(int[] array) {
float[] n = new float[array.length];
for (int i = 0; i < array.length; i++) {
n[i] = (float) array[i];
}
return n;
} | java |
public static float[][] toFloat(int[][] array) {
float[][] n = new float[array.length][array[0].length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
n[i][j] = (float) array[i][j];
}
}
return n;
} | java |
public static int[] toInt(double[] array) {
int[] n = new int[array.length];
for (int i = 0; i < array.length; i++) {
n[i] = (int) array[i];
}
return n;
} | java |
public static int[][] toInt(double[][] array) {
int[][] n = new int[array.length][array[0].length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
n[i][j] = (int) array[i][j];
}
}
return n;
} | java |
public static double[] toDouble(int[] array) {
double[] n = new double[array.length];
for (int i = 0; i < array.length; i++) {
n[i] = (double) array[i];
}
return n;
} | java |
public static double[][] toDouble(int[][] array) {
double[][] n = new double[array.length][array[0].length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[0].length; j++) {
n[i][j] = (double) array[i][j];
}
}
return n;
} | java |
public ApiResponse<TokenInfoSuccessResponse> tokenInfoWithHttpInfo() throws ApiException {
com.squareup.okhttp.Call call = tokenInfoValidateBeforeCall(null, null);
Type localVarReturnType = new TypeToken<TokenInfoSuccessResponse>(){}.getType();
return apiClient.execute(call, localVarReturnType);
} | java |
public static double HighAccuracyFunction(double x) {
if (x < -8 || x > 8)
return 0;
double sum = x;
double term = 0;
double nextTerm = x;
double pwr = x * x;
double i = 1;
// Iterate until adding next terms doesn't produce
// any change within the current numerical accuracy.
while (sum != term) {
term = sum;
// Next term
nextTerm *= pwr / (i += 2);
sum += nextTerm;
}
return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI);
} | java |
public static double HighAccuracyComplemented(double x) {
double[] R =
{
1.25331413731550025, 0.421369229288054473, 0.236652382913560671,
0.162377660896867462, 0.123131963257932296, 0.0990285964717319214,
0.0827662865013691773, 0.0710695805388521071, 0.0622586659950261958
};
int j = (int) (0.5 * (Math.abs(x) + 1));
double a = R[j];
double z = 2 * j;
double b = a * z - 1;
double h = Math.abs(x) - z;
double q = h * h;
double pwr = 1;
double sum = a + h * b;
double term = a;
for (int i = 2; sum != term; i += 2) {
term = sum;
a = (a + z * b) / (i);
b = (b + z * a) / (i + 1);
pwr *= q;
sum = term + pwr * (a + h * b);
}
sum *= Math.exp(-0.5 * (x * x) - 0.5 * Constants.Log2PI);
return (x >= 0) ? sum : (1.0 - sum);
} | java |
public String toIPTC(SubjectReferenceSystem srs) {
StringBuffer b = new StringBuffer();
b.append("IPTC:");
b.append(getNumber());
b.append(":");
if (getNumber().endsWith("000000")) {
b.append(toIPTCHelper(srs.getName(this)));
b.append("::");
} else if (getNumber().endsWith("000")) {
b.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + "000000"))));
b.append(":");
b.append(toIPTCHelper(srs.getName(this)));
b.append(":");
} else {
b.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 2) + "000000"))));
b.append(":");
b.append(toIPTCHelper(srs.getName(srs.get(getNumber().substring(0, 5) + "000"))));
b.append(":");
b.append(toIPTCHelper(srs.getName(this)));
}
return b.toString();
} | java |
public DataSetInfo create(int dataSet) throws InvalidDataSetException {
DataSetInfo info = dataSets.get(createKey(dataSet));
if (info == null) {
int recordNumber = (dataSet >> 8) & 0xFF;
int dataSetNumber = dataSet & 0xFF;
throw new UnsupportedDataSetException(recordNumber + ":" + dataSetNumber);
// info = super.create(dataSet);
}
return info;
} | java |
public double Function1D(double x) {
double frequency = initFrequency;
double amplitude = initAmplitude;
double sum = 0;
// octaves
for (int i = 0; i < octaves; i++) {
sum += SmoothedNoise(x * frequency) * amplitude;
frequency *= 2;
amplitude *= persistence;
}
return sum;
} | java |
public double Function2D(double x, double y) {
double frequency = initFrequency;
double amplitude = initAmplitude;
double sum = 0;
// octaves
for (int i = 0; i < octaves; i++) {
sum += SmoothedNoise(x * frequency, y * frequency) * amplitude;
frequency *= 2;
amplitude *= persistence;
}
return sum;
} | java |
private double Noise(int x, int y) {
int n = x + y * 57;
n = (n << 13) ^ n;
return (1.0 - ((n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0);
} | java |
private double CosineInterpolate(double x1, double x2, double a) {
double f = (1 - Math.cos(a * Math.PI)) * 0.5;
return x1 * (1 - f) + x2 * f;
} | java |
public List<FailedEventInvocation> getFailedInvocations() {
synchronized (this.mutex) {
if (this.failedEvents == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(this.failedEvents);
}
} | java |
public Set<Class<?>> getPrevented() {
if (this.prevent == null) {
return Collections.emptySet();
}
return Collections.unmodifiableSet(this.prevent);
} | java |
public static double Function1D(double x, double mean, double amplitude, double position, double width, double phase, double frequency) {
double envelope = mean + amplitude * Math.exp(-Math.pow((x - position), 2) / Math.pow((2 * width), 2));
double carry = Math.cos(2 * Math.PI * frequency * (x - position) + phase);
return envelope * carry;
} | java |
public static ComplexNumber Function2D(int x, int y, double wavelength, double orientation, double phaseOffset, double gaussVariance, double aspectRatio) {
double X = x * Math.cos(orientation) + y * Math.sin(orientation);
double Y = -x * Math.sin(orientation) + y * Math.cos(orientation);
double envelope = Math.exp(-((X * X + aspectRatio * aspectRatio * Y * Y) / (2 * gaussVariance * gaussVariance)));
double real = Math.cos(2 * Math.PI * (X / wavelength) + phaseOffset);
double imaginary = Math.sin(2 * Math.PI * (X / wavelength) + phaseOffset);
return new ComplexNumber(envelope * real, envelope * imaginary);
} | java |
public Long getOldestTaskCreatedTime(){
Timer.Context ctx = getOldestTaskTimeTimer.time();
try {
long oldest = Long.MAX_VALUE;
/*
* I am asking this question first, because if I ask it after I could
* miss the oldest time if the oldest is polled and worked on
*/
Long oldestQueueTime = this.taskQueue.getOldestQueueTime();
if(oldestQueueTime != null)
oldest = oldestQueueTime;
//there is a tiny race condition here... but we just want to make our best attempt
long inProgressOldestTime = tasksInProgressTracker.getOldestTime();
if(inProgressOldestTime < oldest)
oldest = inProgressOldestTime;
return oldest;
} finally {
ctx.stop();
}
} | java |
@SuppressWarnings({ "unchecked", "rawtypes" })
public List<HazeltaskTask<G>> shutdownNow() {
return (List<HazeltaskTask<G>>) (List) localExecutorPool.shutdownNow();
} | java |
public void registerCollectionSizeGauge(
CollectionSizeGauge collectionSizeGauge) {
String name = createMetricName(LocalTaskExecutorService.class,
"queue-size");
metrics.register(name, collectionSizeGauge);
} | java |
public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {
if(!groupClass.isEnum()) {
throw new IllegalArgumentException("The group class "+groupClass+" is not an enum");
}
groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());
return this;
} | java |
public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() {
return new ExecutorConfig<GROUP>()
.withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>());
} | java |
public Collection<HazeltaskTask<GROUP>> call() throws Exception {
try {
if(isShutdownNow)
return this.getDistributedExecutorService().shutdownNowWithHazeltask();
else
this.getDistributedExecutorService().shutdown();
} catch(IllegalStateException e) {}
return Collections.emptyList();
} | java |
public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {
return executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);
} | java |
public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable, long maxWaitTime, TimeUnit unit) {
Collection<MemberResponse<T>> result = new ArrayList<MemberResponse<T>>(members.size());
Map<Member, Future<T>> resultFutures = execSvc.submitToMembers(callable, members);
for(Entry<Member, Future<T>> futureEntry : resultFutures.entrySet()) {
Future<T> future = futureEntry.getValue();
Member member = futureEntry.getKey();
try {
if(maxWaitTime > 0) {
result.add(new MemberResponse<T>(member, future.get(maxWaitTime, unit)));
} else {
result.add(new MemberResponse<T>(member, future.get()));
}
//ignore exceptions... return what you can
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); //restore interrupted status and return what we have
return result;
} catch (MemberLeftException e) {
log.warn("Member {} left while trying to get a distributed callable result", member);
} catch (ExecutionException e) {
if(e.getCause() instanceof InterruptedException) {
//restore interrupted state and return
Thread.currentThread().interrupt();
return result;
} else {
log.warn("Unable to execute callable on "+member+". There was an error.", e);
}
} catch (TimeoutException e) {
log.error("Unable to execute task on "+member+" within 10 seconds.");
} catch (RuntimeException e) {
log.error("Unable to execute task on "+member+". An unexpected error occurred.", e);
}
}
return result;
} | java |
@SuppressWarnings("unchecked")
public <T> DistributedFuture<GROUP, T> createFuture(HazeltaskTask<GROUP> task) {
DistributedFuture<GROUP, T> future = new DistributedFuture<GROUP, T>(topologyService, task.getGroup(), task.getId());
this.futures.put(task.getId(), (DistributedFuture<GROUP, Serializable>) future);
return future;
} | java |
public void errorFuture(UUID taskId, Exception e) {
DistributedFuture<GROUP, Serializable> future = remove(taskId);
if(future != null) {
future.setException(e);
}
} | java |
public void schedule(BackoffTask task, long initialDelay, long fixedDelay) {
synchronized (queue) {
start();
queue.put(new DelayedTimerTask(task, initialDelay, fixedDelay));
}
} | java |
public Future<HazeltaskTask<GROUP>> addPendingTaskAsync(HazeltaskTask<GROUP> task) {
return pendingTask.putAsync(task.getId(), task);
} | java |
public void applyXMLDSigAsFirstChild (@Nonnull final PrivateKey aPrivateKey,
@Nonnull final X509Certificate aCertificate,
@Nonnull final Document aDocument) throws Exception
{
ValueEnforcer.notNull (aPrivateKey, "privateKey");
ValueEnforcer.notNull (aCertificate, "certificate");
ValueEnforcer.notNull (aDocument, "document");
ValueEnforcer.notNull (aDocument.getDocumentElement (), "Document is missing a document element");
if (aDocument.getDocumentElement ().getChildNodes ().getLength () == 0)
throw new IllegalArgumentException ("Document element has no children!");
// Check that the document does not contain another Signature element
final NodeList aNodeList = aDocument.getElementsByTagNameNS (XMLSignature.XMLNS, XMLDSigSetup.ELEMENT_SIGNATURE);
if (aNodeList.getLength () > 0)
throw new IllegalArgumentException ("Document already contains an XMLDSig Signature element!");
// Create the XMLSignature, but don't sign it yet.
final XMLSignature aXMLSignature = createXMLSignature (aCertificate);
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
// -> The signature is always the first child element of the document
// element for ebInterface
final DOMSignContext aDOMSignContext = new DOMSignContext (aPrivateKey,
aDocument.getDocumentElement (),
aDocument.getDocumentElement ().getFirstChild ());
// The namespace prefix to be used for the signed XML
aDOMSignContext.setDefaultNamespacePrefix (DEFAULT_NS_PREFIX);
// Marshal, generate, and sign the enveloped signature.
aXMLSignature.sign (aDOMSignContext);
} | java |
public static <K> Map<K, Integer> rankMapOnIntegerValue(Map<K, Integer> inputMap) {
Map<K, Integer> newMap = new TreeMap<K, Integer>(new IntegerValueComparator(inputMap));
newMap.putAll(inputMap);
Map<K, Integer> linkedMap = new LinkedHashMap<K, Integer>(newMap);
return linkedMap;
} | java |
private void handleIncomingMessage(SerialMessage incomingMessage) {
logger.debug("Incoming message to process");
logger.debug(incomingMessage.toString());
switch (incomingMessage.getMessageType()) {
case Request:
handleIncomingRequestMessage(incomingMessage);
break;
case Response:
handleIncomingResponseMessage(incomingMessage);
break;
default:
logger.warn("Unsupported incomingMessageType: 0x%02X", incomingMessage.getMessageType());
}
} | java |
private void handleIncomingRequestMessage(SerialMessage incomingMessage) {
logger.debug("Message type = REQUEST");
switch (incomingMessage.getMessageClass()) {
case ApplicationCommandHandler:
handleApplicationCommandRequest(incomingMessage);
break;
case SendData:
handleSendDataRequest(incomingMessage);
break;
case ApplicationUpdate:
handleApplicationUpdateRequest(incomingMessage);
break;
default:
logger.warn(String.format("TODO: Implement processing of Request Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(),
incomingMessage.getMessageClass().getKey()));
break;
}
} | java |
private void handleApplicationCommandRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Application Command Request");
int nodeId = incomingMessage.getMessagePayloadByte(1);
logger.debug("Application Command Request from Node " + nodeId);
ZWaveNode node = getNode(nodeId);
if (node == null) {
logger.warn("Node {} not initialized yet, ignoring message.", nodeId);
return;
}
node.resetResendCount();
int commandClassCode = incomingMessage.getMessagePayloadByte(3);
ZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Incoming command class %s (0x%02x)", commandClass.getLabel(), commandClass.getKey()));
ZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);
// We got an unsupported command class, return.
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
logger.trace("Found Command Class {}, passing to handleApplicationCommandRequest", zwaveCommandClass.getCommandClass().getLabel());
zwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
} | java |
private void handleSendDataRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Send Data Request");
int callbackId = incomingMessage.getMessagePayloadByte(0);
TransmissionState status = TransmissionState.getTransmissionState(incomingMessage.getMessagePayloadByte(1));
SerialMessage originalMessage = this.lastSentMessage;
if (status == null) {
logger.warn("Transmission state not found, ignoring.");
return;
}
logger.debug("CallBack ID = {}", callbackId);
logger.debug(String.format("Status = %s (0x%02x)", status.getLabel(), status.getKey()));
if (originalMessage == null || originalMessage.getCallbackId() != callbackId) {
logger.warn("Already processed another send data request for this callback Id, ignoring.");
return;
}
switch (status) {
case COMPLETE_OK:
ZWaveNode node = this.getNode(originalMessage.getMessageNode());
node.resetResendCount();
// in case we received a ping response and the node is alive, we proceed with the next node stage for this node.
if (node != null && node.getNodeStage() == NodeStage.NODEBUILDINFO_PING) {
node.advanceNodeStage();
}
if (incomingMessage.getMessageClass() == originalMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
return;
case COMPLETE_NO_ACK:
case COMPLETE_FAIL:
case COMPLETE_NOT_IDLE:
case COMPLETE_NOROUTE:
try {
handleFailedSendDataRequest(originalMessage);
} finally {
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
default:
}
} | java |
private void handleFailedSendDataRequest(SerialMessage originalMessage) {
ZWaveNode node = this.getNode(originalMessage.getMessageNode());
if (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD)
return;
if (!node.isListening() && originalMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);
if (wakeUpCommandClass != null) {
wakeUpCommandClass.setAwake(false);
wakeUpCommandClass.putInWakeUpQueue(originalMessage); //it's a battery operated device, place in wake-up queue.
return;
}
} else if (!node.isListening() && originalMessage.getPriority() == SerialMessage.SerialMessagePriority.Low)
return;
node.incrementResendCount();
logger.error("Got an error while sending data to node {}. Resending message.", node.getNodeId());
this.sendData(originalMessage);
} | java |
private void handleApplicationUpdateRequest(SerialMessage incomingMessage) {
logger.trace("Handle Message Application Update Request");
int nodeId = incomingMessage.getMessagePayloadByte(1);
logger.trace("Application Update Request from Node " + nodeId);
UpdateState updateState = UpdateState.getUpdateState(incomingMessage.getMessagePayloadByte(0));
switch (updateState) {
case NODE_INFO_RECEIVED:
logger.debug("Application update request, node information received.");
int length = incomingMessage.getMessagePayloadByte(2);
ZWaveNode node = getNode(nodeId);
node.resetResendCount();
for (int i = 6; i < length + 3; i++) {
int data = incomingMessage.getMessagePayloadByte(i);
if(data == 0xef ) {
// TODO: Implement control command classes
break;
}
logger.debug(String.format("Adding command class 0x%02X to the list of supported command classes.", data));
ZWaveCommandClass commandClass = ZWaveCommandClass.getInstance(data, node, this);
if (commandClass != null)
node.addCommandClass(commandClass);
}
// advance node stage.
node.advanceNodeStage();
if (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && !incomingMessage.isTransActionCanceled()) {
notifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
break;
case NODE_INFO_REQ_FAILED:
logger.debug("Application update request, Node Info Request Failed, re-request node info.");
SerialMessage requestInfoMessage = this.lastSentMessage;
if (requestInfoMessage.getMessageClass() != SerialMessage.SerialMessageClass.RequestNodeInfo) {
logger.warn("Got application update request without node info request, ignoring.");
return;
}
if (--requestInfoMessage.attempts >= 0) {
logger.error("Got Node Info Request Failed while sending this serial message. Requeueing");
this.enqueue(requestInfoMessage);
} else
{
logger.warn("Node Info Request Failed 3x. Discarding message: {}", lastSentMessage.toString());
}
transactionCompleted.release();
break;
default:
logger.warn(String.format("TODO: Implement Application Update Request Handling of %s (0x%02X).", updateState.getLabel(), updateState.getKey()));
}
} | java |
private void handleGetVersionResponse(SerialMessage incomingMessage) {
this.ZWaveLibraryType = incomingMessage.getMessagePayloadByte(12);
this.zWaveVersion = new String(ArrayUtils.subarray(incomingMessage.getMessagePayload(), 0, 11));
logger.debug(String.format("Got MessageGetVersion response. Version = %s, Library Type = 0x%02X", zWaveVersion, ZWaveLibraryType));
} | java |
private void handleSerialApiGetInitDataResponse(
SerialMessage incomingMessage) {
logger.debug(String.format("Got MessageSerialApiGetInitData response."));
this.isConnected = true;
int nodeBytes = incomingMessage.getMessagePayloadByte(2);
if (nodeBytes != NODE_BYTES) {
logger.error("Invalid number of node bytes = {}", nodeBytes);
return;
}
int nodeId = 1;
// loop bytes
for (int i = 3;i < 3 + nodeBytes;i++) {
int incomingByte = incomingMessage.getMessagePayloadByte(i);
// loop bits in byte
for (int j=0;j<8;j++) {
int b1 = incomingByte & (int)Math.pow(2.0D, j);
int b2 = (int)Math.pow(2.0D, j);
if (b1 == b2) {
logger.info(String.format("Found node id = %d", nodeId));
// Place nodes in the local ZWave Controller
this.zwaveNodes.put(nodeId, new ZWaveNode(this.homeId, nodeId, this));
this.getNode(nodeId).advanceNodeStage();
}
nodeId++;
}
}
logger.info("------------Number of Nodes Found Registered to ZWave Controller------------");
logger.info(String.format("# Nodes = %d", this.zwaveNodes.size()));
logger.info("----------------------------------------------------------------------------");
// Advance node stage for the first node.
} | java |
private void handleMemoryGetId(SerialMessage incomingMessage) {
this.homeId = ((incomingMessage.getMessagePayloadByte(0)) << 24) |
((incomingMessage.getMessagePayloadByte(1)) << 16) |
((incomingMessage.getMessagePayloadByte(2)) << 8) |
(incomingMessage.getMessagePayloadByte(3));
this.ownNodeId = incomingMessage.getMessagePayloadByte(4);
logger.debug(String.format("Got MessageMemoryGetId response. Home id = 0x%08X, Controller Node id = %d", this.homeId, this.ownNodeId));
} | java |
private void handleSerialAPIGetCapabilitiesResponse(SerialMessage incomingMessage) {
logger.trace("Handle Message Serial API Get Capabilities");
this.serialAPIVersion = String.format("%d.%d", incomingMessage.getMessagePayloadByte(0), incomingMessage.getMessagePayloadByte(1));
this.manufactureId = ((incomingMessage.getMessagePayloadByte(2)) << 8) | (incomingMessage.getMessagePayloadByte(3));
this.deviceType = ((incomingMessage.getMessagePayloadByte(4)) << 8) | (incomingMessage.getMessagePayloadByte(5));
this.deviceId = (((incomingMessage.getMessagePayloadByte(6)) << 8) | (incomingMessage.getMessagePayloadByte(7)));
logger.debug(String.format("API Version = %s", this.getSerialAPIVersion()));
logger.debug(String.format("Manufacture ID = 0x%x", this.getManufactureId()));
logger.debug(String.format("Device Type = 0x%x", this.getDeviceType()));
logger.debug(String.format("Device ID = 0x%x", this.getDeviceId()));
// Ready to get information on Serial API
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessagePriority.High));
} | java |
private void handleSendDataResponse(SerialMessage incomingMessage) {
logger.trace("Handle Message Send Data Response");
if(incomingMessage.getMessageBuffer()[2] != 0x00)
logger.debug("Sent Data successfully placed on stack.");
else
logger.error("Sent Data was not placed on stack due to error.");
} | java |
private void handleRequestNodeInfoResponse(SerialMessage incomingMessage) {
logger.trace("Handle RequestNodeInfo Response");
if(incomingMessage.getMessageBuffer()[2] != 0x00)
logger.debug("Request node info successfully placed on stack.");
else
logger.error("Request node info not placed on stack due to error.");
} | java |
public void connect(final String serialPortName)
throws SerialInterfaceException {
logger.info("Connecting to serial port {}", serialPortName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open("org.openhab.binding.zwave",2000);
this.serialPort = (SerialPort) commPort;
this.serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
this.serialPort.enableReceiveThreshold(1);
this.serialPort.enableReceiveTimeout(ZWAVE_RECEIVE_TIMEOUT);
this.receiveThread = new ZWaveReceiveThread();
this.receiveThread.start();
this.sendThread = new ZWaveSendThread();
this.sendThread.start();
logger.info("Serial port is initialized");
} catch (NoSuchPortException e) {
logger.error(e.getLocalizedMessage());
throw new SerialInterfaceException(e.getLocalizedMessage(), e);
} catch (PortInUseException e) {
logger.error(e.getLocalizedMessage());
throw new SerialInterfaceException(e.getLocalizedMessage(), e);
} catch (UnsupportedCommOperationException e) {
logger.error(e.getLocalizedMessage());
throw new SerialInterfaceException(e.getLocalizedMessage(), e);
}
} | java |
public void close() {
if (watchdog != null) {
watchdog.cancel();
watchdog = null;
}
disconnect();
// clear nodes collection and send queue
for (Object listener : this.zwaveEventListeners.toArray()) {
if (!(listener instanceof ZWaveNode))
continue;
this.zwaveEventListeners.remove(listener);
}
this.zwaveNodes.clear();
this.sendQueue.clear();
logger.info("Stopped Z-Wave controller");
} | java |
public void disconnect() {
if (sendThread != null) {
sendThread.interrupt();
try {
sendThread.join();
} catch (InterruptedException e) {
}
sendThread = null;
}
if (receiveThread != null) {
receiveThread.interrupt();
try {
receiveThread.join();
} catch (InterruptedException e) {
}
receiveThread = null;
}
if(transactionCompleted.availablePermits() < 0)
transactionCompleted.release(transactionCompleted.availablePermits());
transactionCompleted.drainPermits();
logger.trace("Transaction completed permit count -> {}", transactionCompleted.availablePermits());
if (this.serialPort != null) {
this.serialPort.close();
this.serialPort = null;
}
logger.info("Disconnected from serial port");
} | java |
public void enqueue(SerialMessage serialMessage) {
this.sendQueue.add(serialMessage);
logger.debug("Enqueueing message. Queue length = {}", this.sendQueue.size());
} | java |
public void notifyEventListeners(ZWaveEvent event) {
logger.debug("Notifying event listeners");
for (ZWaveEventListener listener : this.zwaveEventListeners) {
logger.trace("Notifying {}", listener.toString());
listener.ZWaveIncomingEvent(event);
}
} | java |
public void initialize() {
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));
this.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));
} | java |
public void identifyNode(int nodeId) throws SerialInterfaceException {
SerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.IdentifyNode, SerialMessage.SerialMessagePriority.High);
byte[] newPayload = { (byte) nodeId };
newMessage.setMessagePayload(newPayload);
this.enqueue(newMessage);
} | java |
public void requestNodeInfo(int nodeId) {
SerialMessage newMessage = new SerialMessage(nodeId, SerialMessage.SerialMessageClass.RequestNodeInfo, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationUpdate, SerialMessage.SerialMessagePriority.High);
byte[] newPayload = { (byte) nodeId };
newMessage.setMessagePayload(newPayload);
this.enqueue(newMessage);
} | java |
public void sendData(SerialMessage serialMessage)
{
if (serialMessage.getMessageClass() != SerialMessage.SerialMessageClass.SendData) {
logger.error(String.format("Invalid message class %s (0x%02X) for sendData", serialMessage.getMessageClass().getLabel(), serialMessage.getMessageClass().getKey()));
return;
}
if (serialMessage.getMessageType() != SerialMessage.SerialMessageType.Request) {
logger.error("Only request messages can be sent");
return;
}
ZWaveNode node = this.getNode(serialMessage.getMessageNode());
if (node.getNodeStage() == NodeStage.NODEBUILDINFO_DEAD) {
logger.debug("Node {} is dead, not sending message.", node.getNodeId());
return;
}
if (!node.isListening() && serialMessage.getPriority() != SerialMessage.SerialMessagePriority.Low) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass)node.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);
if (wakeUpCommandClass != null && !wakeUpCommandClass.isAwake()) {
wakeUpCommandClass.putInWakeUpQueue(serialMessage); //it's a battery operated device, place in wake-up queue.
return;
}
}
serialMessage.setTransmitOptions(TRANSMIT_OPTION_ACK | TRANSMIT_OPTION_AUTO_ROUTE | TRANSMIT_OPTION_EXPLORE);
if (++sentDataPointer > 0xFF)
sentDataPointer = 1;
serialMessage.setCallbackId(sentDataPointer);
logger.debug("Callback ID = {}", sentDataPointer);
this.enqueue(serialMessage);
} | java |
public void sendValue(int nodeId, int endpoint, int value) {
ZWaveNode node = this.getNode(nodeId);
ZWaveSetCommands zwaveCommandClass = null;
SerialMessage serialMessage = null;
for (ZWaveCommandClass.CommandClass commandClass : new ZWaveCommandClass.CommandClass[] { ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL, ZWaveCommandClass.CommandClass.SWITCH_BINARY, ZWaveCommandClass.CommandClass.BASIC }) {
zwaveCommandClass = (ZWaveSetCommands)node.resolveCommandClass(commandClass, endpoint);
if (zwaveCommandClass != null)
break;
}
if (zwaveCommandClass == null) {
logger.error("No Command Class found on node {}, instance/endpoint {} to request level.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveCommandClass.setValueMessage(value), (ZWaveCommandClass)zwaveCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
// read back level on "ON" command
if (((ZWaveCommandClass)zwaveCommandClass).getCommandClass() == ZWaveCommandClass.CommandClass.SWITCH_MULTILEVEL && value == 255)
this.requestValue(nodeId, endpoint);
} | java |
private void processProperties() {
state = true;
try {
importerServiceFilter = getFilter(importerServiceFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_IMPORTERSERVICE_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
try {
importDeclarationFilter = getFilter(importDeclarationFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_IMPORTDECLARATION_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
} | java |
@Modified(id = "importerServices")
void modifiedImporterService(ServiceReference<ImporterService> serviceReference) {
try {
importersManager.modified(serviceReference);
} catch (InvalidFilterException invalidFilterException) {
LOG.error("The ServiceProperty \"" + TARGET_FILTER_PROPERTY + "\" of the ImporterService "
+ bundleContext.getService(serviceReference) + " doesn't provides a valid Filter."
+ " To be used, it must provides a correct \"" + TARGET_FILTER_PROPERTY + "\" ServiceProperty.",
invalidFilterException
);
importersManager.removeLinks(serviceReference);
return;
}
if (importersManager.matched(serviceReference)) {
importersManager.updateLinks(serviceReference);
} else {
importersManager.removeLinks(serviceReference);
}
} | java |
private void unregisterAllServlets() {
for (String endpoint : registeredServlets) {
registeredServlets.remove(endpoint);
web.unregister(endpoint);
LOG.info("endpoint {} unregistered", endpoint);
}
} | java |
public double[] calculateDrift(ArrayList<T> tracks){
double[] result = new double[3];
double sumX =0;
double sumY = 0;
double sumZ = 0;
int N=0;
for(int i = 0; i < tracks.size(); i++){
T t = tracks.get(i);
TrajectoryValidIndexTimelagIterator it = new TrajectoryValidIndexTimelagIterator(t,1);
//for(int j = 1; j < t.size(); j++){
while(it.hasNext()) {
int j = it.next();
sumX += t.get(j+1).x - t.get(j).x;
sumY += t.get(j+1).y - t.get(j).y;
sumZ += t.get(j+1).z - t.get(j).z;
N++;
}
}
result[0] = sumX/N;
result[1] = sumY/N;
result[2] = sumZ/N;
return result;
} | java |
public void addCommandClass(ZWaveCommandClass commandClass) {
ZWaveCommandClass.CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
supportedCommandClasses.put(key, commandClass);
}
} | java |
public boolean canBeLinked(D declaration, ServiceReference<S> declarationBinderRef) {
// Evaluate the target filter of the ImporterService on the Declaration
Filter filter = bindersManager.getTargetFilter(declarationBinderRef);
return filter.matches(declaration.getMetadata());
} | java |
public boolean link(D declaration, ServiceReference<S> declarationBinderRef) {
S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);
LOG.debug(declaration + " match the filter of " + declarationBinder + " : bind them together");
declaration.bind(declarationBinderRef);
try {
declarationBinder.addDeclaration(declaration);
} catch (Exception e) {
declaration.unbind(declarationBinderRef);
LOG.debug(declarationBinder + " throw an exception when giving to it the Declaration "
+ declaration, e);
return false;
}
return true;
} | java |
public boolean unlink(D declaration, ServiceReference<S> declarationBinderRef) {
S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);
try {
declarationBinder.removeDeclaration(declaration);
} catch (BinderException e) {
LOG.debug(declarationBinder + " throw an exception when removing of it the Declaration "
+ declaration, e);
declaration.unhandle(declarationBinderRef);
return false;
} finally {
declaration.unbind(declarationBinderRef);
}
return true;
} | java |
private static String removeLastDot(final String pkgName) {
return pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;
} | java |
@Nonnull
private static Properties findDefaultProperties() {
final InputStream in = SourceCodeFormatter.class.getClassLoader().getResourceAsStream(DEFAULT_PROPERTIES_PATH);
final Properties p = new Properties();
try {
p.load(in);
} catch (final IOException e) {
throw new RuntimeException(String.format("Can not load resource %s", DEFAULT_PROPERTIES_PATH));
}
return p;
} | java |
public static String format(final String code, final Properties options, final LineEnding lineEnding) {
Check.notEmpty(code, "code");
Check.notEmpty(options, "options");
Check.notNull(lineEnding, "lineEnding");
final CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
final String lineSeparator = LineEnding.find(lineEnding, code);
TextEdit te = null;
try {
te = formatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, lineSeparator);
} catch (final Exception formatFailed) {
LOG.warn("Formatting failed", formatFailed);
}
String formattedCode = code;
if (te == null) {
LOG.info("Code cannot be formatted. Possible cause is unmatched source/target/compliance version.");
} else {
final IDocument doc = new Document(code);
try {
te.apply(doc);
} catch (final Exception e) {
LOG.warn(e.getLocalizedMessage(), e);
}
formattedCode = doc.get();
}
return formattedCode;
} | java |
private void processProperties() {
state = true;
try {
exporterServiceFilter = getFilter(exporterServiceFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_EXPORTERSERVICE_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
try {
exportDeclarationFilter = getFilter(exportDeclarationFilterProperty);
} catch (InvalidFilterException invalidFilterException) {
LOG.debug("The value of the Property " + FILTER_EXPORTDECLARATION_PROPERTY + " is invalid,"
+ " the recuperation of the Filter has failed. The instance gonna stop.", invalidFilterException);
state = false;
return;
}
} | java |
@Modified(id = "exporterServices")
void modifiedExporterService(ServiceReference<ExporterService> serviceReference) {
try {
exportersManager.modified(serviceReference);
} catch (InvalidFilterException invalidFilterException) {
LOG.error("The ServiceProperty \"" + TARGET_FILTER_PROPERTY + "\" of the ExporterService "
+ bundleContext.getService(serviceReference) + " doesn't provides a valid Filter."
+ " To be used, it must provides a correct \"" + TARGET_FILTER_PROPERTY + "\" ServiceProperty.",
invalidFilterException
);
exportersManager.removeLinks(serviceReference);
return;
}
if (exportersManager.matched(serviceReference)) {
exportersManager.updateLinks(serviceReference);
} else {
exportersManager.removeLinks(serviceReference);
}
} | java |
private void checkGAs(List l)
{
for (final Iterator i = l.iterator(); i.hasNext();)
if (!(i.next() instanceof GroupAddress))
throw new KNXIllegalArgumentException("not a group address list");
} | java |
public static Trajectory addPositionNoise(Trajectory t, double sd){
CentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();
Trajectory newt = new Trajectory(t.getDimension());
for(int i = 0; i < t.size(); i++){
newt.add(t.get(i));
for(int j = 1; j <= t.getDimension(); j++){
switch (j) {
case 1:
newt.get(i).setX(newt.get(i).x + r.nextGaussian()*sd);
break;
case 2:
newt.get(i).setY(newt.get(i).y + r.nextGaussian()*sd);
break;
case 3:
newt.get(i).setZ(newt.get(i).z + r.nextGaussian()*sd);
break;
default:
break;
}
}
}
return newt;
} | java |
public SerialMessage getNoMoreInformationMessage() {
logger.debug("Creating new message for application command WAKE_UP_NO_MORE_INFORMATION for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessagePriority.Low);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
2,
(byte) getCommandClass().getKey(),
(byte) WAKE_UP_NO_MORE_INFORMATION };
result.setMessagePayload(newPayload);
return result;
} | java |
public void putInWakeUpQueue(SerialMessage serialMessage) {
if (this.wakeUpQueue.contains(serialMessage)) {
logger.debug("Message already on the wake-up queue for node {}. Discarding.", this.getNode().getNodeId());
return;
}
logger.debug("Putting message in wakeup queue for node {}.", this.getNode().getNodeId());
this.wakeUpQueue.add(serialMessage);
} | java |
protected Method resolveTargetMethod(Message message,
FieldDescriptor payloadField) {
Method targetMethod = fieldToMethod.get(payloadField);
if (targetMethod == null) {
// look up and cache target method; this block is called only once
// per target method, so synchronized is ok
synchronized (this) {
targetMethod = fieldToMethod.get(payloadField);
if (targetMethod == null) {
String name = payloadField.getName();
for (Method method : service.getClass().getMethods()) {
if (method.getName().equals(name)) {
try {
method.setAccessible(true);
} catch (Exception ex) {
log.log(Level.SEVERE,"Error accessing RPC method",ex);
}
targetMethod = method;
fieldToMethod.put(payloadField, targetMethod);
break;
}
}
}
}
}
if (targetMethod != null) {
return targetMethod;
} else {
throw new RuntimeException("No matching method found by the name '"
+ payloadField.getName() + "'");
}
} | java |
protected FieldDescriptor resolvePayloadField(Message message) {
for (FieldDescriptor field : message.getDescriptorForType().getFields()) {
if (message.hasField(field)) {
return field;
}
}
throw new RuntimeException("No payload found in message " + message);
} | java |
public static Status from(Set<ServiceReference> serviceReferencesBound, Set<ServiceReference> serviceReferencesHandled) {
if (serviceReferencesBound == null && serviceReferencesHandled == null) {
throw new IllegalArgumentException("Cannot create a status with serviceReferencesBound == null" +
"and serviceReferencesHandled == null");
} else if (serviceReferencesBound == null) {
throw new IllegalArgumentException("Cannot create a status with serviceReferencesBound == null");
} else if (serviceReferencesHandled == null) {
throw new IllegalArgumentException("Cannot create a status with serviceReferencesHandled == null");
}
return new Status(serviceReferencesBound, serviceReferencesHandled);
} | java |
public SerialMessage getValueMessage() {
logger.debug("Creating new message for application command BASIC_GET for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
2,
(byte) getCommandClass().getKey(),
(byte) BASIC_GET };
result.setMessagePayload(newPayload);
return result;
} | java |
public SerialMessage setValueMessage(int level) {
logger.debug("Creating new message for application command BASIC_SET for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.Set);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) BASIC_SET,
(byte) level
};
result.setMessagePayload(newPayload);
return result;
} | java |
public void subscriptionRequestReceived(SubscriptionRequest sr) throws SubscriptionException {
LOG.info("Subscriber -> (Hub), new subscription request received.", sr.getCallback());
try {
verifySubscriberRequestedSubscription(sr);
if ("subscribe".equals(sr.getMode())) {
LOG.info("Adding callback {} to the topic {}", sr.getCallback(), sr.getTopic());
addCallbackToTopic(sr.getCallback(), sr.getTopic());
} else if ("unsubscribe".equals(sr.getMode())) {
LOG.info("Removing callback {} from the topic {}", sr.getCallback(), sr.getTopic());
removeCallbackToTopic(sr.getCallback(), sr.getTopic());
}
} catch (Exception e) {
throw new SubscriptionException(e);
}
} | java |
public Boolean verifySubscriberRequestedSubscription(SubscriptionRequest sr) throws SubscriptionOriginVerificationException {
LOG.info("(Hub) -> Subscriber, sending notification to verify the origin of the subscription {}.", sr.getCallback());
SubscriptionConfirmationRequest sc = new SubscriptionConfirmationRequest(sr.getMode(),
sr.getTopic(), "challenge", "0");
URI uri;
try {
uri = new URIBuilder(sr.getCallback()).setParameters(sc.toRequestParameters()).build();
} catch (URISyntaxException e) {
throw new SubscriptionOriginVerificationException("URISyntaxException while sending a confirmation of subscription", e);
}
HttpGet httpGet = new HttpGet(uri);
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response;
try {
response = httpclient.execute(httpGet);
} catch (IOException e) {
throw new SubscriptionOriginVerificationException("IOException while sending a confirmation of subscription", e);
}
LOG.info("Subscriber replied with the http code {}.", response.getStatusLine().getStatusCode());
Integer returnedCode = response.getStatusLine().getStatusCode();
// if code is a success code return true, else false
return (199 < returnedCode) && (returnedCode < 300);
} | java |
public void notifySubscriberCallback(ContentNotification cn) {
String content = fetchContentFromPublisher(cn);
distributeContentToSubscribers(content, cn.getUrl());
} | java |
public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){
double minDistance = Double.MAX_VALUE;
Point2D.Double minDistancePoint = null;
int numberOfSplines = spline.getN();
double[] knots = spline.getKnots();
for(int i = 0; i < numberOfSplines; i++){
double x = knots[i];
double stopx = knots[i+1];
double dx = (stopx-x)/nPointsPerSegment;
for(int j = 0; j < nPointsPerSegment; j++){
Point2D.Double candidate = new Point2D.Double(x, spline.value(x));
double d = p.distance(candidate);
if(d<minDistance){
minDistance = d;
minDistancePoint = candidate;
}
x += dx;
}
}
return minDistancePoint;
} | java |
public void showTrajectoryAndSpline(){
if(t.getDimension()==2){
double[] xData = new double[rotatedTrajectory.size()];
double[] yData = new double[rotatedTrajectory.size()];
for(int i = 0; i < rotatedTrajectory.size(); i++){
xData[i] = rotatedTrajectory.get(i).x;
yData[i] = rotatedTrajectory.get(i).y;
}
// Create Chart
Chart chart = QuickChart.getChart("Spline+Track", "X", "Y", "y(x)", xData, yData);
//Add spline support points
double[] subxData = new double[splineSupportPoints.size()];
double[] subyData = new double[splineSupportPoints.size()];
for(int i = 0; i < splineSupportPoints.size(); i++){
subxData[i] = splineSupportPoints.get(i).x;
subyData[i] = splineSupportPoints.get(i).y;
}
Series s = chart.addSeries("Spline Support Points", subxData, subyData);
s.setLineStyle(SeriesLineStyle.NONE);
s.setSeriesType(SeriesType.Line);
//ADd spline points
int numberInterpolatedPointsPerSegment = 20;
int numberOfSplines = spline.getN();
double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];
double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];
double[] knots = spline.getKnots();
for(int i = 0; i < numberOfSplines; i++){
double x = knots[i];
double stopx = knots[i+1];
double dx = (stopx-x)/numberInterpolatedPointsPerSegment;
for(int j = 0; j < numberInterpolatedPointsPerSegment; j++){
sxData[i*numberInterpolatedPointsPerSegment+j] = x;
syData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);
x += dx;
}
}
s = chart.addSeries("Spline", sxData, syData);
s.setLineStyle(SeriesLineStyle.DASH_DASH);
s.setMarker(SeriesMarker.NONE);
s.setSeriesType(SeriesType.Line);
//Show it
new SwingWrapper(chart).displayChart();
}
} | java |
public static <T> Set<T> getSet(Collection<T> collection) {
Set<T> set = new LinkedHashSet<T>();
set.addAll(collection);
return set;
} | java |
public static <T> String join(Collection<T> col, String delim) {
StringBuilder sb = new StringBuilder();
Iterator<T> iter = col.iterator();
if (iter.hasNext())
sb.append(iter.next().toString());
while (iter.hasNext()) {
sb.append(delim);
sb.append(iter.next().toString());
}
return sb.toString();
} | java |
public void checkVersion(ZWaveCommandClass commandClass) {
ZWaveVersionCommandClass versionCommandClass = (ZWaveVersionCommandClass)this.getNode().getCommandClass(CommandClass.VERSION);
if (versionCommandClass == null) {
logger.error(String.format("Version command class not supported on node %d," +
"reverting to version 1 for command class %s (0x%02x)",
this.getNode().getNodeId(),
commandClass.getCommandClass().getLabel(),
commandClass.getCommandClass().getKey()));
return;
}
this.getController().sendData(versionCommandClass.getCommandClassVersionMessage(commandClass.getCommandClass()));
} | java |
public static String getContent(String stringUrl) throws IOException {
InputStream stream = getContentStream(stringUrl);
return MyStreamUtils.readContent(stream);
} | java |
public static InputStream getContentStream(String stringUrl) throws MalformedURLException, IOException {
URL url = new URL(stringUrl);
URLConnection urlConnection = url.openConnection();
InputStream is = urlConnection.getInputStream();
if ("gzip".equals(urlConnection.getContentEncoding())) {
is = new GZIPInputStream(is);
}
return is;
} | java |
public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {
return getResponseHeaders(stringUrl, true);
} | java |
public static Map<String, List<String>> getResponseHeaders(String stringUrl,
boolean followRedirects) throws IOException {
URL url = new URL(stringUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(followRedirects);
InputStream is = conn.getInputStream();
if ("gzip".equals(conn.getContentEncoding())) {
is = new GZIPInputStream(is);
}
Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());
headers.put("X-Content", Arrays.asList(MyStreamUtils.readContent(is)));
headers.put("X-URL", Arrays.asList(conn.getURL().toString()));
headers.put("X-Status", Arrays.asList(String.valueOf(conn.getResponseCode())));
return headers;
} | java |
public static void downloadUrl(String stringUrl, Map<String, String> parameters, File fileToSave)
throws IOException {
URL url = new URL(stringUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setFollowRedirects(true);
if (parameters != null) {
for (Entry<String, String> entry : parameters.entrySet()) {
conn.addRequestProperty(entry.getKey(), entry.getValue());
}
}
boolean redirect = false;
// normally, 3xx is redirect
int status = conn.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP
|| status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER)
redirect = true;
}
if (redirect) {
// get redirect url from "location" header field
String newUrl = conn.getHeaderField("Location");
// get the cookie if need, for login
String cookies = conn.getHeaderField("Set-Cookie");
// open the new connnection again
conn = (HttpURLConnection) new URL(newUrl).openConnection();
conn.setRequestProperty("Cookie", cookies);
}
byte[] data = MyStreamUtils.readContentBytes(conn.getInputStream());
FileOutputStream fos = new FileOutputStream(fileToSave);
fos.write(data);
fos.close();
} | java |
public static byte[] getContentBytes(String stringUrl) throws IOException {
URL url = new URL(stringUrl);
byte[] data = MyStreamUtils.readContentBytes(url.openStream());
return data;
} | java |
public static String httpRequest(String stringUrl, String method, Map<String, String> parameters,
String input, String charset) throws IOException {
URL url = new URL(stringUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod(method);
if (parameters != null) {
for (Entry<String, String> entry : parameters.entrySet()) {
conn.addRequestProperty(entry.getKey(), entry.getValue());
}
}
if (input != null) {
OutputStream output = null;
try {
output = conn.getOutputStream();
output.write(input.getBytes(charset));
} finally {
if (output != null) {
output.close();
}
}
}
return MyStreamUtils.readContent(conn.getInputStream());
} | java |
public void add(ServiceReference<D> declarationSRef) {
D declaration = getDeclaration(declarationSRef);
boolean matchFilter = declarationFilter.matches(declaration.getMetadata());
declarations.put(declarationSRef, matchFilter);
} | java |
public void createLinks(ServiceReference<D> declarationSRef) {
D declaration = getDeclaration(declarationSRef);
for (ServiceReference<S> serviceReference : linkerManagement.getMatchedBinderServiceRef()) {
if (linkerManagement.canBeLinked(declaration, serviceReference)) {
linkerManagement.link(declaration, serviceReference);
}
}
} | java |
public void removeLinks(ServiceReference<D> declarationSRef) {
D declaration = getDeclaration(declarationSRef);
for (ServiceReference serviceReference : declaration.getStatus().getServiceReferencesBounded()) {
// FIXME : In case of multiples Linker, we will remove the link of all the ServiceReference
// FIXME : event the ones which dun know nothing about
linkerManagement.unlink(declaration, serviceReference);
}
} | java |
public Set<D> getMatchedDeclaration() {
Set<D> bindedSet = new HashSet<D>();
for (Map.Entry<ServiceReference<D>, Boolean> e : declarations.entrySet()) {
if (e.getValue()) {
bindedSet.add(getDeclaration(e.getKey()));
}
}
return bindedSet;
} | java |
Subsets and Splits