_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q8600 | ZWaveController.handleGetVersionResponse | train | 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 | {
"resource": ""
} |
q8601 | ZWaveController.handleSerialApiGetInitDataResponse | train | 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 | {
"resource": ""
} |
q8602 | ZWaveController.handleMemoryGetId | train | 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 | {
"resource": ""
} |
q8603 | ZWaveController.handleSerialAPIGetCapabilitiesResponse | train | 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 | {
"resource": ""
} |
q8604 | ZWaveController.handleSendDataResponse | train | 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 | {
"resource": ""
} |
q8605 | ZWaveController.handleRequestNodeInfoResponse | train | 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 | {
"resource": ""
} |
q8606 | ZWaveController.connect | train | 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 | {
"resource": ""
} |
q8607 | ZWaveController.close | train | 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 | {
"resource": ""
} |
q8608 | ZWaveController.disconnect | train | 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 | {
"resource": ""
} |
q8609 | ZWaveController.enqueue | train | public void enqueue(SerialMessage serialMessage) {
this.sendQueue.add(serialMessage);
logger.debug("Enqueueing message. Queue length = {}", this.sendQueue.size());
} | java | {
"resource": ""
} |
q8610 | ZWaveController.notifyEventListeners | train | public void notifyEventListeners(ZWaveEvent event) {
logger.debug("Notifying event listeners");
for (ZWaveEventListener listener : this.zwaveEventListeners) {
logger.trace("Notifying {}", listener.toString());
listener.ZWaveIncomingEvent(event);
}
} | java | {
"resource": ""
} |
q8611 | ZWaveController.initialize | train | 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 | {
"resource": ""
} |
q8612 | ZWaveController.identifyNode | train | 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 | {
"resource": ""
} |
q8613 | ZWaveController.requestNodeInfo | train | 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 | {
"resource": ""
} |
q8614 | ZWaveController.sendData | train | 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 | {
"resource": ""
} |
q8615 | ZWaveController.sendValue | train | 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 | {
"resource": ""
} |
q8616 | DefaultImportationLinker.processProperties | train | 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 | {
"resource": ""
} |
q8617 | DefaultImportationLinker.modifiedImporterService | train | @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 | {
"resource": ""
} |
q8618 | JSONRPCExporter.unregisterAllServlets | train | private void unregisterAllServlets() {
for (String endpoint : registeredServlets) {
registeredServlets.remove(endpoint);
web.unregister(endpoint);
LOG.info("endpoint {} unregistered", endpoint);
}
} | java | {
"resource": ""
} |
q8619 | StaticDriftCalculator.calculateDrift | train | 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 | {
"resource": ""
} |
q8620 | ZWaveEndpoint.addCommandClass | train | public void addCommandClass(ZWaveCommandClass commandClass) {
ZWaveCommandClass.CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
supportedCommandClasses.put(key, commandClass);
}
} | java | {
"resource": ""
} |
q8621 | LinkerManagement.canBeLinked | train | 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 | {
"resource": ""
} |
q8622 | LinkerManagement.link | train | 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 | {
"resource": ""
} |
q8623 | LinkerManagement.unlink | train | 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 | {
"resource": ""
} |
q8624 | Package.removeLastDot | train | private static String removeLastDot(final String pkgName) {
return pkgName.charAt(pkgName.length() - 1) == Characters.DOT ? pkgName.substring(0, pkgName.length() - 1) : pkgName;
} | java | {
"resource": ""
} |
q8625 | SourceCodeFormatter.findDefaultProperties | train | @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 | {
"resource": ""
} |
q8626 | SourceCodeFormatter.format | train | 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 | {
"resource": ""
} |
q8627 | DefaultExportationLinker.processProperties | train | 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 | {
"resource": ""
} |
q8628 | DefaultExportationLinker.modifiedExporterService | train | @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 | {
"resource": ""
} |
q8629 | StateDP.checkGAs | train | 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 | {
"resource": ""
} |
q8630 | SimulationUtil.addPositionNoise | train | 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 | {
"resource": ""
} |
q8631 | ZWaveWakeUpCommandClass.getNoMoreInformationMessage | train | 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 | {
"resource": ""
} |
q8632 | ZWaveWakeUpCommandClass.putInWakeUpQueue | train | 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 | {
"resource": ""
} |
q8633 | SimpleRpcDispatcher.resolveTargetMethod | train | 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 | {
"resource": ""
} |
q8634 | SimpleRpcDispatcher.resolvePayloadField | train | 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 | {
"resource": ""
} |
q8635 | Status.from | train | 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 | {
"resource": ""
} |
q8636 | ZWaveBasicCommandClass.getValueMessage | train | 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 | {
"resource": ""
} |
q8637 | ZWaveBasicCommandClass.setValueMessage | train | 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 | {
"resource": ""
} |
q8638 | HubImpl.subscriptionRequestReceived | train | 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 | {
"resource": ""
} |
q8639 | HubImpl.verifySubscriberRequestedSubscription | train | 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 | {
"resource": ""
} |
q8640 | HubImpl.notifySubscriberCallback | train | public void notifySubscriberCallback(ContentNotification cn) {
String content = fetchContentFromPublisher(cn);
distributeContentToSubscribers(content, cn.getUrl());
} | java | {
"resource": ""
} |
q8641 | TrajectorySplineFit.minDistancePointSpline | train | 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 | {
"resource": ""
} |
q8642 | TrajectorySplineFit.showTrajectoryAndSpline | train | 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 | {
"resource": ""
} |
q8643 | MyListUtils.getSet | train | public static <T> Set<T> getSet(Collection<T> collection) {
Set<T> set = new LinkedHashSet<T>();
set.addAll(collection);
return set;
} | java | {
"resource": ""
} |
q8644 | MyListUtils.join | train | 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 | {
"resource": ""
} |
q8645 | ZWaveVersionCommandClass.checkVersion | train | 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 | {
"resource": ""
} |
q8646 | MyHTTPUtils.getContent | train | public static String getContent(String stringUrl) throws IOException {
InputStream stream = getContentStream(stringUrl);
return MyStreamUtils.readContent(stream);
} | java | {
"resource": ""
} |
q8647 | MyHTTPUtils.getContentStream | train | 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 | {
"resource": ""
} |
q8648 | MyHTTPUtils.getResponseHeaders | train | public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {
return getResponseHeaders(stringUrl, true);
} | java | {
"resource": ""
} |
q8649 | MyHTTPUtils.getResponseHeaders | train | 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 | {
"resource": ""
} |
q8650 | MyHTTPUtils.downloadUrl | train | 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 | {
"resource": ""
} |
q8651 | MyHTTPUtils.getContentBytes | train | public static byte[] getContentBytes(String stringUrl) throws IOException {
URL url = new URL(stringUrl);
byte[] data = MyStreamUtils.readContentBytes(url.openStream());
return data;
} | java | {
"resource": ""
} |
q8652 | MyHTTPUtils.httpRequest | train | 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 | {
"resource": ""
} |
q8653 | LinkerDeclarationsManager.add | train | public void add(ServiceReference<D> declarationSRef) {
D declaration = getDeclaration(declarationSRef);
boolean matchFilter = declarationFilter.matches(declaration.getMetadata());
declarations.put(declarationSRef, matchFilter);
} | java | {
"resource": ""
} |
q8654 | LinkerDeclarationsManager.createLinks | train | 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 | {
"resource": ""
} |
q8655 | LinkerDeclarationsManager.removeLinks | train | 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 | {
"resource": ""
} |
q8656 | LinkerDeclarationsManager.getMatchedDeclaration | train | 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 | {
"resource": ""
} |
q8657 | FieldUtil.determineAccessorPrefix | train | public static AccessorPrefix determineAccessorPrefix(@Nonnull final String methodName) {
Check.notEmpty(methodName, "methodName");
final Matcher m = PATTERN.matcher(methodName);
Check.stateIsTrue(m.find(), "passed method name '%s' is not applicable", methodName);
return new AccessorPrefix(m.group(1));
} | java | {
"resource": ""
} |
q8658 | FieldUtil.determineFieldName | train | public static String determineFieldName(@Nonnull final String methodName) {
Check.notEmpty(methodName, "methodName");
final Matcher m = PATTERN.matcher(methodName);
Check.stateIsTrue(m.find(), "passed method name '%s' is not applicable", methodName);
return m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);
} | java | {
"resource": ""
} |
q8659 | JsonRtnUtil.parseJsonRtn | train | public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {
T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);
appendErrorHumanMsg(rtn);
return rtn;
} | java | {
"resource": ""
} |
q8660 | JsonRtnUtil.appendErrorHumanMsg | train | private static JsonRtn appendErrorHumanMsg(JsonRtn jsonRtn) {
if (bundle == null || jsonRtn == null || StringUtils.isEmpty(jsonRtn.getErrCode())) {
return null;
}
try {
jsonRtn.setErrHumanMsg(bundle.getString(jsonRtn.getErrCode()));
return jsonRtn;
} catch (Exception e) {
return null;
}
} | java | {
"resource": ""
} |
q8661 | JsonRtnUtil.isSuccess | train | public static boolean isSuccess(JsonRtn jsonRtn) {
if (jsonRtn == null) {
return false;
}
String errCode = jsonRtn.getErrCode();
if (StringUtils.isEmpty(errCode) || StringUtils.equals(WECHAT_JSON_RTN_SUCCESS_CODE, errCode)) {
return true;
}
return false;
} | java | {
"resource": ""
} |
q8662 | XmlUtil.unmarshal | train | public static Object unmarshal(String message, Class<?> childClass) {
try {
Class<?>[] reverseAndToArray = Iterables.toArray(Lists.reverse(getAllSuperTypes(childClass)), Class.class);
JAXBContext jaxbCtx = JAXBContext.newInstance(reverseAndToArray);
Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();
return unmarshaller.unmarshal(new StringReader(message));
} catch (Exception e) {
}
return null;
} | java | {
"resource": ""
} |
q8663 | XmlUtil.marshal | train | public static String marshal(Object object) {
if (object == null) {
return null;
}
try {
JAXBContext jaxbCtx = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = jaxbCtx.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
StringWriter sw = new StringWriter();
marshaller.marshal(object, sw);
return sw.toString();
} catch (Exception e) {
}
return null;
} | java | {
"resource": ""
} |
q8664 | AbstractFileBasedDiscovery.parseFile | train | private Properties parseFile(File file) throws InvalidDeclarationFileException {
Properties properties = new Properties();
InputStream is = null;
try {
is = new FileInputStream(file);
properties.load(is);
} catch (Exception e) {
throw new InvalidDeclarationFileException(String.format("Error reading declaration file %s", file.getAbsoluteFile()), e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
LOG.error("IOException thrown while trying to close the declaration file.", e);
}
}
}
if (!properties.containsKey(Constants.ID)) {
throw new InvalidDeclarationFileException(String.format("File %s is not a correct declaration, needs to contains an id property", file.getAbsoluteFile()));
}
return properties;
} | java | {
"resource": ""
} |
q8665 | AbstractFileBasedDiscovery.createAndRegisterDeclaration | train | private D createAndRegisterDeclaration(Map<String, Object> metadata) {
D declaration;
if (klass.equals(ImportDeclaration.class)) {
declaration = (D) ImportDeclarationBuilder.fromMetadata(metadata).build();
} else if (klass.equals(ExportDeclaration.class)) {
declaration = (D) ExportDeclarationBuilder.fromMetadata(metadata).build();
} else {
throw new IllegalStateException("");
}
declarationRegistrationManager.registerDeclaration(declaration);
return declaration;
} | java | {
"resource": ""
} |
q8666 | AbstractFileBasedDiscovery.start | train | void start(String monitoredDirectory, Long pollingTime) {
this.monitoredDirectory = monitoredDirectory;
String deployerKlassName;
if (klass.equals(ImportDeclaration.class)) {
deployerKlassName = ImporterDeployer.class.getName();
} else if (klass.equals(ExportDeclaration.class)) {
deployerKlassName = ExporterDeployer.class.getName();
} else {
throw new IllegalStateException("");
}
this.dm = new DirectoryMonitor(monitoredDirectory, pollingTime, deployerKlassName);
try {
dm.start(getBundleContext());
} catch (DirectoryMonitoringException e) {
LOG.error("Failed to start " + DirectoryMonitor.class.getName() + " for the directory " + monitoredDirectory + " and polling time " + pollingTime.toString(), e);
}
} | java | {
"resource": ""
} |
q8667 | AbstractFileBasedDiscovery.stop | train | void stop() {
try {
dm.stop(getBundleContext());
} catch (DirectoryMonitoringException e) {
LOG.error("Failed to stop " + DirectoryMonitor.class.getName() + " for the directory " + monitoredDirectory, e);
}
declarationsFiles.clear();
declarationRegistrationManager.unregisterAll();
} | java | {
"resource": ""
} |
q8668 | BoundednessFeature.calculateBoundedness | train | public static double calculateBoundedness(double D, int N, double timelag, double confRadius){
double r = confRadius;
double cov_area = a(N)*D*timelag;
double res = cov_area/(4*r*r);
return res;
} | java | {
"resource": ""
} |
q8669 | BoundednessFeature.getRadiusToBoundedness | train | public static double getRadiusToBoundedness(double D, int N, double timelag, double B){
double cov_area = a(N)*D*timelag;
double radius = Math.sqrt(cov_area/(4*B));
return radius;
} | java | {
"resource": ""
} |
q8670 | NumberInRange.checkByte | train | @ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static byte checkByte(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInByteRange(number)) {
throw new IllegalNumberRangeException(number.toString(), BYTE_MIN, BYTE_MAX);
}
return number.byteValue();
} | java | {
"resource": ""
} |
q8671 | NumberInRange.checkDouble | train | @ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static double checkDouble(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInDoubleRange(number)) {
throw new IllegalNumberRangeException(number.toString(), DOUBLE_MIN, DOUBLE_MAX);
}
return number.doubleValue();
} | java | {
"resource": ""
} |
q8672 | NumberInRange.checkFloat | train | @ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static float checkFloat(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInFloatRange(number)) {
throw new IllegalNumberRangeException(number.toString(), FLOAT_MIN, FLOAT_MAX);
}
return number.floatValue();
} | java | {
"resource": ""
} |
q8673 | NumberInRange.checkInteger | train | @ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static int checkInteger(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInIntegerRange(number)) {
throw new IllegalNumberRangeException(number.toString(), INTEGER_MIN, INTEGER_MAX);
}
return number.intValue();
} | java | {
"resource": ""
} |
q8674 | NumberInRange.checkLong | train | @ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static int checkLong(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInLongRange(number)) {
throw new IllegalNumberRangeException(number.toString(), LONG_MIN, LONG_MAX);
}
return number.intValue();
} | java | {
"resource": ""
} |
q8675 | NumberInRange.checkShort | train | @ArgumentsChecked
@Throws(IllegalNullArgumentException.class)
public static short checkShort(@Nonnull final Number number) {
Check.notNull(number, "number");
if (!isInShortRange(number)) {
throw new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);
}
return number.shortValue();
} | java | {
"resource": ""
} |
q8676 | AnomalousDiffusionScene.estimateExcludedVolumeFraction | train | public double estimateExcludedVolumeFraction(){
//Calculate volume/area of the of the scene without obstacles
if(recalculateVolumeFraction){
CentralRandomNumberGenerator r = CentralRandomNumberGenerator.getInstance();
boolean firstRandomDraw = false;
if(randomNumbers==null){
randomNumbers = new double[nRandPoints*dimension];
firstRandomDraw = true;
}
int countCollision = 0;
for(int i = 0; i< nRandPoints; i++){
double[] pos = new double[dimension];
for(int j = 0; j < dimension; j++){
if(firstRandomDraw){
randomNumbers[i*dimension + j] = r.nextDouble();
}
pos[j] = randomNumbers[i*dimension + j]*size[j];
}
if(checkCollision(pos)){
countCollision++;
}
}
fraction = countCollision*1.0/nRandPoints;
recalculateVolumeFraction = false;
}
return fraction;
} | java | {
"resource": ""
} |
q8677 | ZWaveMultiInstanceCommandClass.handleMultiInstanceReportResponse | train | private void handleMultiInstanceReportResponse(SerialMessage serialMessage,
int offset) {
logger.trace("Process Multi-instance Report");
int commandClassCode = serialMessage.getMessagePayloadByte(offset);
int instances = serialMessage.getMessagePayloadByte(offset + 1);
if (instances == 0) {
setInstances(1);
} else
{
CommandClass commandClass = CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Node %d Requested Command Class = %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));
ZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
zwaveCommandClass.setInstances(instances);
logger.debug(String.format("Node %d Instances = %d, number of instances set.", this.getNode().getNodeId(), instances));
}
for (ZWaveCommandClass zwaveCommandClass : this.getNode().getCommandClasses())
if (zwaveCommandClass.getInstances() == 0) // still waiting for an instance report of another command class.
return;
// advance node stage.
this.getNode().advanceNodeStage();
} | java | {
"resource": ""
} |
q8678 | ZWaveMultiInstanceCommandClass.handleMultiInstanceEncapResponse | train | private void handleMultiInstanceEncapResponse(
SerialMessage serialMessage, int offset) {
logger.trace("Process Multi-instance Encapsulation");
int instance = serialMessage.getMessagePayloadByte(offset);
int commandClassCode = serialMessage.getMessagePayloadByte(offset + 1);
CommandClass commandClass = CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Node %d Requested Command Class = %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));
ZWaveCommandClass zwaveCommandClass = this.getNode().getCommandClass(commandClass);
if (zwaveCommandClass == null) {
logger.error(String.format("Unsupported command class %s (0x%02x)", commandClass.getLabel(), commandClassCode));
return;
}
logger.debug(String.format("Node %d, Instance = %d, calling handleApplicationCommandRequest.", this.getNode().getNodeId(), instance));
zwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset+ 3, instance);
} | java | {
"resource": ""
} |
q8679 | ZWaveMultiInstanceCommandClass.handleMultiChannelEncapResponse | train | private void handleMultiChannelEncapResponse(
SerialMessage serialMessage, int offset) {
logger.trace("Process Multi-channel Encapsulation");
CommandClass commandClass;
ZWaveCommandClass zwaveCommandClass;
int endpointId = serialMessage.getMessagePayloadByte(offset);
int commandClassCode = serialMessage.getMessagePayloadByte(offset + 2);
commandClass = CommandClass.getCommandClass(commandClassCode);
if (commandClass == null) {
logger.error(String.format("Unsupported command class 0x%02x", commandClassCode));
return;
}
logger.debug(String.format("Node %d Requested Command Class = %s (0x%02x)", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));
ZWaveEndpoint endpoint = this.endpoints.get(endpointId);
if (endpoint == null){
logger.error("Endpoint {} not found on node {}. Cannot set command classes.", endpoint, this.getNode().getNodeId());
return;
}
zwaveCommandClass = endpoint.getCommandClass(commandClass);
if (zwaveCommandClass == null) {
logger.warn(String.format("CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node.", commandClass.getLabel(), commandClassCode, endpointId));
zwaveCommandClass = this.getNode().getCommandClass(commandClass);
}
if (zwaveCommandClass == null) {
logger.error(String.format("CommandClass %s (0x%02x) not implemented by node %d.", commandClass.getLabel(), commandClassCode, this.getNode().getNodeId()));
return;
}
logger.debug(String.format("Node %d, Endpoint = %d, calling handleApplicationCommandRequest.", this.getNode().getNodeId(), endpointId));
zwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 3, endpointId);
} | java | {
"resource": ""
} |
q8680 | ZWaveMultiInstanceCommandClass.getMultiInstanceGetMessage | train | public SerialMessage getMultiInstanceGetMessage(CommandClass commandClass) {
logger.debug("Creating new message for application command MULTI_INSTANCE_GET for node {} and command class {}", this.getNode().getNodeId(), commandClass.getLabel());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) MULTI_INSTANCE_GET,
(byte) commandClass.getKey()
};
result.setMessagePayload(newPayload);
return result;
} | java | {
"resource": ""
} |
q8681 | ZWaveMultiInstanceCommandClass.getMultiChannelCapabilityGetMessage | train | public SerialMessage getMultiChannelCapabilityGetMessage(ZWaveEndpoint endpoint) {
logger.debug("Creating new message for application command MULTI_CHANNEL_CAPABILITY_GET for node {} and endpoint {}", this.getNode().getNodeId(), endpoint.getEndpointId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessageClass.SendData, SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) MULTI_CHANNEL_CAPABILITY_GET,
(byte) endpoint.getEndpointId() };
result.setMessagePayload(newPayload);
return result;
} | java | {
"resource": ""
} |
q8682 | UPnPDiscovery.createImportationDeclaration | train | public synchronized void createImportationDeclaration(String deviceId, String deviceType, String deviceSubType) {
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put(Constants.DEVICE_ID, deviceId);
metadata.put(Constants.DEVICE_TYPE, deviceType);
metadata.put(Constants.DEVICE_TYPE_SUB, deviceSubType);
metadata.put("scope", "generic");
ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();
importDeclarations.put(deviceId, declaration);
registerImportDeclaration(declaration);
} | java | {
"resource": ""
} |
q8683 | MyVideoUtils.getDimension | train | public static Dimension getDimension(File videoFile) throws IOException {
try (FileInputStream fis = new FileInputStream(videoFile)) {
return getDimension(fis, new AtomicReference<ByteBuffer>());
}
} | java | {
"resource": ""
} |
q8684 | MethodUtil.determineAccessorName | train | public static String determineAccessorName(@Nonnull final AccessorPrefix prefix, @Nonnull final String fieldName) {
Check.notNull(prefix, "prefix");
Check.notEmpty(fieldName, "fieldName");
final Matcher m = PATTERN.matcher(fieldName);
Check.stateIsTrue(m.find(), "passed field name '%s' is not applicable", fieldName);
final String name = m.group();
return prefix.getPrefix() + name.substring(0, 1).toUpperCase() + name.substring(1);
} | java | {
"resource": ""
} |
q8685 | MethodUtil.determineMutatorName | train | public static String determineMutatorName(@Nonnull final String fieldName) {
Check.notEmpty(fieldName, "fieldName");
final Matcher m = PATTERN.matcher(fieldName);
Check.stateIsTrue(m.find(), "passed field name '%s' is not applicable", fieldName);
final String name = m.group();
return METHOD_SET_PREFIX + name.substring(0, 1).toUpperCase() + name.substring(1);
} | java | {
"resource": ""
} |
q8686 | XMLDSigValidationResult.createReferenceErrors | train | @Nonnull
public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)
{
return new XMLDSigValidationResult (aInvalidReferences);
} | java | {
"resource": ""
} |
q8687 | VisualizationUtils.getTrajectoryChart | train | public static Chart getTrajectoryChart(String title, Trajectory t){
if(t.getDimension()==2){
double[] xData = new double[t.size()];
double[] yData = new double[t.size()];
for(int i = 0; i < t.size(); i++){
xData[i] = t.get(i).x;
yData[i] = t.get(i).y;
}
// Create Chart
Chart chart = QuickChart.getChart(title, "X", "Y", "y(x)", xData, yData);
return chart;
//Show it
// SwingWrapper swr = new SwingWrapper(chart);
// swr.displayChart();
}
return null;
} | java | {
"resource": ""
} |
q8688 | VisualizationUtils.getMSDLineChart | train | public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,
AbstractMeanSquaredDisplacmentEvaluator msdeval) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | java | {
"resource": ""
} |
q8689 | VisualizationUtils.getMSDLineWithConfinedModelChart | train | public static Chart getMSDLineWithConfinedModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double a, double b, double c, double d) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = a
* (1 - b * Math.exp((-4 * d) * ((i * timelag) / a) * c));
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
if(Math.abs(1-b)<0.00001 && Math.abs(1-a)<0.00001){
chart.addSeries("y=a*(1-exp(-4*D*t/a))", xData, modelData);
}else{
chart.addSeries("y=a*(1-b*exp(-4*c*D*t/a))", xData, modelData);
}
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | java | {
"resource": ""
} |
q8690 | VisualizationUtils.getMSDLineWithPowerModelChart | train | public static Chart getMSDLineWithPowerModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double a, double D) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = 4 * D * Math.pow(i * timelag, a);
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
chart.addSeries("y=4*D*t^alpha", xData, modelData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | java | {
"resource": ""
} |
q8691 | VisualizationUtils.getMSDLineWithFreeModelChart | train | public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double diffusionCoefficient, double intercept) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
chart.addSeries("y=4*D*t + a", xData, modelData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | java | {
"resource": ""
} |
q8692 | VisualizationUtils.getMSDLineWithActiveTransportModelChart | train | public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,
int lagMax, double timelag, double diffusionCoefficient, double velocity) {
double[] xData = new double[lagMax - lagMin + 1];
double[] yData = new double[lagMax - lagMin + 1];
double[] modelData = new double[lagMax - lagMin + 1];
MeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(
t, lagMin);
msdeval.setTrajectory(t);
msdeval.setTimelag(lagMin);
for (int i = lagMin; i < lagMax + 1; i++) {
msdeval.setTimelag(i);
double msdhelp = msdeval.evaluate()[0];
xData[i - lagMin] = i;
yData[i - lagMin] = msdhelp;
modelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);
}
// Create Chart
Chart chart = QuickChart.getChart("MSD Line", "LAG", "MSD", "MSD",
xData, yData);
chart.addSeries("y=4*D*t + (v*t)^2", xData, modelData);
// Show it
//new SwingWrapper(chart).displayChart();
return chart;
} | java | {
"resource": ""
} |
q8693 | VisualizationUtils.getMSDLineChart | train | public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {
return getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,
lagMin));
} | java | {
"resource": ""
} |
q8694 | VisualizationUtils.plotCharts | train | public static void plotCharts(List<Chart> charts){
int numRows =1;
int numCols =1;
if(charts.size()>1){
numRows = (int) Math.ceil(charts.size()/2.0);
numCols = 2;
}
final JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(numRows, numCols));
for (Chart chart : charts) {
if (chart != null) {
JPanel chartPanel = new XChartPanel(chart);
frame.add(chartPanel);
}
else {
JPanel chartPanel = new JPanel();
frame.getContentPane().add(chartPanel);
}
}
// Display the window.
frame.pack();
frame.setVisible(true);
} | java | {
"resource": ""
} |
q8695 | Imports.find | train | @Nullable
public Import find(@Nonnull final String typeName) {
Check.notEmpty(typeName, "typeName");
Import ret = null;
final Type type = new Type(typeName);
for (final Import imp : imports) {
if (imp.getType().getName().equals(type.getName())) {
ret = imp;
break;
}
}
if (ret == null) {
final Type javaLangType = Type.evaluateJavaLangType(typeName);
if (javaLangType != null) {
ret = Import.of(javaLangType);
}
}
return ret;
} | java | {
"resource": ""
} |
q8696 | ZipCodeConverter.query | train | private void query(String zipcode) {
/* Setup YQL query statement using dynamic zipcode. The statement searches geo.places
for the zipcode and returns XML which includes the WOEID. For more info about YQL go
to: http://developer.yahoo.com/yql/ */
String qry = URLEncoder.encode("SELECT woeid FROM geo.places WHERE text=" + zipcode + " LIMIT 1");
// Generate request URI using the query statement
URL url;
try {
// get URL content
url = new URL("http://query.yahooapis.com/v1/public/yql?q=" + qry);
URLConnection conn = url.openConnection();
InputStream content = conn.getInputStream();
parseResponse(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} | java | {
"resource": ""
} |
q8697 | ZipCodeConverter.parseResponse | train | private void parseResponse(InputStream inputStream) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputStream);
doc.getDocumentElement().normalize();
NodeList nodes = doc.getElementsByTagName("place");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
_woeid = getValue("woeid", element);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
} | java | {
"resource": ""
} |
q8698 | InterfaceAnalyzer.analyze | train | @Nonnull
public static InterfaceAnalysis analyze(@Nonnull final String code) {
Check.notNull(code, "code");
final CompilationUnit unit = Check.notNull(SourceCodeReader.parse(code), "compilationUnit");
final List<TypeDeclaration> types = Check.notEmpty(unit.getTypes(), "typeDeclarations");
Check.stateIsTrue(types.size() == 1, "only one interface declaration per analysis is supported");
final ClassOrInterfaceDeclaration type = (ClassOrInterfaceDeclaration) types.get(0);
final Imports imports = SourceCodeReader.findImports(unit.getImports());
final Package pkg = unit.getPackage() != null ? new Package(unit.getPackage().getName().toString()) : Package.UNDEFINED;
final List<Annotation> annotations = SourceCodeReader.findAnnotations(type.getAnnotations(), imports);
final List<Method> methods = SourceCodeReader.findMethods(type.getMembers(), imports);
Check.stateIsTrue(!hasPossibleMutatingMethods(methods), "The passed interface '%s' seems to have mutating methods", type.getName());
final List<Interface> extendsInterfaces = SourceCodeReader.findExtends(type);
final String interfaceName = type.getName();
return new ImmutableInterfaceAnalysis(annotations, extendsInterfaces, imports.asList(), interfaceName, methods, pkg);
} | java | {
"resource": ""
} |
q8699 | TrajectoryValidIndexTimelagIterator.next | train | public Integer next() {
for(int i = currentIndex; i < t.size(); i++){
if(i+timelag>=t.size()){
return null;
}
if((t.get(i) != null) && (t.get(i+timelag) != null)){
if(overlap){
currentIndex = i+1;
}
else{
currentIndex = i+timelag;
}
return i;
}
}
return null;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.