code
stringlengths 73
34.1k
| func_name
stringlengths 1
122
|
---|---|
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));
} | determineAccessorPrefix |
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);
} | determineFieldName |
public static <T extends JsonRtn> T parseJsonRtn(String jsonRtn, Class<T> jsonRtnClazz) {
T rtn = JSONObject.parseObject(jsonRtn, jsonRtnClazz);
appendErrorHumanMsg(rtn);
return rtn;
} | parseJsonRtn |
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;
}
} | appendErrorHumanMsg |
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;
} | isSuccess |
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;
} | unmarshal |
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;
} | marshal |
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;
} | parseFile |
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;
} | createAndRegisterDeclaration |
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);
}
} | start |
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();
} | stop |
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;
} | calculateBoundedness |
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;
} | getRadiusToBoundedness |
@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();
} | checkByte |
@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();
} | checkDouble |
@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();
} | checkFloat |
@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();
} | checkInteger |
@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();
} | checkLong |
@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();
} | checkShort |
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;
} | estimateExcludedVolumeFraction |
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();
} | handleMultiInstanceReportResponse |
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);
} | handleMultiInstanceEncapResponse |
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);
} | handleMultiChannelEncapResponse |
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;
} | getMultiInstanceGetMessage |
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;
} | getMultiChannelCapabilityGetMessage |
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);
} | createImportationDeclaration |
public static Dimension getDimension(File videoFile) throws IOException {
try (FileInputStream fis = new FileInputStream(videoFile)) {
return getDimension(fis, new AtomicReference<ByteBuffer>());
}
} | getDimension |
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);
} | determineAccessorName |
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);
} | determineMutatorName |
@Nonnull
public static XMLDSigValidationResult createReferenceErrors (@Nonnull @Nonempty final List <Integer> aInvalidReferences)
{
return new XMLDSigValidationResult (aInvalidReferences);
} | createReferenceErrors |
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;
} | getTrajectoryChart |
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;
} | getMSDLineChart |
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;
} | getMSDLineWithConfinedModelChart |
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;
} | getMSDLineWithPowerModelChart |
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;
} | getMSDLineWithFreeModelChart |
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;
} | getMSDLineWithActiveTransportModelChart |
public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax) {
return getMSDLineChart(t, lagMin, lagMax, new MeanSquaredDisplacmentFeature(t,
lagMin));
} | getMSDLineChart |
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);
} | plotCharts |
@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;
} | find |
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();
}
} | query |
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();
}
} | parseResponse |
@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);
} | analyze |
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;
} | next |
private static boolean matches(@Nonnull final Pattern pattern, @Nonnull final CharSequence chars) {
return pattern.matcher(chars).matches();
} | matches |
@ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNumberArgumentException.class })
public static void isNumber(final boolean condition, @Nonnull final String value) {
if (condition) {
Check.isNumber(value);
}
} | isNumber |
@Override
public Trajectory subList(int fromIndex, int toIndex) {
Trajectory t = new Trajectory(dimension);
for(int i = fromIndex; i < toIndex; i++){
t.add(this.get(i));
}
return t;
} | subList |
public double[][] getPositionsAsArray(){
double[][] posAsArr = new double[size()][3];
for(int i = 0; i < size(); i++){
if(get(i)!=null){
posAsArr[i][0] = get(i).x;
posAsArr[i][1] = get(i).y;
posAsArr[i][2] = get(i).z;
}
else{
posAsArr[i] = null;
}
}
return posAsArr;
} | getPositionsAsArray |
public void scale(double v){
for(int i = 0; i < this.size(); i++){
this.get(i).scale(v);;
}
} | scale |
public static int randomIntBetween(int min, int max) {
Random rand = new Random();
return rand.nextInt((max - min) + 1) + min;
} | randomIntBetween |
public static long randomLongBetween(long min, long max) {
Random rand = new Random();
return min + (long) (rand.nextDouble() * (max - min));
} | randomLongBetween |
private static int getTrimmedXStart(BufferedImage img) {
int height = img.getHeight();
int width = img.getWidth();
int xStart = width;
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (img.getRGB(j, i) != Color.WHITE.getRGB() && j < xStart) {
xStart = j;
break;
}
}
}
return xStart;
} | getTrimmedXStart |
private static int getTrimmedWidth(BufferedImage img) {
int height = img.getHeight();
int width = img.getWidth();
int trimmedWidth = 0;
for (int i = 0; i < height; i++) {
for (int j = width - 1; j >= 0; j--) {
if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {
trimmedWidth = j;
break;
}
}
}
return trimmedWidth;
} | getTrimmedWidth |
private static int getTrimmedYStart(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int yStart = height;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
if (img.getRGB(i, j) != Color.WHITE.getRGB() && j < yStart) {
yStart = j;
break;
}
}
}
return yStart;
} | getTrimmedYStart |
private static int getTrimmedHeight(BufferedImage img) {
int width = img.getWidth();
int height = img.getHeight();
int trimmedHeight = 0;
for (int i = 0; i < width; i++) {
for (int j = height - 1; j >= 0; j--) {
if (img.getRGB(i, j) != Color.WHITE.getRGB() && j > trimmedHeight) {
trimmedHeight = j;
break;
}
}
}
return trimmedHeight;
} | getTrimmedHeight |
public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int heightPercent = (heightOut * 100) / height;
int newWidth = (width * heightPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);
g.dispose();
return resizedImage;
} | resizeToHeight |
public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int widthPercent = (widthOut * 100) / width;
int newHeight = (height * widthPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);
g.dispose();
return resizedImage;
} | resizeToWidth |
public static String regexFindFirst(String pattern, String str) {
return regexFindFirst(Pattern.compile(pattern), str, 1);
} | regexFindFirst |
public static List<String> asListLines(String content) {
List<String> retorno = new ArrayList<String>();
content = content.replace(CARRIAGE_RETURN, RETURN);
content = content.replace(RETURN, CARRIAGE_RETURN);
for (String str : content.split(CARRIAGE_RETURN)) {
retorno.add(str);
}
return retorno;
} | asListLines |
public static List<String> asListLinesIgnore(String content, Pattern ignorePattern) {
List<String> retorno = new ArrayList<String>();
content = content.replace(CARRIAGE_RETURN, RETURN);
content = content.replace(RETURN, CARRIAGE_RETURN);
for (String str : content.split(CARRIAGE_RETURN)) {
if (!ignorePattern.matcher(str).matches()) {
retorno.add(str);
}
}
return retorno;
} | asListLinesIgnore |
public static Map<String, String> getContentMap(File file, String separator) throws IOException {
List<String> content = getContentLines(file);
Map<String, String> map = new LinkedHashMap<String, String>();
for (String line : content) {
String[] spl = line.split(separator);
if (line.trim().length() > 0) {
map.put(spl[0], (spl.length > 1 ? spl[1] : ""));
}
}
return map;
} | getContentMap |
public static void saveContentMap(Map<String, String> map, File file) throws IOException {
FileWriter out = new FileWriter(file);
for (String key : map.keySet()) {
if (map.get(key) != null) {
out.write(key.replace(":", "#escapedtwodots#") + ":"
+ map.get(key).replace(":", "#escapedtwodots#") + "\r\n");
}
}
out.close();
} | saveContentMap |
public static String getTabularData(String[] labels, String[][] data, int padding) {
int[] size = new int[labels.length];
for (int i = 0; i < labels.length; i++) {
size[i] = labels[i].length() + padding;
}
for (String[] row : data) {
for (int i = 0; i < labels.length; i++) {
if (row[i].length() >= size[i]) {
size[i] = row[i].length() + padding;
}
}
}
StringBuffer tabularData = new StringBuffer();
for (int i = 0; i < labels.length; i++) {
tabularData.append(labels[i]);
tabularData.append(fill(' ', size[i] - labels[i].length()));
}
tabularData.append("\n");
for (int i = 0; i < labels.length; i++) {
tabularData.append(fill('=', size[i] - 1)).append(" ");
}
tabularData.append("\n");
for (String[] row : data) {
for (int i = 0; i < labels.length; i++) {
tabularData.append(row[i]);
tabularData.append(fill(' ', size[i] - row[i].length()));
}
tabularData.append("\n");
}
return tabularData.toString();
} | getTabularData |
public static String replaceHtmlEntities(String content, Map<String, Character> map) {
for (Entry<String, Character> entry : escapeStrings.entrySet()) {
if (content.indexOf(entry.getKey()) != -1) {
content = content.replace(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return content;
} | replaceHtmlEntities |
public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {
BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);
declarationBinders.put(declarationBinderRef, binderDescriptor);
} | add |
public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {
declarationBinders.get(declarationBinderRef).update(declarationBinderRef);
} | modified |
public void createLinks(ServiceReference<S> declarationBinderRef) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {
linkerManagement.link(declaration, declarationBinderRef);
}
}
} | createLinks |
public void updateLinks(ServiceReference<S> serviceReference) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);
boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);
if (isAlreadyLinked && !canBeLinked) {
linkerManagement.unlink(declaration, serviceReference);
} else if (!isAlreadyLinked && canBeLinked) {
linkerManagement.link(declaration, serviceReference);
}
}
} | updateLinks |
public void removeLinks(ServiceReference<S> declarationBinderRef) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {
linkerManagement.unlink(declaration, declarationBinderRef);
}
}
} | removeLinks |
public Set<S> getMatchedDeclarationBinder() {
Set<S> bindedSet = new HashSet<S>();
for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {
if (e.getValue().match) {
bindedSet.add(getDeclarationBinder(e.getKey()));
}
}
return bindedSet;
} | getMatchedDeclarationBinder |
public static List<File> extract(File zipFile, File outputFolder) throws IOException {
List<File> extracted = new ArrayList<File>();
byte[] buffer = new byte[2048];
if (!outputFolder.exists()) {
outputFolder.mkdir();
}
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zipInput.getNextEntry();
while (zipEntry != null) {
String neFileNameName = zipEntry.getName();
File newFile = new File(outputFolder + File.separator + neFileNameName);
newFile.getParentFile().mkdirs();
if (!zipEntry.isDirectory()) {
FileOutputStream fos = new FileOutputStream(newFile);
int size;
while ((size = zipInput.read(buffer)) > 0) {
fos.write(buffer, 0, size);
}
fos.close();
extracted.add(newFile);
}
zipEntry = zipInput.getNextEntry();
}
zipInput.closeEntry();
zipInput.close();
return extracted;
} | extract |
public static void validateZip(File file) throws IOException {
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zipInput.getNextEntry();
while (zipEntry != null) {
zipEntry = zipInput.getNextEntry();
}
try {
if (zipInput != null) {
zipInput.close();
}
} catch (IOException e) {
}
} | validateZip |
public static void compress(File dir, File zipFile) throws IOException {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
recursiveAddZip(dir, zos, dir);
zos.finish();
zos.close();
} | compress |
public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)
throws IOException {
File[] files = fileSource.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
recursiveAddZip(parent, zout, files[i]);
continue;
}
byte[] buffer = new byte[1024];
FileInputStream fin = new FileInputStream(files[i]);
ZipEntry zipEntry =
new ZipEntry(files[i].getAbsolutePath()
.replace(parent.getAbsolutePath(), "").substring(1)); //$NON-NLS-1$
zout.putNextEntry(zipEntry);
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
} | recursiveAddZip |
public static String readContent(InputStream is) {
String ret = "";
try {
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer out = new StringBuffer();
while ((line = in.readLine()) != null) {
out.append(line).append(CARRIAGE_RETURN);
}
ret = out.toString();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
} | readContent |
public static boolean streamHasText(InputStream in, String text) {
final byte[] readBuffer = new byte[8192];
StringBuffer sb = new StringBuffer();
try {
if (in.available() > 0) {
int bytesRead = 0;
while ((bytesRead = in.read(readBuffer)) != -1) {
sb.append(new String(readBuffer, 0, bytesRead));
if (sb.toString().contains(text)) {
sb = null;
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} | streamHasText |
private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {
final String DUMMY_PROP="dummywrite";
instance.put(DUMMY_PROP,"test");
instance.flush();
instance.remove(DUMMY_PROP);
instance.flush();
} | tryWritePreferenceOnDisk |
private void doSend(byte[] msg, boolean wait, KNXAddress dst)
throws KNXAckTimeoutException, KNXLinkClosedException
{
if (closed)
throw new KNXLinkClosedException("link closed");
try {
logger.info("send message to " + dst + (wait ? ", wait for ack" : ""));
logger.trace("EMI " + DataUnitBuilder.toHex(msg, " "));
conn.send(msg, wait);
logger.trace("send to " + dst + " succeeded");
}
catch (final KNXPortClosedException e) {
logger.error("send error, closing link", e);
close();
throw new KNXLinkClosedException("link closed, " + e.getMessage());
}
} | doSend |
static public String bb2hex(byte[] bb) {
String result = "";
for (int i=0; i<bb.length; i++) {
result = result + String.format("%02X ", bb[i]);
}
return result;
} | bb2hex |
private static byte calculateChecksum(byte[] buffer) {
byte checkSum = (byte)0xFF;
for (int i=1; i<buffer.length-1; i++) {
checkSum = (byte) (checkSum ^ buffer[i]);
}
logger.trace(String.format("Calculated checksum = 0x%02X", checkSum));
return checkSum;
} | calculateChecksum |
public byte[] getMessageBuffer() {
ByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();
byte[] result;
resultByteBuffer.write((byte)0x01);
int messageLength = messagePayload.length +
(this.messageClass == SerialMessageClass.SendData &&
this.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length
resultByteBuffer.write((byte) messageLength);
resultByteBuffer.write((byte) messageType.ordinal());
resultByteBuffer.write((byte) messageClass.getKey());
try {
resultByteBuffer.write(messagePayload);
} catch (IOException e) {
}
// callback ID and transmit options for a Send Data message.
if (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {
resultByteBuffer.write(transmitOptions);
resultByteBuffer.write(callbackId);
}
resultByteBuffer.write((byte) 0x00);
result = resultByteBuffer.toByteArray();
result[result.length - 1] = 0x01;
result[result.length - 1] = calculateChecksum(result);
logger.debug("Assembled message buffer = " + SerialMessage.bb2hex(result));
return result;
} | getMessageBuffer |
private static String getBundle(String friendlyName, String className, int truncate)
{
try {
cl.loadClass(className);
int start = className.length();
for (int i = 0; i < truncate; ++i)
start = className.lastIndexOf('.', start - 1);
final String bundle = className.substring(0, start);
return "+ " + friendlyName + align(friendlyName) + "- " + bundle;
}
catch (final ClassNotFoundException e) {}
catch (final NoClassDefFoundError e) {}
return "- " + friendlyName + align(friendlyName) + "- not available";
} | getBundle |
protected ServiceRegistration registerProxy(Object objectProxy, Class clazz) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
ServiceRegistration registration;
registration = context.registerService(clazz, objectProxy, props);
return registration;
} | registerProxy |
@Override
protected void denyImportDeclaration(ImportDeclaration importDeclaration) {
LOG.debug("CXFImporter destroy a proxy for " + importDeclaration);
ServiceRegistration serviceRegistration = map.get(importDeclaration);
serviceRegistration.unregister();
// set the importDeclaration has unhandled
super.unhandleImportDeclaration(importDeclaration);
map.remove(importDeclaration);
} | denyImportDeclaration |
public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {
Check.notNull(code, "code");
final ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, "settings"));
final InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);
final Clazz clazz = scaffoldClazz(analysis, settings);
// immutable settings
settingsBuilder.fields(clazz.getFields());
settingsBuilder.immutableName(clazz.getName());
settingsBuilder.imports(clazz.getImports());
final Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));
settingsBuilder.mainInterface(definition);
settingsBuilder.interfaces(clazz.getInterfaces());
settingsBuilder.packageDeclaration(clazz.getPackage());
final String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));
final String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));
return new Result(implementationCode, testCode);
} | generate |
public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException {
URLClassLoader sysloader = (URLClassLoader) loader;
Class<?> sysclass = URLClassLoader.class;
Method method =
sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});
method.setAccessible(true);
method.invoke(sysloader, new Object[] {url});
} | addJarToClasspath |
public void resetResendCount() {
this.resendCount = 0;
if (this.initializationComplete)
this.nodeStage = NodeStage.NODEBUILDINFO_DONE;
this.lastUpdated = Calendar.getInstance().getTime();
} | resetResendCount |
public void addCommandClass(ZWaveCommandClass commandClass)
{
ZWaveCommandClass.CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
supportedCommandClasses.put(key, commandClass);
if (commandClass instanceof ZWaveEventListener)
this.controller.addEventListener((ZWaveEventListener)commandClass);
this.lastUpdated = Calendar.getInstance().getTime();
}
} | addCommandClass |
public static String getPostString(InputStream is, String encoding) {
try {
StringWriter sw = new StringWriter();
IOUtils.copy(is, sw, encoding);
return sw.toString();
} catch (IOException e) {
// no op
return null;
} finally {
IOUtils.closeQuietly(is);
}
} | getPostString |
public static void outputString(final HttpServletResponse response, final Object obj) {
try {
response.setContentType("text/javascript");
response.setCharacterEncoding("utf-8");
disableCache(response);
response.getWriter().write(obj.toString());
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
}
} | outputString |
public double convert(double value, double temperatur, double viscosity){
return temperatur*kB / (Math.PI*viscosity*value);
} | convert |
public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values)
throws InstantiationException, IllegalAccessException, IntrospectionException,
IllegalArgumentException, InvocationTargetException {
return buildInstanceForMap(clazz, values, new MyDefaultReflectionDifferenceHandler());
} | buildInstanceForMap |
public static <T> T buildInstanceForMap(Class<T> clazz, Map<String, Object> values, MyReflectionDifferenceHandler differenceHandler)
throws InstantiationException, IllegalAccessException, IntrospectionException,
IllegalArgumentException, InvocationTargetException {
log.debug("Building new instance of Class " + clazz.getName());
T instance = clazz.newInstance();
for (String key : values.keySet()) {
Object value = values.get(key);
if (value == null) {
log.debug("Value for field " + key + " is null, so ignoring it...");
continue;
}
log.debug(
"Invoke setter for " + key + " (" + value.getClass() + " / " + value.toString() + ")");
Method setter = null;
try {
setter = new PropertyDescriptor(key.replace('.', '_'), clazz).getWriteMethod();
} catch (Exception e) {
throw new IllegalArgumentException("Setter for field " + key + " was not found", e);
}
Class<?> argumentType = setter.getParameterTypes()[0];
if (argumentType.isAssignableFrom(value.getClass())) {
setter.invoke(instance, value);
} else {
Object newValue = differenceHandler.handleDifference(value, setter.getParameterTypes()[0]);
setter.invoke(instance, newValue);
}
}
return instance;
} | buildInstanceForMap |
private static BundleCapability getExportedPackage(BundleContext context, String packageName) {
List<BundleCapability> packages = new ArrayList<BundleCapability>();
for (Bundle bundle : context.getBundles()) {
BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
for (BundleCapability packageCapability : bundleRevision.getDeclaredCapabilities(BundleRevision.PACKAGE_NAMESPACE)) {
String pName = (String) packageCapability.getAttributes().get(BundleRevision.PACKAGE_NAMESPACE);
if (pName.equalsIgnoreCase(packageName)) {
packages.add(packageCapability);
}
}
}
Version max = Version.emptyVersion;
BundleCapability maxVersion = null;
for (BundleCapability aPackage : packages) {
Version version = (Version) aPackage.getAttributes().get("version");
if (max.compareTo(version) <= 0) {
max = version;
maxVersion = aPackage;
}
}
return maxVersion;
} | getExportedPackage |
private String[] readXMLDeclaration(Reader r) throws KNXMLException
{
final StringBuffer buf = new StringBuffer(100);
try {
for (int c = 0; (c = r.read()) != -1 && c != '?';)
buf.append((char) c);
}
catch (final IOException e) {
throw new KNXMLException("reading XML declaration, " + e.getMessage(), buf
.toString(), 0);
}
String s = buf.toString().trim();
String version = null;
String encoding = null;
String standalone = null;
for (int state = 0; state < 3; ++state)
if (state == 0 && s.startsWith("version")) {
version = getAttValue(s = s.substring(7));
s = s.substring(s.indexOf(version) + version.length() + 1).trim();
}
else if (state == 1 && s.startsWith("encoding")) {
encoding = getAttValue(s = s.substring(8));
s = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();
}
else if (state == 1 || state == 2) {
if (s.startsWith("standalone")) {
standalone = getAttValue(s);
if (!standalone.equals("yes") && !standalone.equals("no"))
throw new KNXMLException("invalid standalone pseudo-attribute",
standalone, 0);
break;
}
}
else
throw new KNXMLException("unknown XML declaration pseudo-attribute", s, 0);
return new String[] { version, encoding, standalone };
} | readXMLDeclaration |
private Long fetchServiceId(ServiceReference serviceReference) {
return (Long) serviceReference.getProperty(org.osgi.framework.Constants.SERVICE_ID);
} | fetchServiceId |
public void setSpecificDeviceClass(Specific specificDeviceClass) throws IllegalArgumentException {
// The specific Device class does not match the generic device class.
if (specificDeviceClass.genericDeviceClass != Generic.NOT_KNOWN &&
specificDeviceClass.genericDeviceClass != this.genericDeviceClass)
throw new IllegalArgumentException("specificDeviceClass");
this.specificDeviceClass = specificDeviceClass;
} | setSpecificDeviceClass |
private String parseRssFeed(String feed) {
String[] result = feed.split("<br />");
String[] result2 = result[2].split("<BR />");
return result2[0];
} | parseRssFeed |
private List<String> parseRssFeedForeCast(String feed) {
String[] result = feed.split("<br />");
List<String> returnList = new ArrayList<String>();
String[] result2 = result[2].split("<BR />");
returnList.add(result2[3] + "\n");
returnList.add(result[3] + "\n");
returnList.add(result[4] + "\n");
returnList.add(result[5] + "\n");
returnList.add(result[6] + "\n");
return returnList;
} | parseRssFeedForeCast |
public SerialMessage getMessage(AlarmType alarmType) {
logger.debug("Creating new message for application command SENSOR_ALARM_GET for node {}", this.getNode().getNodeId());
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
3,
(byte) getCommandClass().getKey(),
(byte) SENSOR_ALARM_GET,
(byte) alarmType.getKey() };
result.setMessagePayload(newPayload);
return result;
} | getMessage |
public SerialMessage getSupportedMessage() {
logger.debug("Creating new message for application command SENSOR_ALARM_SUPPORTED_GET for node {}", this.getNode().getNodeId());
if (this.getNode().getManufacturer() == 0x010F && this.getNode().getDeviceType() == 0x0501) {
logger.warn("Detected Fibaro FGBS001 Universal Sensor - this device fails to respond to SENSOR_ALARM_GET and SENSOR_ALARM_SUPPORTED_GET.");
return null;
}
SerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);
byte[] newPayload = { (byte) this.getNode().getNodeId(),
2,
(byte) getCommandClass().getKey(),
(byte) SENSOR_ALARM_SUPPORTED_GET };
result.setMessagePayload(newPayload);
return result;
} | getSupportedMessage |