code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package com.netflix.astyanax.partitioner; import java.math.BigInteger; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import org.apache.cassandra.dht.RandomPartitioner; import com.google.common.collect.Lists; import com.netflix.astyanax.connectionpool.TokenRange; import com.netflix.astyanax.connectionpool.impl.TokenRangeImpl; public class BigInteger127Partitioner implements Partitioner { public static final BigInteger MINIMUM = new BigInteger("" + 0); public static final BigInteger MAXIMUM = new BigInteger("" + 2).pow(127); public static final BigInteger ONE = new BigInteger("1"); private static final RandomPartitioner partitioner = new RandomPartitioner(); @Override public String getMinToken() { return MINIMUM.toString(); } @Override public String getMaxToken() { return MAXIMUM.toString(); } @Override public List<TokenRange> splitTokenRange(String first, String last, int count) { List<TokenRange> tokens = Lists.newArrayList(); for (int i = 0; i < count; i++) { String startToken = getTokenMinusOne(getSegmentToken(count, i, new BigInteger(first), new BigInteger(last))); String endToken; if (i == count-1 && last.equals(getMaxToken())) endToken = getMinToken(); else endToken = getSegmentToken(count, i+1, new BigInteger(first), new BigInteger(last)); tokens.add(new TokenRangeImpl(startToken, endToken, new ArrayList<String>())); } return tokens; } @Override public List<TokenRange> splitTokenRange(int count) { return splitTokenRange(getMinToken(), getMaxToken(), count); } @Override public String getTokenForKey(ByteBuffer key) { return partitioner.getToken(key).toString(); } @Override public String getTokenMinusOne(String token) { BigInteger bigInt = new BigInteger(token); // if zero rotate to the Maximum else minus one. if (bigInt.equals(MINIMUM)) return MAXIMUM.toString(); else return bigInt.subtract(ONE).toString(); } public static String getSegmentToken(int size, int position, BigInteger minInitialToken, BigInteger maxInitialToken ) { BigInteger decValue = minInitialToken; if (position != 0) decValue = maxInitialToken.multiply(new BigInteger("" + position)).divide(new BigInteger("" + size)); return decValue.toString(); } }
0x6e6562/astyanax
src/main/java/com/netflix/astyanax/partitioner/BigInteger127Partitioner.java
Java
apache-2.0
2,553
'use strict'; // THIS FILE IS AUTO-GENERATED - DO NOT MODIFY var inherits = require('util').inherits; var Characteristic = require('../Characteristic').Characteristic; var Service = require('../Service').Service; /** * Characteristic "Label Namespace" */ Characteristic.LabelNamespace = function() { Characteristic.call(this, 'Label Namespace', '000000CD-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LabelNamespace, Characteristic); Characteristic.LabelNamespace.UUID = '000000CD-0000-1000-8000-0026BB765291'; // The value property of LabelNamespace must be one of the following: Characteristic.LabelNamespace.DOT = 0; Characteristic.LabelNamespace.NUMBER = 1; /** * Characteristic "Label Index" */ Characteristic.LabelIndex = function() { Characteristic.call(this, 'Label Index', '000000CB-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, maxValue: 255, minValue: 1, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LabelIndex, Characteristic); Characteristic.LabelIndex.UUID = '000000CB-0000-1000-8000-0026BB765291'; /** * Characteristic "Accessory Flags" */ Characteristic.AccessoryFlags = function() { Characteristic.call(this, 'Accessory Flags', '000000A6-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT32, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AccessoryFlags, Characteristic); Characteristic.AccessoryFlags.UUID = '000000A6-0000-1000-8000-0026BB765291'; /** * Characteristic "Active" */ Characteristic.Active = function() { Characteristic.call(this, 'Active', '000000B0-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Active, Characteristic); Characteristic.Active.UUID = '000000B0-0000-1000-8000-0026BB765291'; // The value property of Active must be one of the following: Characteristic.Active.INACTIVE = 0; Characteristic.Active.ACTIVE = 1; /** * Characteristic "Administrator Only Access" */ Characteristic.AdministratorOnlyAccess = function() { Characteristic.call(this, 'Administrator Only Access', '00000001-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AdministratorOnlyAccess, Characteristic); Characteristic.AdministratorOnlyAccess.UUID = '00000001-0000-1000-8000-0026BB765291'; /** * Characteristic "Air Particulate Density" */ Characteristic.AirParticulateDensity = function() { Characteristic.call(this, 'Air Particulate Density', '00000064-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AirParticulateDensity, Characteristic); Characteristic.AirParticulateDensity.UUID = '00000064-0000-1000-8000-0026BB765291'; /** * Characteristic "Air Particulate Size" */ Characteristic.AirParticulateSize = function() { Characteristic.call(this, 'Air Particulate Size', '00000065-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AirParticulateSize, Characteristic); Characteristic.AirParticulateSize.UUID = '00000065-0000-1000-8000-0026BB765291'; // The value property of AirParticulateSize must be one of the following: Characteristic.AirParticulateSize._2_5_M = 0; Characteristic.AirParticulateSize._10_M = 1; /** * Characteristic "Air Quality" */ Characteristic.AirQuality = function() { Characteristic.call(this, 'Air Quality', '00000095-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AirQuality, Characteristic); Characteristic.AirQuality.UUID = '00000095-0000-1000-8000-0026BB765291'; // The value property of AirQuality must be one of the following: Characteristic.AirQuality.UNKNOWN = 0; Characteristic.AirQuality.EXCELLENT = 1; Characteristic.AirQuality.GOOD = 2; Characteristic.AirQuality.FAIR = 3; Characteristic.AirQuality.INFERIOR = 4; Characteristic.AirQuality.POOR = 5; /** * Characteristic "App Matching Identifier" */ Characteristic.AppMatchingIdentifier = function() { Characteristic.call(this, 'App Matching Identifier', '000000A4-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AppMatchingIdentifier, Characteristic); Characteristic.AppMatchingIdentifier.UUID = '000000A4-0000-1000-8000-0026BB765291'; /** * Characteristic "Audio Feedback" */ Characteristic.AudioFeedback = function() { Characteristic.call(this, 'Audio Feedback', '00000005-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.AudioFeedback, Characteristic); Characteristic.AudioFeedback.UUID = '00000005-0000-1000-8000-0026BB765291'; /** * Characteristic "Battery Level" */ Characteristic.BatteryLevel = function() { Characteristic.call(this, 'Battery Level', '00000068-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.BatteryLevel, Characteristic); Characteristic.BatteryLevel.UUID = '00000068-0000-1000-8000-0026BB765291'; /** * Characteristic "Brightness" */ Characteristic.Brightness = function() { Characteristic.call(this, 'Brightness', '00000008-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Brightness, Characteristic); Characteristic.Brightness.UUID = '00000008-0000-1000-8000-0026BB765291'; /** * Characteristic "Carbon Dioxide Detected" */ Characteristic.CarbonDioxideDetected = function() { Characteristic.call(this, 'Carbon Dioxide Detected', '00000092-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CarbonDioxideDetected, Characteristic); Characteristic.CarbonDioxideDetected.UUID = '00000092-0000-1000-8000-0026BB765291'; // The value property of CarbonDioxideDetected must be one of the following: Characteristic.CarbonDioxideDetected.CO2_LEVELS_NORMAL = 0; Characteristic.CarbonDioxideDetected.CO2_LEVELS_ABNORMAL = 1; /** * Characteristic "Carbon Dioxide Level" */ Characteristic.CarbonDioxideLevel = function() { Characteristic.call(this, 'Carbon Dioxide Level', '00000093-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100000, minValue: 0, minStep: 100, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CarbonDioxideLevel, Characteristic); Characteristic.CarbonDioxideLevel.UUID = '00000093-0000-1000-8000-0026BB765291'; /** * Characteristic "Carbon Dioxide Peak Level" */ Characteristic.CarbonDioxidePeakLevel = function() { Characteristic.call(this, 'Carbon Dioxide Peak Level', '00000094-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100000, minValue: 0, minStep: 100, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CarbonDioxidePeakLevel, Characteristic); Characteristic.CarbonDioxidePeakLevel.UUID = '00000094-0000-1000-8000-0026BB765291'; /** * Characteristic "Carbon Monoxide Detected" */ Characteristic.CarbonMonoxideDetected = function() { Characteristic.call(this, 'Carbon Monoxide Detected', '00000069-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CarbonMonoxideDetected, Characteristic); Characteristic.CarbonMonoxideDetected.UUID = '00000069-0000-1000-8000-0026BB765291'; // The value property of CarbonMonoxideDetected must be one of the following: Characteristic.CarbonMonoxideDetected.CO_LEVELS_NORMAL = 0; Characteristic.CarbonMonoxideDetected.CO_LEVELS_ABNORMAL = 1; /** * Characteristic "Carbon Monoxide Level" */ Characteristic.CarbonMonoxideLevel = function() { Characteristic.call(this, 'Carbon Monoxide Level', '00000090-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100, minValue: 0, minStep: 0.1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CarbonMonoxideLevel, Characteristic); Characteristic.CarbonMonoxideLevel.UUID = '00000090-0000-1000-8000-0026BB765291'; /** * Characteristic "Carbon Monoxide Peak Level" */ Characteristic.CarbonMonoxidePeakLevel = function() { Characteristic.call(this, 'Carbon Monoxide Peak Level', '00000091-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100, minValue: 0, minStep: 0.1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CarbonMonoxidePeakLevel, Characteristic); Characteristic.CarbonMonoxidePeakLevel.UUID = '00000091-0000-1000-8000-0026BB765291'; /** * Characteristic "Charging State" */ Characteristic.ChargingState = function() { Characteristic.call(this, 'Charging State', '0000008F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, maxValue: 2, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ChargingState, Characteristic); Characteristic.ChargingState.UUID = '0000008F-0000-1000-8000-0026BB765291'; // The value property of ChargingState must be one of the following: Characteristic.ChargingState.NOT_CHARGING = 0; Characteristic.ChargingState.CHARGING = 1; Characteristic.ChargingState.NOT_CHARGEABLE = 2; /** * Characteristic "Contact Sensor State" */ Characteristic.ContactSensorState = function() { Characteristic.call(this, 'Contact Sensor State', '0000006A-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ContactSensorState, Characteristic); Characteristic.ContactSensorState.UUID = '0000006A-0000-1000-8000-0026BB765291'; // The value property of ContactSensorState must be one of the following: Characteristic.ContactSensorState.CONTACT_DETECTED = 0; Characteristic.ContactSensorState.CONTACT_NOT_DETECTED = 1; /** * Characteristic "Cooling Threshold Temperature" */ Characteristic.CoolingThresholdTemperature = function() { Characteristic.call(this, 'Cooling Threshold Temperature', '0000000D-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.CELSIUS, maxValue: 35, minValue: 10, minStep: 0.1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CoolingThresholdTemperature, Characteristic); Characteristic.CoolingThresholdTemperature.UUID = '0000000D-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Air Purifier State" */ Characteristic.CurrentAirPurifierState = function() { Characteristic.call(this, 'Current Air Purifier State', '000000A9-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentAirPurifierState, Characteristic); Characteristic.CurrentAirPurifierState.UUID = '000000A9-0000-1000-8000-0026BB765291'; // The value property of CurrentAirPurifierState must be one of the following: Characteristic.CurrentAirPurifierState.INACTIVE = 0; Characteristic.CurrentAirPurifierState.IDLE = 1; Characteristic.CurrentAirPurifierState.PURIFYING_AIR = 2; /** * Characteristic "Current Ambient Light Level" */ Characteristic.CurrentAmbientLightLevel = function() { Characteristic.call(this, 'Current Ambient Light Level', '0000006B-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.LUX, maxValue: 100000, minValue: 0.0001, minStep: 0.0001, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentAmbientLightLevel, Characteristic); Characteristic.CurrentAmbientLightLevel.UUID = '0000006B-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Door State" */ Characteristic.CurrentDoorState = function() { Characteristic.call(this, 'Current Door State', '0000000E-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentDoorState, Characteristic); Characteristic.CurrentDoorState.UUID = '0000000E-0000-1000-8000-0026BB765291'; // The value property of CurrentDoorState must be one of the following: Characteristic.CurrentDoorState.OPEN = 0; Characteristic.CurrentDoorState.CLOSED = 1; Characteristic.CurrentDoorState.OPENING = 2; Characteristic.CurrentDoorState.CLOSING = 3; Characteristic.CurrentDoorState.STOPPED = 4; /** * Characteristic "Current Fan State" */ Characteristic.CurrentFanState = function() { Characteristic.call(this, 'Current Fan State', '000000AF-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentFanState, Characteristic); Characteristic.CurrentFanState.UUID = '000000AF-0000-1000-8000-0026BB765291'; // The value property of CurrentFanState must be one of the following: Characteristic.CurrentFanState.INACTIVE = 0; Characteristic.CurrentFanState.IDLE = 1; Characteristic.CurrentFanState.BLOWING_AIR = 2; /** * Characteristic "Current Heater Cooler State" */ Characteristic.CurrentHeaterCoolerState = function() { Characteristic.call(this, 'Current Heater Cooler State', '000000B1-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentHeaterCoolerState, Characteristic); Characteristic.CurrentHeaterCoolerState.UUID = '000000B1-0000-1000-8000-0026BB765291'; // The value property of CurrentHeaterCoolerState must be one of the following: Characteristic.CurrentHeaterCoolerState.INACTIVE = 0; Characteristic.CurrentHeaterCoolerState.IDLE = 1; Characteristic.CurrentHeaterCoolerState.HEATING = 2; Characteristic.CurrentHeaterCoolerState.COOLING = 3; /** * Characteristic "Current Heating Cooling State" */ Characteristic.CurrentHeatingCoolingState = function() { Characteristic.call(this, 'Current Heating Cooling State', '0000000F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentHeatingCoolingState, Characteristic); Characteristic.CurrentHeatingCoolingState.UUID = '0000000F-0000-1000-8000-0026BB765291'; // The value property of CurrentHeatingCoolingState must be one of the following: Characteristic.CurrentHeatingCoolingState.OFF = 0; Characteristic.CurrentHeatingCoolingState.HEAT = 1; Characteristic.CurrentHeatingCoolingState.COOL = 2; /** * Characteristic "Current Horizontal Tilt Angle" */ Characteristic.CurrentHorizontalTiltAngle = function() { Characteristic.call(this, 'Current Horizontal Tilt Angle', '0000006C-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 90, minValue: -90, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentHorizontalTiltAngle, Characteristic); Characteristic.CurrentHorizontalTiltAngle.UUID = '0000006C-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Humidifier Dehumidifier State" */ Characteristic.CurrentHumidifierDehumidifierState = function() { Characteristic.call(this, 'Current Humidifier Dehumidifier State', '000000B3-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentHumidifierDehumidifierState, Characteristic); Characteristic.CurrentHumidifierDehumidifierState.UUID = '000000B3-0000-1000-8000-0026BB765291'; // The value property of CurrentHumidifierDehumidifierState must be one of the following: Characteristic.CurrentHumidifierDehumidifierState.INACTIVE = 0; Characteristic.CurrentHumidifierDehumidifierState.IDLE = 1; Characteristic.CurrentHumidifierDehumidifierState.HUMIDIFYING = 2; Characteristic.CurrentHumidifierDehumidifierState.DEHUMIDIFYING = 3; /** * Characteristic "Current Position" */ Characteristic.CurrentPosition = function() { Characteristic.call(this, 'Current Position', '0000006D-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentPosition, Characteristic); Characteristic.CurrentPosition.UUID = '0000006D-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Relative Humidity" */ Characteristic.CurrentRelativeHumidity = function() { Characteristic.call(this, 'Current Relative Humidity', '00000010-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentRelativeHumidity, Characteristic); Characteristic.CurrentRelativeHumidity.UUID = '00000010-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Slat State" */ Characteristic.CurrentSlatState = function() { Characteristic.call(this, 'Current Slat State', '000000AA-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentSlatState, Characteristic); Characteristic.CurrentSlatState.UUID = '000000AA-0000-1000-8000-0026BB765291'; // The value property of CurrentSlatState must be one of the following: Characteristic.CurrentSlatState.FIXED = 0; Characteristic.CurrentSlatState.JAMMED = 1; Characteristic.CurrentSlatState.SWINGING = 2; /** * Characteristic "Current Temperature" */ Characteristic.CurrentTemperature = function() { Characteristic.call(this, 'Current Temperature', '00000011-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.CELSIUS, maxValue: 100, minValue: 0, minStep: 0.1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentTemperature, Characteristic); Characteristic.CurrentTemperature.UUID = '00000011-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Tilt Angle" */ Characteristic.CurrentTiltAngle = function() { Characteristic.call(this, 'Current Tilt Angle', '000000C1-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 90, minValue: -90, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentTiltAngle, Characteristic); Characteristic.CurrentTiltAngle.UUID = '000000C1-0000-1000-8000-0026BB765291'; /** * Characteristic "Current Vertical Tilt Angle" */ Characteristic.CurrentVerticalTiltAngle = function() { Characteristic.call(this, 'Current Vertical Tilt Angle', '0000006E-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 90, minValue: -90, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.CurrentVerticalTiltAngle, Characteristic); Characteristic.CurrentVerticalTiltAngle.UUID = '0000006E-0000-1000-8000-0026BB765291'; /** * Characteristic "Digital Zoom" */ Characteristic.DigitalZoom = function() { Characteristic.call(this, 'Digital Zoom', '0000011D-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.DigitalZoom, Characteristic); Characteristic.DigitalZoom.UUID = '0000011D-0000-1000-8000-0026BB765291'; /** * Characteristic "Filter Change Indication" */ Characteristic.FilterChangeIndication = function() { Characteristic.call(this, 'Filter Change Indication', '000000AC-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.FilterChangeIndication, Characteristic); Characteristic.FilterChangeIndication.UUID = '000000AC-0000-1000-8000-0026BB765291'; // The value property of FilterChangeIndication must be one of the following: Characteristic.FilterChangeIndication.FILTER_OK = 0; Characteristic.FilterChangeIndication.CHANGE_FILTER = 1; /** * Characteristic "Filter Life Level" */ Characteristic.FilterLifeLevel = function() { Characteristic.call(this, 'Filter Life Level', '000000AB-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100, minValue: 0, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.FilterLifeLevel, Characteristic); Characteristic.FilterLifeLevel.UUID = '000000AB-0000-1000-8000-0026BB765291'; /** * Characteristic "Firmware Revision" */ Characteristic.FirmwareRevision = function() { Characteristic.call(this, 'Firmware Revision', '00000052-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.FirmwareRevision, Characteristic); Characteristic.FirmwareRevision.UUID = '00000052-0000-1000-8000-0026BB765291'; /** * Characteristic "Hardware Revision" */ Characteristic.HardwareRevision = function() { Characteristic.call(this, 'Hardware Revision', '00000053-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.HardwareRevision, Characteristic); Characteristic.HardwareRevision.UUID = '00000053-0000-1000-8000-0026BB765291'; /** * Characteristic "Heating Threshold Temperature" */ Characteristic.HeatingThresholdTemperature = function() { Characteristic.call(this, 'Heating Threshold Temperature', '00000012-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.CELSIUS, maxValue: 25, minValue: 0, minStep: 0.1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.HeatingThresholdTemperature, Characteristic); Characteristic.HeatingThresholdTemperature.UUID = '00000012-0000-1000-8000-0026BB765291'; /** * Characteristic "Hold Position" */ Characteristic.HoldPosition = function() { Characteristic.call(this, 'Hold Position', '0000006F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.HoldPosition, Characteristic); Characteristic.HoldPosition.UUID = '0000006F-0000-1000-8000-0026BB765291'; /** * Characteristic "Hue" */ Characteristic.Hue = function() { Characteristic.call(this, 'Hue', '00000013-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 360, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Hue, Characteristic); Characteristic.Hue.UUID = '00000013-0000-1000-8000-0026BB765291'; /** * Characteristic "Identify" */ Characteristic.Identify = function() { Characteristic.call(this, 'Identify', '00000014-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Identify, Characteristic); Characteristic.Identify.UUID = '00000014-0000-1000-8000-0026BB765291'; /** * Characteristic "Image Mirroring" */ Characteristic.ImageMirroring = function() { Characteristic.call(this, 'Image Mirroring', '0000011F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ImageMirroring, Characteristic); Characteristic.ImageMirroring.UUID = '0000011F-0000-1000-8000-0026BB765291'; /** * Characteristic "Image Rotation" */ Characteristic.ImageRotation = function() { Characteristic.call(this, 'Image Rotation', '0000011E-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 270, minValue: 0, minStep: 90, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ImageRotation, Characteristic); Characteristic.ImageRotation.UUID = '0000011E-0000-1000-8000-0026BB765291'; /** * Characteristic "Leak Detected" */ Characteristic.LeakDetected = function() { Characteristic.call(this, 'Leak Detected', '00000070-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LeakDetected, Characteristic); Characteristic.LeakDetected.UUID = '00000070-0000-1000-8000-0026BB765291'; // The value property of LeakDetected must be one of the following: Characteristic.LeakDetected.LEAK_NOT_DETECTED = 0; Characteristic.LeakDetected.LEAK_DETECTED = 1; /** * Characteristic "Lock Control Point" */ Characteristic.LockControlPoint = function() { Characteristic.call(this, 'Lock Control Point', '00000019-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LockControlPoint, Characteristic); Characteristic.LockControlPoint.UUID = '00000019-0000-1000-8000-0026BB765291'; /** * Characteristic "Lock Current State" */ Characteristic.LockCurrentState = function() { Characteristic.call(this, 'Lock Current State', '0000001D-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LockCurrentState, Characteristic); Characteristic.LockCurrentState.UUID = '0000001D-0000-1000-8000-0026BB765291'; // The value property of LockCurrentState must be one of the following: Characteristic.LockCurrentState.UNSECURED = 0; Characteristic.LockCurrentState.SECURED = 1; Characteristic.LockCurrentState.JAMMED = 2; Characteristic.LockCurrentState.UNKNOWN = 3; /** * Characteristic "Lock Last Known Action" */ Characteristic.LockLastKnownAction = function() { Characteristic.call(this, 'Lock Last Known Action', '0000001C-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LockLastKnownAction, Characteristic); Characteristic.LockLastKnownAction.UUID = '0000001C-0000-1000-8000-0026BB765291'; // The value property of LockLastKnownAction must be one of the following: Characteristic.LockLastKnownAction.SECURED_PHYSICALLY_INTERIOR = 0; Characteristic.LockLastKnownAction.UNSECURED_PHYSICALLY_INTERIOR = 1; Characteristic.LockLastKnownAction.SECURED_PHYSICALLY_EXTERIOR = 2; Characteristic.LockLastKnownAction.UNSECURED_PHYSICALLY_EXTERIOR = 3; Characteristic.LockLastKnownAction.SECURED_BY_KEYPAD = 4; Characteristic.LockLastKnownAction.UNSECURED_BY_KEYPAD = 5; Characteristic.LockLastKnownAction.SECURED_REMOTELY = 6; Characteristic.LockLastKnownAction.UNSECURED_REMOTELY = 7; Characteristic.LockLastKnownAction.SECURED_BY_AUTO_SECURE_TIMEOUT = 8; /** * Characteristic "Lock Management Auto Security Timeout" */ Characteristic.LockManagementAutoSecurityTimeout = function() { Characteristic.call(this, 'Lock Management Auto Security Timeout', '0000001A-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT32, unit: Characteristic.Units.SECONDS, maxValue: 86400, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LockManagementAutoSecurityTimeout, Characteristic); Characteristic.LockManagementAutoSecurityTimeout.UUID = '0000001A-0000-1000-8000-0026BB765291'; /** * Characteristic "Lock Physical Controls" */ Characteristic.LockPhysicalControls = function() { Characteristic.call(this, 'Lock Physical Controls', '000000A7-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LockPhysicalControls, Characteristic); Characteristic.LockPhysicalControls.UUID = '000000A7-0000-1000-8000-0026BB765291'; // The value property of LockPhysicalControls must be one of the following: Characteristic.LockPhysicalControls.CONTROL_LOCK_DISABLED = 0; Characteristic.LockPhysicalControls.CONTROL_LOCK_ENABLED = 1; /** * Characteristic "Lock Target State" */ Characteristic.LockTargetState = function() { Characteristic.call(this, 'Lock Target State', '0000001E-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.LockTargetState, Characteristic); Characteristic.LockTargetState.UUID = '0000001E-0000-1000-8000-0026BB765291'; // The value property of LockTargetState must be one of the following: Characteristic.LockTargetState.UNSECURED = 0; Characteristic.LockTargetState.SECURED = 1; /** * Characteristic "Logs" */ Characteristic.Logs = function() { Characteristic.call(this, 'Logs', '0000001F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Logs, Characteristic); Characteristic.Logs.UUID = '0000001F-0000-1000-8000-0026BB765291'; /** * Characteristic "Manufacturer" */ Characteristic.Manufacturer = function() { Characteristic.call(this, 'Manufacturer', '00000020-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Manufacturer, Characteristic); Characteristic.Manufacturer.UUID = '00000020-0000-1000-8000-0026BB765291'; /** * Characteristic "Model" */ Characteristic.Model = function() { Characteristic.call(this, 'Model', '00000021-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Model, Characteristic); Characteristic.Model.UUID = '00000021-0000-1000-8000-0026BB765291'; /** * Characteristic "Mute" */ Characteristic.Mute = function() { Characteristic.call(this, 'Mute', '0000011A-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Mute, Characteristic); Characteristic.Mute.UUID = '0000011A-0000-1000-8000-0026BB765291'; /** * Characteristic "Motion Detected" */ Characteristic.MotionDetected = function() { Characteristic.call(this, 'Motion Detected', '00000022-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.MotionDetected, Characteristic); Characteristic.MotionDetected.UUID = '00000022-0000-1000-8000-0026BB765291'; /** * Characteristic "Name" */ Characteristic.Name = function() { Characteristic.call(this, 'Name', '00000023-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Name, Characteristic); Characteristic.Name.UUID = '00000023-0000-1000-8000-0026BB765291'; /** * Characteristic "Night Vision" */ Characteristic.NightVision = function() { Characteristic.call(this, 'Night Vision', '0000011B-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.NightVision, Characteristic); Characteristic.NightVision.UUID = '0000011B-0000-1000-8000-0026BB765291'; /** * Characteristic "Nitrogen Dioxide Density" */ Characteristic.NitrogenDioxideDensity = function() { Characteristic.call(this, 'Nitrogen Dioxide Density', '000000C4-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.NitrogenDioxideDensity, Characteristic); Characteristic.NitrogenDioxideDensity.UUID = '000000C4-0000-1000-8000-0026BB765291'; /** * Characteristic "Obstruction Detected" */ Characteristic.ObstructionDetected = function() { Characteristic.call(this, 'Obstruction Detected', '00000024-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ObstructionDetected, Characteristic); Characteristic.ObstructionDetected.UUID = '00000024-0000-1000-8000-0026BB765291'; /** * Characteristic "Occupancy Detected" */ Characteristic.OccupancyDetected = function() { Characteristic.call(this, 'Occupancy Detected', '00000071-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.OccupancyDetected, Characteristic); Characteristic.OccupancyDetected.UUID = '00000071-0000-1000-8000-0026BB765291'; // The value property of OccupancyDetected must be one of the following: Characteristic.OccupancyDetected.OCCUPANCY_NOT_DETECTED = 0; Characteristic.OccupancyDetected.OCCUPANCY_DETECTED = 1; /** * Characteristic "On" */ Characteristic.On = function() { Characteristic.call(this, 'On', '00000025-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.On, Characteristic); Characteristic.On.UUID = '00000025-0000-1000-8000-0026BB765291'; /** * Characteristic "Optical Zoom" */ Characteristic.OpticalZoom = function() { Characteristic.call(this, 'Optical Zoom', '0000011C-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.OpticalZoom, Characteristic); Characteristic.OpticalZoom.UUID = '0000011C-0000-1000-8000-0026BB765291'; /** * Characteristic "Outlet In Use" */ Characteristic.OutletInUse = function() { Characteristic.call(this, 'Outlet In Use', '00000026-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.OutletInUse, Characteristic); Characteristic.OutletInUse.UUID = '00000026-0000-1000-8000-0026BB765291'; /** * Characteristic "Ozone Density" */ Characteristic.OzoneDensity = function() { Characteristic.call(this, 'Ozone Density', '000000C3-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.OzoneDensity, Characteristic); Characteristic.OzoneDensity.UUID = '000000C3-0000-1000-8000-0026BB765291'; /** * Characteristic "Pair Setup" */ Characteristic.PairSetup = function() { Characteristic.call(this, 'Pair Setup', '0000004C-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PairSetup, Characteristic); Characteristic.PairSetup.UUID = '0000004C-0000-1000-8000-0026BB765291'; /** * Characteristic "Pair Verify" */ Characteristic.PairVerify = function() { Characteristic.call(this, 'Pair Verify', '0000004E-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PairVerify, Characteristic); Characteristic.PairVerify.UUID = '0000004E-0000-1000-8000-0026BB765291'; /** * Characteristic "Pairing Features" */ Characteristic.PairingFeatures = function() { Characteristic.call(this, 'Pairing Features', '0000004F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PairingFeatures, Characteristic); Characteristic.PairingFeatures.UUID = '0000004F-0000-1000-8000-0026BB765291'; /** * Characteristic "Pairing Pairings" */ Characteristic.PairingPairings = function() { Characteristic.call(this, 'Pairing Pairings', '00000050-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PairingPairings, Characteristic); Characteristic.PairingPairings.UUID = '00000050-0000-1000-8000-0026BB765291'; /** * Characteristic "PM10 Density" */ Characteristic.PM10Density = function() { Characteristic.call(this, 'PM10 Density', '000000C7-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PM10Density, Characteristic); Characteristic.PM10Density.UUID = '000000C7-0000-1000-8000-0026BB765291'; /** * Characteristic "PM2.5 Density" */ Characteristic.PM2_5Density = function() { Characteristic.call(this, 'PM2.5 Density', '000000C6-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PM2_5Density, Characteristic); Characteristic.PM2_5Density.UUID = '000000C6-0000-1000-8000-0026BB765291'; /** * Characteristic "Position State" */ Characteristic.PositionState = function() { Characteristic.call(this, 'Position State', '00000072-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.PositionState, Characteristic); Characteristic.PositionState.UUID = '00000072-0000-1000-8000-0026BB765291'; // The value property of PositionState must be one of the following: Characteristic.PositionState.DECREASING = 0; Characteristic.PositionState.INCREASING = 1; Characteristic.PositionState.STOPPED = 2; /** * Characteristic "Programmable Switch Event" */ Characteristic.ProgrammableSwitchEvent = function() { Characteristic.call(this, 'Programmable Switch Event', '00000073-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, maxValue: 1, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.eventOnlyCharacteristic = true; this.value = this.getDefaultValue(); }; inherits(Characteristic.ProgrammableSwitchEvent, Characteristic); Characteristic.ProgrammableSwitchEvent.UUID = '00000073-0000-1000-8000-0026BB765291'; // The value property of ProgrammableSwitchEvent must be one of the following: Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS = 0; Characteristic.ProgrammableSwitchEvent.DOUBLE_PRESS = 1; Characteristic.ProgrammableSwitchEvent.LONG_PRESS = 2; /** * Characteristic "Programmable Switch Output State" */ Characteristic.ProgrammableSwitchOutputState = function() { Characteristic.call(this, 'Programmable Switch Output State', '00000074-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, maxValue: 1, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ProgrammableSwitchOutputState, Characteristic); Characteristic.ProgrammableSwitchOutputState.UUID = '00000074-0000-1000-8000-0026BB765291'; /** * Characteristic "Relative Humidity Dehumidifier Threshold" */ Characteristic.RelativeHumidityDehumidifierThreshold = function() { Characteristic.call(this, 'Relative Humidity Dehumidifier Threshold', '000000C9-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.RelativeHumidityDehumidifierThreshold, Characteristic); Characteristic.RelativeHumidityDehumidifierThreshold.UUID = '000000C9-0000-1000-8000-0026BB765291'; /** * Characteristic "Relative Humidity Humidifier Threshold" */ Characteristic.RelativeHumidityHumidifierThreshold = function() { Characteristic.call(this, 'Relative Humidity Humidifier Threshold', '000000CA-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.RelativeHumidityHumidifierThreshold, Characteristic); Characteristic.RelativeHumidityHumidifierThreshold.UUID = '000000CA-0000-1000-8000-0026BB765291'; /** * Characteristic "Reset Filter Indication" */ Characteristic.ResetFilterIndication = function() { Characteristic.call(this, 'Reset Filter Indication', '000000AD-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, maxValue: 1, minValue: 1, minStep: 1, perms: [Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.ResetFilterIndication, Characteristic); Characteristic.ResetFilterIndication.UUID = '000000AD-0000-1000-8000-0026BB765291'; /** * Characteristic "Rotation Direction" */ Characteristic.RotationDirection = function() { Characteristic.call(this, 'Rotation Direction', '00000028-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.RotationDirection, Characteristic); Characteristic.RotationDirection.UUID = '00000028-0000-1000-8000-0026BB765291'; // The value property of RotationDirection must be one of the following: Characteristic.RotationDirection.CLOCKWISE = 0; Characteristic.RotationDirection.COUNTER_CLOCKWISE = 1; /** * Characteristic "Rotation Speed" */ Characteristic.RotationSpeed = function() { Characteristic.call(this, 'Rotation Speed', '00000029-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.RotationSpeed, Characteristic); Characteristic.RotationSpeed.UUID = '00000029-0000-1000-8000-0026BB765291'; /** * Characteristic "Saturation" */ Characteristic.Saturation = function() { Characteristic.call(this, 'Saturation', '0000002F-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Saturation, Characteristic); Characteristic.Saturation.UUID = '0000002F-0000-1000-8000-0026BB765291'; /** * Characteristic "Security System Alarm Type" */ Characteristic.SecuritySystemAlarmType = function() { Characteristic.call(this, 'Security System Alarm Type', '0000008E-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, maxValue: 1, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SecuritySystemAlarmType, Characteristic); Characteristic.SecuritySystemAlarmType.UUID = '0000008E-0000-1000-8000-0026BB765291'; /** * Characteristic "Security System Current State" */ Characteristic.SecuritySystemCurrentState = function() { Characteristic.call(this, 'Security System Current State', '00000066-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SecuritySystemCurrentState, Characteristic); Characteristic.SecuritySystemCurrentState.UUID = '00000066-0000-1000-8000-0026BB765291'; // The value property of SecuritySystemCurrentState must be one of the following: Characteristic.SecuritySystemCurrentState.STAY_ARM = 0; Characteristic.SecuritySystemCurrentState.AWAY_ARM = 1; Characteristic.SecuritySystemCurrentState.NIGHT_ARM = 2; Characteristic.SecuritySystemCurrentState.DISARMED = 3; Characteristic.SecuritySystemCurrentState.ALARM_TRIGGERED = 4; /** * Characteristic "Security System Target State" */ Characteristic.SecuritySystemTargetState = function() { Characteristic.call(this, 'Security System Target State', '00000067-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SecuritySystemTargetState, Characteristic); Characteristic.SecuritySystemTargetState.UUID = '00000067-0000-1000-8000-0026BB765291'; // The value property of SecuritySystemTargetState must be one of the following: Characteristic.SecuritySystemTargetState.STAY_ARM = 0; Characteristic.SecuritySystemTargetState.AWAY_ARM = 1; Characteristic.SecuritySystemTargetState.NIGHT_ARM = 2; Characteristic.SecuritySystemTargetState.DISARM = 3; /** * Characteristic "Selected Stream Configuration" */ Characteristic.SelectedStreamConfiguration = function() { Characteristic.call(this, 'Selected Stream Configuration', '00000117-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SelectedStreamConfiguration, Characteristic); Characteristic.SelectedStreamConfiguration.UUID = '00000117-0000-1000-8000-0026BB765291'; /** * Characteristic "Serial Number" */ Characteristic.SerialNumber = function() { Characteristic.call(this, 'Serial Number', '00000030-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SerialNumber, Characteristic); Characteristic.SerialNumber.UUID = '00000030-0000-1000-8000-0026BB765291'; /** * Characteristic "Setup Endpoints" */ Characteristic.SetupEndpoints = function() { Characteristic.call(this, 'Setup Endpoints', '00000118-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SetupEndpoints, Characteristic); Characteristic.SetupEndpoints.UUID = '00000118-0000-1000-8000-0026BB765291'; /** * Characteristic "Slat Type" */ Characteristic.SlatType = function() { Characteristic.call(this, 'Slat Type', '000000C0-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SlatType, Characteristic); Characteristic.SlatType.UUID = '000000C0-0000-1000-8000-0026BB765291'; // The value property of SlatType must be one of the following: Characteristic.SlatType.HORIZONTAL = 0; Characteristic.SlatType.VERTICAL = 1; /** * Characteristic "Smoke Detected" */ Characteristic.SmokeDetected = function() { Characteristic.call(this, 'Smoke Detected', '00000076-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SmokeDetected, Characteristic); Characteristic.SmokeDetected.UUID = '00000076-0000-1000-8000-0026BB765291'; // The value property of SmokeDetected must be one of the following: Characteristic.SmokeDetected.SMOKE_NOT_DETECTED = 0; Characteristic.SmokeDetected.SMOKE_DETECTED = 1; /** * Characteristic "Software Revision" */ Characteristic.SoftwareRevision = function() { Characteristic.call(this, 'Software Revision', '00000054-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SoftwareRevision, Characteristic); Characteristic.SoftwareRevision.UUID = '00000054-0000-1000-8000-0026BB765291'; /** * Characteristic "Status Active" */ Characteristic.StatusActive = function() { Characteristic.call(this, 'Status Active', '00000075-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.BOOL, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.StatusActive, Characteristic); Characteristic.StatusActive.UUID = '00000075-0000-1000-8000-0026BB765291'; /** * Characteristic "Status Fault" */ Characteristic.StatusFault = function() { Characteristic.call(this, 'Status Fault', '00000077-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.StatusFault, Characteristic); Characteristic.StatusFault.UUID = '00000077-0000-1000-8000-0026BB765291'; // The value property of StatusFault must be one of the following: Characteristic.StatusFault.NO_FAULT = 0; Characteristic.StatusFault.GENERAL_FAULT = 1; /** * Characteristic "Status Jammed" */ Characteristic.StatusJammed = function() { Characteristic.call(this, 'Status Jammed', '00000078-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.StatusJammed, Characteristic); Characteristic.StatusJammed.UUID = '00000078-0000-1000-8000-0026BB765291'; // The value property of StatusJammed must be one of the following: Characteristic.StatusJammed.NOT_JAMMED = 0; Characteristic.StatusJammed.JAMMED = 1; /** * Characteristic "Status Low Battery" */ Characteristic.StatusLowBattery = function() { Characteristic.call(this, 'Status Low Battery', '00000079-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.StatusLowBattery, Characteristic); Characteristic.StatusLowBattery.UUID = '00000079-0000-1000-8000-0026BB765291'; // The value property of StatusLowBattery must be one of the following: Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL = 0; Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW = 1; /** * Characteristic "Status Tampered" */ Characteristic.StatusTampered = function() { Characteristic.call(this, 'Status Tampered', '0000007A-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.StatusTampered, Characteristic); Characteristic.StatusTampered.UUID = '0000007A-0000-1000-8000-0026BB765291'; // The value property of StatusTampered must be one of the following: Characteristic.StatusTampered.NOT_TAMPERED = 0; Characteristic.StatusTampered.TAMPERED = 1; /** * Characteristic "Streaming Status" */ Characteristic.StreamingStatus = function() { Characteristic.call(this, 'Streaming Status', '00000120-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.StreamingStatus, Characteristic); Characteristic.StreamingStatus.UUID = '00000120-0000-1000-8000-0026BB765291'; /** * Characteristic "Sulphur Dioxide Density" */ Characteristic.SulphurDioxideDensity = function() { Characteristic.call(this, 'Sulphur Dioxide Density', '000000C5-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SulphurDioxideDensity, Characteristic); Characteristic.SulphurDioxideDensity.UUID = '000000C5-0000-1000-8000-0026BB765291'; /** * Characteristic "Supported Audio Stream Configuration" */ Characteristic.SupportedAudioStreamConfiguration = function() { Characteristic.call(this, 'Supported Audio Stream Configuration', '00000115-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SupportedAudioStreamConfiguration, Characteristic); Characteristic.SupportedAudioStreamConfiguration.UUID = '00000115-0000-1000-8000-0026BB765291'; /** * Characteristic "Supported RTP Configuration" */ Characteristic.SupportedRTPConfiguration = function() { Characteristic.call(this, 'Supported RTP Configuration', '00000116-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SupportedRTPConfiguration, Characteristic); Characteristic.SupportedRTPConfiguration.UUID = '00000116-0000-1000-8000-0026BB765291'; /** * Characteristic "Supported Video Stream Configuration" */ Characteristic.SupportedVideoStreamConfiguration = function() { Characteristic.call(this, 'Supported Video Stream Configuration', '00000114-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.TLV8, perms: [Characteristic.Perms.READ] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SupportedVideoStreamConfiguration, Characteristic); Characteristic.SupportedVideoStreamConfiguration.UUID = '00000114-0000-1000-8000-0026BB765291'; /** * Characteristic "Swing Mode" */ Characteristic.SwingMode = function() { Characteristic.call(this, 'Swing Mode', '000000B6-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.SwingMode, Characteristic); Characteristic.SwingMode.UUID = '000000B6-0000-1000-8000-0026BB765291'; // The value property of SwingMode must be one of the following: Characteristic.SwingMode.SWING_DISABLED = 0; Characteristic.SwingMode.SWING_ENABLED = 1; /** * Characteristic "Target Air Purifier State" */ Characteristic.TargetAirPurifierState = function() { Characteristic.call(this, 'Target Air Purifier State', '000000A8-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetAirPurifierState, Characteristic); Characteristic.TargetAirPurifierState.UUID = '000000A8-0000-1000-8000-0026BB765291'; // The value property of TargetAirPurifierState must be one of the following: Characteristic.TargetAirPurifierState.MANUAL = 0; Characteristic.TargetAirPurifierState.AUTO = 1; /** * Characteristic "Target Air Quality" */ Characteristic.TargetAirQuality = function() { Characteristic.call(this, 'Target Air Quality', '000000AE-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetAirQuality, Characteristic); Characteristic.TargetAirQuality.UUID = '000000AE-0000-1000-8000-0026BB765291'; // The value property of TargetAirQuality must be one of the following: Characteristic.TargetAirQuality.EXCELLENT = 0; Characteristic.TargetAirQuality.GOOD = 1; Characteristic.TargetAirQuality.FAIR = 2; /** * Characteristic "Target Door State" */ Characteristic.TargetDoorState = function() { Characteristic.call(this, 'Target Door State', '00000032-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetDoorState, Characteristic); Characteristic.TargetDoorState.UUID = '00000032-0000-1000-8000-0026BB765291'; // The value property of TargetDoorState must be one of the following: Characteristic.TargetDoorState.OPEN = 0; Characteristic.TargetDoorState.CLOSED = 1; /** * Characteristic "Target Fan State" */ Characteristic.TargetFanState = function() { Characteristic.call(this, 'Target Fan State', '000000BF-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetFanState, Characteristic); Characteristic.TargetFanState.UUID = '000000BF-0000-1000-8000-0026BB765291'; // The value property of TargetFanState must be one of the following: Characteristic.TargetFanState.MANUAL = 0; Characteristic.TargetFanState.AUTO = 1; /** * Characteristic "Target Heater Cooler State" */ Characteristic.TargetHeaterCoolerState = function() { Characteristic.call(this, 'Target Heater Cooler State', '000000B2-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetHeaterCoolerState, Characteristic); Characteristic.TargetHeaterCoolerState.UUID = '000000B2-0000-1000-8000-0026BB765291'; // The value property of TargetHeaterCoolerState must be one of the following: Characteristic.TargetHeaterCoolerState.AUTO = 0; Characteristic.TargetHeaterCoolerState.HEAT = 1; Characteristic.TargetHeaterCoolerState.COOL = 2; /** * Characteristic "Target Heating Cooling State" */ Characteristic.TargetHeatingCoolingState = function() { Characteristic.call(this, 'Target Heating Cooling State', '00000033-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetHeatingCoolingState, Characteristic); Characteristic.TargetHeatingCoolingState.UUID = '00000033-0000-1000-8000-0026BB765291'; // The value property of TargetHeatingCoolingState must be one of the following: Characteristic.TargetHeatingCoolingState.OFF = 0; Characteristic.TargetHeatingCoolingState.HEAT = 1; Characteristic.TargetHeatingCoolingState.COOL = 2; Characteristic.TargetHeatingCoolingState.AUTO = 3; /** * Characteristic "Target Horizontal Tilt Angle" */ Characteristic.TargetHorizontalTiltAngle = function() { Characteristic.call(this, 'Target Horizontal Tilt Angle', '0000007B-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 90, minValue: -90, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetHorizontalTiltAngle, Characteristic); Characteristic.TargetHorizontalTiltAngle.UUID = '0000007B-0000-1000-8000-0026BB765291'; /** * Characteristic "Target Humidifier Dehumidifier State" */ Characteristic.TargetHumidifierDehumidifierState = function() { Characteristic.call(this, 'Target Humidifier Dehumidifier State', '000000B4-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetHumidifierDehumidifierState, Characteristic); Characteristic.TargetHumidifierDehumidifierState.UUID = '000000B4-0000-1000-8000-0026BB765291'; // The value property of TargetHumidifierDehumidifierState must be one of the following: Characteristic.TargetHumidifierDehumidifierState.AUTO = 0; Characteristic.TargetHumidifierDehumidifierState.HUMIDIFIER = 1; Characteristic.TargetHumidifierDehumidifierState.DEHUMIDIFIER = 2; /** * Characteristic "Target Position" */ Characteristic.TargetPosition = function() { Characteristic.call(this, 'Target Position', '0000007C-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetPosition, Characteristic); Characteristic.TargetPosition.UUID = '0000007C-0000-1000-8000-0026BB765291'; /** * Characteristic "Target Relative Humidity" */ Characteristic.TargetRelativeHumidity = function() { Characteristic.call(this, 'Target Relative Humidity', '00000034-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetRelativeHumidity, Characteristic); Characteristic.TargetRelativeHumidity.UUID = '00000034-0000-1000-8000-0026BB765291'; /** * Characteristic "Target Slat State" */ Characteristic.TargetSlatState = function() { Characteristic.call(this, 'Target Slat State', '000000BE-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetSlatState, Characteristic); Characteristic.TargetSlatState.UUID = '000000BE-0000-1000-8000-0026BB765291'; // The value property of TargetSlatState must be one of the following: Characteristic.TargetSlatState.MANUAL = 0; Characteristic.TargetSlatState.AUTO = 1; /** * Characteristic "Target Temperature" */ Characteristic.TargetTemperature = function() { Characteristic.call(this, 'Target Temperature', '00000035-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.CELSIUS, maxValue: 38, minValue: 10, minStep: 0.1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetTemperature, Characteristic); Characteristic.TargetTemperature.UUID = '00000035-0000-1000-8000-0026BB765291'; /** * Characteristic "Target Tilt Angle" */ Characteristic.TargetTiltAngle = function() { Characteristic.call(this, 'Target Tilt Angle', '000000C2-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 90, minValue: -90, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetTiltAngle, Characteristic); Characteristic.TargetTiltAngle.UUID = '000000C2-0000-1000-8000-0026BB765291'; /** * Characteristic "Target Vertical Tilt Angle" */ Characteristic.TargetVerticalTiltAngle = function() { Characteristic.call(this, 'Target Vertical Tilt Angle', '0000007D-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.INT, unit: Characteristic.Units.ARC_DEGREE, maxValue: 90, minValue: -90, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TargetVerticalTiltAngle, Characteristic); Characteristic.TargetVerticalTiltAngle.UUID = '0000007D-0000-1000-8000-0026BB765291'; /** * Characteristic "Temperature Display Units" */ Characteristic.TemperatureDisplayUnits = function() { Characteristic.call(this, 'Temperature Display Units', '00000036-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.UINT8, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.TemperatureDisplayUnits, Characteristic); Characteristic.TemperatureDisplayUnits.UUID = '00000036-0000-1000-8000-0026BB765291'; // The value property of TemperatureDisplayUnits must be one of the following: Characteristic.TemperatureDisplayUnits.CELSIUS = 0; Characteristic.TemperatureDisplayUnits.FAHRENHEIT = 1; /** * Characteristic "Version" */ Characteristic.Version = function() { Characteristic.call(this, 'Version', '00000037-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.STRING, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Version, Characteristic); Characteristic.Version.UUID = '00000037-0000-1000-8000-0026BB765291'; /** * Characteristic "VOC Density" */ Characteristic.VOCDensity = function() { Characteristic.call(this, 'VOC Density', '000000C8-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 1000, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.VOCDensity, Characteristic); Characteristic.VOCDensity.UUID = '000000C8-0000-1000-8000-0026BB765291'; /** * Characteristic "Volume" */ Characteristic.Volume = function() { Characteristic.call(this, 'Volume', '00000119-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, unit: Characteristic.Units.PERCENTAGE, maxValue: 100, minValue: 0, minStep: 1, perms: [Characteristic.Perms.READ, Characteristic.Perms.WRITE, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.Volume, Characteristic); Characteristic.Volume.UUID = '00000119-0000-1000-8000-0026BB765291'; /** * Characteristic "Water Level" */ Characteristic.WaterLevel = function() { Characteristic.call(this, 'Water Level', '000000B5-0000-1000-8000-0026BB765291'); this.setProps({ format: Characteristic.Formats.FLOAT, maxValue: 100, minValue: 0, perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY] }); this.value = this.getDefaultValue(); }; inherits(Characteristic.WaterLevel, Characteristic); Characteristic.WaterLevel.UUID = '000000B5-0000-1000-8000-0026BB765291'; /** * Service "Label" */ Service.Label = function(displayName, subtype) { Service.call(this, displayName, '000000CC-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.LabelNamespace); }; inherits(Service.Label, Service); Service.Label.UUID = '000000CC-0000-1000-8000-0026BB765291'; /** * Service "Accessory Information" */ Service.AccessoryInformation = function(displayName, subtype) { Service.call(this, displayName, '0000003E-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.Identify); this.addCharacteristic(Characteristic.Manufacturer); this.addCharacteristic(Characteristic.Model); this.addCharacteristic(Characteristic.Name); this.addCharacteristic(Characteristic.SerialNumber); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.FirmwareRevision); this.addOptionalCharacteristic(Characteristic.HardwareRevision); this.addOptionalCharacteristic(Characteristic.SoftwareRevision); this.addOptionalCharacteristic(Characteristic.AccessoryFlags); this.addOptionalCharacteristic(Characteristic.AppMatchingIdentifier); }; inherits(Service.AccessoryInformation, Service); Service.AccessoryInformation.UUID = '0000003E-0000-1000-8000-0026BB765291'; /** * Service "Air Purifier" */ Service.AirPurifier = function(displayName, subtype) { Service.call(this, displayName, '000000BB-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.Active); this.addCharacteristic(Characteristic.CurrentAirPurifierState); this.addCharacteristic(Characteristic.TargetAirPurifierState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.LockPhysicalControls); this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.SwingMode); this.addOptionalCharacteristic(Characteristic.RotationSpeed); }; inherits(Service.AirPurifier, Service); Service.AirPurifier.UUID = '000000BB-0000-1000-8000-0026BB765291'; /** * Service "Air Quality Sensor" */ Service.AirQualitySensor = function(displayName, subtype) { Service.call(this, displayName, '0000008D-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.AirQuality); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.OzoneDensity); this.addOptionalCharacteristic(Characteristic.NitrogenDioxideDensity); this.addOptionalCharacteristic(Characteristic.SulphurDioxideDensity); this.addOptionalCharacteristic(Characteristic.PM2_5Density); this.addOptionalCharacteristic(Characteristic.PM10Density); this.addOptionalCharacteristic(Characteristic.VOCDensity); this.addOptionalCharacteristic(Characteristic.CarbonMonoxideLevel); this.addOptionalCharacteristic(Characteristic.CarbonDioxideLevel); }; inherits(Service.AirQualitySensor, Service); Service.AirQualitySensor.UUID = '0000008D-0000-1000-8000-0026BB765291'; /** * Service "Battery Service" */ Service.BatteryService = function(displayName, subtype) { Service.call(this, displayName, '00000096-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.BatteryLevel); this.addCharacteristic(Characteristic.ChargingState); this.addCharacteristic(Characteristic.StatusLowBattery); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.BatteryService, Service); Service.BatteryService.UUID = '00000096-0000-1000-8000-0026BB765291'; /** * Service "Camera Control" */ Service.CameraControl = function(displayName, subtype) { Service.call(this, displayName, '00000111-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.On); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.CurrentHorizontalTiltAngle); this.addOptionalCharacteristic(Characteristic.CurrentVerticalTiltAngle); this.addOptionalCharacteristic(Characteristic.TargetHorizontalTiltAngle); this.addOptionalCharacteristic(Characteristic.TargetVerticalTiltAngle); this.addOptionalCharacteristic(Characteristic.NightVision); this.addOptionalCharacteristic(Characteristic.OpticalZoom); this.addOptionalCharacteristic(Characteristic.DigitalZoom); this.addOptionalCharacteristic(Characteristic.ImageRotation); this.addOptionalCharacteristic(Characteristic.ImageMirroring); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.CameraControl, Service); Service.CameraControl.UUID = '00000111-0000-1000-8000-0026BB765291'; /** * Service "Camera RTP Stream Management" */ Service.CameraRTPStreamManagement = function(displayName, subtype) { Service.call(this, displayName, '00000110-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.SupportedVideoStreamConfiguration); this.addCharacteristic(Characteristic.SupportedAudioStreamConfiguration); this.addCharacteristic(Characteristic.SupportedRTPConfiguration); this.addCharacteristic(Characteristic.SelectedStreamConfiguration); this.addCharacteristic(Characteristic.StreamingStatus); this.addCharacteristic(Characteristic.SetupEndpoints); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.CameraRTPStreamManagement, Service); Service.CameraRTPStreamManagement.UUID = '00000110-0000-1000-8000-0026BB765291'; /** * Service "Carbon Dioxide Sensor" */ Service.CarbonDioxideSensor = function(displayName, subtype) { Service.call(this, displayName, '00000097-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CarbonDioxideDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.CarbonDioxideLevel); this.addOptionalCharacteristic(Characteristic.CarbonDioxidePeakLevel); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.CarbonDioxideSensor, Service); Service.CarbonDioxideSensor.UUID = '00000097-0000-1000-8000-0026BB765291'; /** * Service "Carbon Monoxide Sensor" */ Service.CarbonMonoxideSensor = function(displayName, subtype) { Service.call(this, displayName, '0000007F-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CarbonMonoxideDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.CarbonMonoxideLevel); this.addOptionalCharacteristic(Characteristic.CarbonMonoxidePeakLevel); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.CarbonMonoxideSensor, Service); Service.CarbonMonoxideSensor.UUID = '0000007F-0000-1000-8000-0026BB765291'; /** * Service "Contact Sensor" */ Service.ContactSensor = function(displayName, subtype) { Service.call(this, displayName, '00000080-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.ContactSensorState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.ContactSensor, Service); Service.ContactSensor.UUID = '00000080-0000-1000-8000-0026BB765291'; /** * Service "Door" */ Service.Door = function(displayName, subtype) { Service.call(this, displayName, '00000081-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentPosition); this.addCharacteristic(Characteristic.PositionState); this.addCharacteristic(Characteristic.TargetPosition); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.HoldPosition); this.addOptionalCharacteristic(Characteristic.ObstructionDetected); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Door, Service); Service.Door.UUID = '00000081-0000-1000-8000-0026BB765291'; /** * Service "Doorbell" */ Service.Doorbell = function(displayName, subtype) { Service.call(this, displayName, '00000121-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.ProgrammableSwitchEvent); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Brightness); this.addOptionalCharacteristic(Characteristic.Volume); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Doorbell, Service); Service.Doorbell.UUID = '00000121-0000-1000-8000-0026BB765291'; /** * Service "Fan" */ Service.Fan = function(displayName, subtype) { Service.call(this, displayName, '00000040-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.On); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.RotationDirection); this.addOptionalCharacteristic(Characteristic.RotationSpeed); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Fan, Service); Service.Fan.UUID = '00000040-0000-1000-8000-0026BB765291'; /** * Service "Fan v2" */ Service.Fanv2 = function(displayName, subtype) { Service.call(this, displayName, '000000B7-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.Active); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.CurrentFanState); this.addOptionalCharacteristic(Characteristic.TargetFanState); this.addOptionalCharacteristic(Characteristic.LockPhysicalControls); this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.RotationDirection); this.addOptionalCharacteristic(Characteristic.RotationSpeed); this.addOptionalCharacteristic(Characteristic.SwingMode); }; inherits(Service.Fanv2, Service); Service.Fanv2.UUID = '000000B7-0000-1000-8000-0026BB765291'; /** * Service "Filter Maintenance" */ Service.FilterMaintenance = function(displayName, subtype) { Service.call(this, displayName, '000000BA-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.FilterChangeIndication); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.FilterLifeLevel); this.addOptionalCharacteristic(Characteristic.ResetFilterIndication); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.FilterMaintenance, Service); Service.FilterMaintenance.UUID = '000000BA-0000-1000-8000-0026BB765291'; /** * Service "Garage Door Opener" */ Service.GarageDoorOpener = function(displayName, subtype) { Service.call(this, displayName, '00000041-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentDoorState); this.addCharacteristic(Characteristic.TargetDoorState); this.addCharacteristic(Characteristic.ObstructionDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.LockCurrentState); this.addOptionalCharacteristic(Characteristic.LockTargetState); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.GarageDoorOpener, Service); Service.GarageDoorOpener.UUID = '00000041-0000-1000-8000-0026BB765291'; /** * Service "Heater Cooler" */ Service.HeaterCooler = function(displayName, subtype) { Service.call(this, displayName, '000000BC-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.Active); this.addCharacteristic(Characteristic.CurrentHeaterCoolerState); this.addCharacteristic(Characteristic.TargetHeaterCoolerState); this.addCharacteristic(Characteristic.CurrentTemperature); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.LockPhysicalControls); this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.SwingMode); this.addOptionalCharacteristic(Characteristic.CoolingThresholdTemperature); this.addOptionalCharacteristic(Characteristic.HeatingThresholdTemperature); this.addOptionalCharacteristic(Characteristic.TemperatureDisplayUnits); this.addOptionalCharacteristic(Characteristic.RotationSpeed); }; inherits(Service.HeaterCooler, Service); Service.HeaterCooler.UUID = '000000BC-0000-1000-8000-0026BB765291'; /** * Service "Humidifier Dehumidifier" */ Service.HumidifierDehumidifier = function(displayName, subtype) { Service.call(this, displayName, '000000BD-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentRelativeHumidity); this.addCharacteristic(Characteristic.CurrentHumidifierDehumidifierState); this.addCharacteristic(Characteristic.TargetHumidifierDehumidifierState); this.addCharacteristic(Characteristic.Active); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.LockPhysicalControls); this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.SwingMode); this.addOptionalCharacteristic(Characteristic.WaterLevel); this.addOptionalCharacteristic(Characteristic.RelativeHumidityDehumidifierThreshold); this.addOptionalCharacteristic(Characteristic.RelativeHumidityHumidifierThreshold); this.addOptionalCharacteristic(Characteristic.RotationSpeed); }; inherits(Service.HumidifierDehumidifier, Service); Service.HumidifierDehumidifier.UUID = '000000BD-0000-1000-8000-0026BB765291'; /** * Service "Humidity Sensor" */ Service.HumiditySensor = function(displayName, subtype) { Service.call(this, displayName, '00000082-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentRelativeHumidity); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.HumiditySensor, Service); Service.HumiditySensor.UUID = '00000082-0000-1000-8000-0026BB765291'; /** * Service "Leak Sensor" */ Service.LeakSensor = function(displayName, subtype) { Service.call(this, displayName, '00000083-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.LeakDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.LeakSensor, Service); Service.LeakSensor.UUID = '00000083-0000-1000-8000-0026BB765291'; /** * Service "Light Sensor" */ Service.LightSensor = function(displayName, subtype) { Service.call(this, displayName, '00000084-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentAmbientLightLevel); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.LightSensor, Service); Service.LightSensor.UUID = '00000084-0000-1000-8000-0026BB765291'; /** * Service "Lightbulb" */ Service.Lightbulb = function(displayName, subtype) { Service.call(this, displayName, '00000043-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.On); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Brightness); this.addOptionalCharacteristic(Characteristic.Hue); this.addOptionalCharacteristic(Characteristic.Saturation); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Lightbulb, Service); Service.Lightbulb.UUID = '00000043-0000-1000-8000-0026BB765291'; /** * Service "Lock Management" */ Service.LockManagement = function(displayName, subtype) { Service.call(this, displayName, '00000044-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.LockControlPoint); this.addCharacteristic(Characteristic.Version); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Logs); this.addOptionalCharacteristic(Characteristic.AudioFeedback); this.addOptionalCharacteristic(Characteristic.LockManagementAutoSecurityTimeout); this.addOptionalCharacteristic(Characteristic.AdministratorOnlyAccess); this.addOptionalCharacteristic(Characteristic.LockLastKnownAction); this.addOptionalCharacteristic(Characteristic.CurrentDoorState); this.addOptionalCharacteristic(Characteristic.MotionDetected); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.LockManagement, Service); Service.LockManagement.UUID = '00000044-0000-1000-8000-0026BB765291'; /** * Service "Lock Mechanism" */ Service.LockMechanism = function(displayName, subtype) { Service.call(this, displayName, '00000045-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.LockCurrentState); this.addCharacteristic(Characteristic.LockTargetState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.LockMechanism, Service); Service.LockMechanism.UUID = '00000045-0000-1000-8000-0026BB765291'; /** * Service "Microphone" */ Service.Microphone = function(displayName, subtype) { Service.call(this, displayName, '00000112-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.Mute); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Volume); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Microphone, Service); Service.Microphone.UUID = '00000112-0000-1000-8000-0026BB765291'; /** * Service "Motion Sensor" */ Service.MotionSensor = function(displayName, subtype) { Service.call(this, displayName, '00000085-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.MotionDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.MotionSensor, Service); Service.MotionSensor.UUID = '00000085-0000-1000-8000-0026BB765291'; /** * Service "Occupancy Sensor" */ Service.OccupancySensor = function(displayName, subtype) { Service.call(this, displayName, '00000086-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.OccupancyDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.OccupancySensor, Service); Service.OccupancySensor.UUID = '00000086-0000-1000-8000-0026BB765291'; /** * Service "Outlet" */ Service.Outlet = function(displayName, subtype) { Service.call(this, displayName, '00000047-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.On); this.addCharacteristic(Characteristic.OutletInUse); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Outlet, Service); Service.Outlet.UUID = '00000047-0000-1000-8000-0026BB765291'; /** * Service "Security System" */ Service.SecuritySystem = function(displayName, subtype) { Service.call(this, displayName, '0000007E-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.SecuritySystemCurrentState); this.addCharacteristic(Characteristic.SecuritySystemTargetState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.SecuritySystemAlarmType); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.SecuritySystem, Service); Service.SecuritySystem.UUID = '0000007E-0000-1000-8000-0026BB765291'; /** * Service "Slat" */ Service.Slat = function(displayName, subtype) { Service.call(this, displayName, '000000B9-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.SlatType); this.addCharacteristic(Characteristic.CurrentSlatState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.CurrentTiltAngle); this.addOptionalCharacteristic(Characteristic.TargetTiltAngle); this.addOptionalCharacteristic(Characteristic.SwingMode); }; inherits(Service.Slat, Service); Service.Slat.UUID = '000000B9-0000-1000-8000-0026BB765291'; /** * Service "Smoke Sensor" */ Service.SmokeSensor = function(displayName, subtype) { Service.call(this, displayName, '00000087-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.SmokeDetected); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.SmokeSensor, Service); Service.SmokeSensor.UUID = '00000087-0000-1000-8000-0026BB765291'; /** * Service "Speaker" */ Service.Speaker = function(displayName, subtype) { Service.call(this, displayName, '00000113-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.Mute); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Volume); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Speaker, Service); Service.Speaker.UUID = '00000113-0000-1000-8000-0026BB765291'; /** * Service "Stateful Programmable Switch" */ Service.StatefulProgrammableSwitch = function(displayName, subtype) { Service.call(this, displayName, '00000088-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.ProgrammableSwitchEvent); this.addCharacteristic(Characteristic.ProgrammableSwitchOutputState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.StatefulProgrammableSwitch, Service); Service.StatefulProgrammableSwitch.UUID = '00000088-0000-1000-8000-0026BB765291'; /** * Service "Stateless Programmable Switch" */ Service.StatelessProgrammableSwitch = function(displayName, subtype) { Service.call(this, displayName, '00000089-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.ProgrammableSwitchEvent); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); this.addOptionalCharacteristic(Characteristic.LabelIndex); }; inherits(Service.StatelessProgrammableSwitch, Service); Service.StatelessProgrammableSwitch.UUID = '00000089-0000-1000-8000-0026BB765291'; /** * Service "Switch" */ Service.Switch = function(displayName, subtype) { Service.call(this, displayName, '00000049-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.On); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Switch, Service); Service.Switch.UUID = '00000049-0000-1000-8000-0026BB765291'; /** * Service "Temperature Sensor" */ Service.TemperatureSensor = function(displayName, subtype) { Service.call(this, displayName, '0000008A-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentTemperature); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.StatusActive); this.addOptionalCharacteristic(Characteristic.StatusFault); this.addOptionalCharacteristic(Characteristic.StatusLowBattery); this.addOptionalCharacteristic(Characteristic.StatusTampered); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.TemperatureSensor, Service); Service.TemperatureSensor.UUID = '0000008A-0000-1000-8000-0026BB765291'; /** * Service "Thermostat" */ Service.Thermostat = function(displayName, subtype) { Service.call(this, displayName, '0000004A-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentHeatingCoolingState); this.addCharacteristic(Characteristic.TargetHeatingCoolingState); this.addCharacteristic(Characteristic.CurrentTemperature); this.addCharacteristic(Characteristic.TargetTemperature); this.addCharacteristic(Characteristic.TemperatureDisplayUnits); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.CurrentRelativeHumidity); this.addOptionalCharacteristic(Characteristic.TargetRelativeHumidity); this.addOptionalCharacteristic(Characteristic.CoolingThresholdTemperature); this.addOptionalCharacteristic(Characteristic.HeatingThresholdTemperature); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Thermostat, Service); Service.Thermostat.UUID = '0000004A-0000-1000-8000-0026BB765291'; /** * Service "Window" */ Service.Window = function(displayName, subtype) { Service.call(this, displayName, '0000008B-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentPosition); this.addCharacteristic(Characteristic.TargetPosition); this.addCharacteristic(Characteristic.PositionState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.HoldPosition); this.addOptionalCharacteristic(Characteristic.ObstructionDetected); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.Window, Service); Service.Window.UUID = '0000008B-0000-1000-8000-0026BB765291'; /** * Service "Window Covering" */ Service.WindowCovering = function(displayName, subtype) { Service.call(this, displayName, '0000008C-0000-1000-8000-0026BB765291', subtype); // Required Characteristics this.addCharacteristic(Characteristic.CurrentPosition); this.addCharacteristic(Characteristic.TargetPosition); this.addCharacteristic(Characteristic.PositionState); // Optional Characteristics this.addOptionalCharacteristic(Characteristic.HoldPosition); this.addOptionalCharacteristic(Characteristic.TargetHorizontalTiltAngle); this.addOptionalCharacteristic(Characteristic.TargetVerticalTiltAngle); this.addOptionalCharacteristic(Characteristic.CurrentHorizontalTiltAngle); this.addOptionalCharacteristic(Characteristic.CurrentVerticalTiltAngle); this.addOptionalCharacteristic(Characteristic.ObstructionDetected); this.addOptionalCharacteristic(Characteristic.Name); }; inherits(Service.WindowCovering, Service); Service.WindowCovering.UUID = '0000008C-0000-1000-8000-0026BB765291'; var HomeKitTypesBridge = require('./HomeKitTypes-Bridge');
pantonante/parsec-node
lib/gen/HomeKitTypes.js
JavaScript
apache-2.0
104,246
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.observable; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import java.io.IOException; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.atomic.*; import org.junit.*; import org.mockito.*; import io.reactivex.*; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.disposables.*; import io.reactivex.exceptions.*; import io.reactivex.functions.*; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.Functions; import io.reactivex.internal.operators.observable.ObservableBuffer.BufferExactObserver; import io.reactivex.internal.operators.observable.ObservableBufferBoundarySupplier.BufferBoundarySupplierObserver; import io.reactivex.internal.operators.observable.ObservableBufferTimed.*; import io.reactivex.observers.*; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.*; import io.reactivex.subjects.*; public class ObservableBufferTest { private Observer<List<String>> observer; private TestScheduler scheduler; private Scheduler.Worker innerScheduler; @Before public void before() { observer = TestHelper.mockObserver(); scheduler = new TestScheduler(); innerScheduler = scheduler.createWorker(); } @Test public void testComplete() { Observable<String> source = Observable.empty(); Observable<List<String>> buffered = source.buffer(3, 3); buffered.subscribe(observer); Mockito.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); Mockito.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); Mockito.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testSkipAndCountOverlappingBuffers() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); observer.onNext("one"); observer.onNext("two"); observer.onNext("three"); observer.onNext("four"); observer.onNext("five"); } }); Observable<List<String>> buffered = source.buffer(3, 1); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two", "three")); inOrder.verify(observer, Mockito.times(1)).onNext(list("two", "three", "four")); inOrder.verify(observer, Mockito.times(1)).onNext(list("three", "four", "five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.never()).onComplete(); } @Test public void testSkipAndCountGaplessBuffers() { Observable<String> source = Observable.just("one", "two", "three", "four", "five"); Observable<List<String>> buffered = source.buffer(3, 3); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two", "three")); inOrder.verify(observer, Mockito.times(1)).onNext(list("four", "five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testSkipAndCountBuffersWithGaps() { Observable<String> source = Observable.just("one", "two", "three", "four", "five"); Observable<List<String>> buffered = source.buffer(2, 3); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two")); inOrder.verify(observer, Mockito.times(1)).onNext(list("four", "five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testTimedAndCount() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); push(observer, "one", 10); push(observer, "two", 90); push(observer, "three", 110); push(observer, "four", 190); push(observer, "five", 210); complete(observer, 250); } }); Observable<List<String>> buffered = source.buffer(100, TimeUnit.MILLISECONDS, scheduler, 2); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); scheduler.advanceTimeTo(100, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two")); scheduler.advanceTimeTo(200, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("three", "four")); scheduler.advanceTimeTo(300, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testTimed() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); push(observer, "one", 97); push(observer, "two", 98); /** * Changed from 100. Because scheduling the cut to 100ms happens before this * Observable even runs due how lift works, pushing at 100ms would execute after the * buffer cut. */ push(observer, "three", 99); push(observer, "four", 101); push(observer, "five", 102); complete(observer, 150); } }); Observable<List<String>> buffered = source.buffer(100, TimeUnit.MILLISECONDS, scheduler); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); scheduler.advanceTimeTo(101, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two", "three")); scheduler.advanceTimeTo(201, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("four", "five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testObservableBasedOpenerAndCloser() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); push(observer, "one", 10); push(observer, "two", 60); push(observer, "three", 110); push(observer, "four", 160); push(observer, "five", 210); complete(observer, 500); } }); Observable<Object> openings = Observable.unsafeCreate(new ObservableSource<Object>() { @Override public void subscribe(Observer<Object> observer) { observer.onSubscribe(Disposables.empty()); push(observer, new Object(), 50); push(observer, new Object(), 200); complete(observer, 250); } }); Function<Object, Observable<Object>> closer = new Function<Object, Observable<Object>>() { @Override public Observable<Object> apply(Object opening) { return Observable.unsafeCreate(new ObservableSource<Object>() { @Override public void subscribe(Observer<? super Object> observer) { observer.onSubscribe(Disposables.empty()); push(observer, new Object(), 100); complete(observer, 101); } }); } }; Observable<List<String>> buffered = source.buffer(openings, closer); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("two", "three")); inOrder.verify(observer, Mockito.times(1)).onNext(list("five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testObservableBasedCloser() { Observable<String> source = Observable.unsafeCreate(new ObservableSource<String>() { @Override public void subscribe(Observer<? super String> observer) { observer.onSubscribe(Disposables.empty()); push(observer, "one", 10); push(observer, "two", 60); push(observer, "three", 110); push(observer, "four", 160); push(observer, "five", 210); complete(observer, 250); } }); Callable<Observable<Object>> closer = new Callable<Observable<Object>>() { @Override public Observable<Object> call() { return Observable.unsafeCreate(new ObservableSource<Object>() { @Override public void subscribe(Observer<? super Object> observer) { observer.onSubscribe(Disposables.empty()); push(observer, new Object(), 100); push(observer, new Object(), 200); push(observer, new Object(), 300); complete(observer, 301); } }); } }; Observable<List<String>> buffered = source.buffer(closer); buffered.subscribe(observer); InOrder inOrder = Mockito.inOrder(observer); scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); inOrder.verify(observer, Mockito.times(1)).onNext(list("one", "two")); inOrder.verify(observer, Mockito.times(1)).onNext(list("three", "four")); inOrder.verify(observer, Mockito.times(1)).onNext(list("five")); inOrder.verify(observer, Mockito.never()).onNext(Mockito.<String>anyList()); inOrder.verify(observer, Mockito.never()).onError(Mockito.any(Throwable.class)); inOrder.verify(observer, Mockito.times(1)).onComplete(); } @Test public void testLongTimeAction() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); LongTimeAction action = new LongTimeAction(latch); Observable.just(1).buffer(10, TimeUnit.MILLISECONDS, 10) .subscribe(action); latch.await(); assertFalse(action.fail); } private static class LongTimeAction implements Consumer<List<Integer>> { CountDownLatch latch; boolean fail; LongTimeAction(CountDownLatch latch) { this.latch = latch; } @Override public void accept(List<Integer> t1) { try { if (fail) { return; } Thread.sleep(200); } catch (InterruptedException e) { fail = true; } finally { latch.countDown(); } } } private List<String> list(String... args) { List<String> list = new ArrayList<String>(); for (String arg : args) { list.add(arg); } return list; } private <T> void push(final Observer<T> observer, final T value, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { observer.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } private void complete(final Observer<?> observer, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { observer.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } @Test public void testBufferStopsWhenUnsubscribed1() { Observable<Integer> source = Observable.never(); Observer<List<Integer>> o = TestHelper.mockObserver(); TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(o); source.buffer(100, 200, TimeUnit.MILLISECONDS, scheduler) .doOnNext(new Consumer<List<Integer>>() { @Override public void accept(List<Integer> pv) { System.out.println(pv); } }) .subscribe(to); InOrder inOrder = Mockito.inOrder(o); scheduler.advanceTimeBy(1001, TimeUnit.MILLISECONDS); inOrder.verify(o, times(5)).onNext(Arrays.<Integer> asList()); to.dispose(); scheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS); inOrder.verifyNoMoreInteractions(); } @Test public void bufferWithBONormal1() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = Mockito.inOrder(o); source.buffer(boundary).subscribe(o); source.onNext(1); source.onNext(2); source.onNext(3); boundary.onNext(1); inOrder.verify(o, times(1)).onNext(Arrays.asList(1, 2, 3)); source.onNext(4); source.onNext(5); boundary.onNext(2); inOrder.verify(o, times(1)).onNext(Arrays.asList(4, 5)); source.onNext(6); boundary.onComplete(); inOrder.verify(o, times(1)).onNext(Arrays.asList(6)); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOEmptyLastViaBoundary() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = Mockito.inOrder(o); source.buffer(boundary).subscribe(o); boundary.onComplete(); inOrder.verify(o, times(1)).onNext(Arrays.asList()); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOEmptyLastViaSource() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = Mockito.inOrder(o); source.buffer(boundary).subscribe(o); source.onComplete(); inOrder.verify(o, times(1)).onNext(Arrays.asList()); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOEmptyLastViaBoth() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = Mockito.inOrder(o); source.buffer(boundary).subscribe(o); source.onComplete(); boundary.onComplete(); inOrder.verify(o, times(1)).onNext(Arrays.asList()); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOSourceThrows() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); source.buffer(boundary).subscribe(o); source.onNext(1); source.onError(new TestException()); verify(o).onError(any(TestException.class)); verify(o, never()).onComplete(); verify(o, never()).onNext(any()); } @Test public void bufferWithBOBoundaryThrows() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> boundary = PublishSubject.create(); Observer<Object> o = TestHelper.mockObserver(); source.buffer(boundary).subscribe(o); source.onNext(1); boundary.onError(new TestException()); verify(o).onError(any(TestException.class)); verify(o, never()).onComplete(); verify(o, never()).onNext(any()); } @Test(timeout = 2000) public void bufferWithSizeTake1() { Observable<Integer> source = Observable.just(1).repeat(); Observable<List<Integer>> result = source.buffer(2).take(1); Observer<Object> o = TestHelper.mockObserver(); result.subscribe(o); verify(o).onNext(Arrays.asList(1, 1)); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithSizeSkipTake1() { Observable<Integer> source = Observable.just(1).repeat(); Observable<List<Integer>> result = source.buffer(2, 3).take(1); Observer<Object> o = TestHelper.mockObserver(); result.subscribe(o); verify(o).onNext(Arrays.asList(1, 1)); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithTimeTake1() { Observable<Long> source = Observable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Observable<List<Long>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler).take(1); Observer<Object> o = TestHelper.mockObserver(); result.subscribe(o); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); verify(o).onNext(Arrays.asList(0L, 1L)); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithTimeSkipTake2() { Observable<Long> source = Observable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Observable<List<Long>> result = source.buffer(100, 60, TimeUnit.MILLISECONDS, scheduler).take(2); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); result.subscribe(o); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(o).onNext(Arrays.asList(0L, 1L)); inOrder.verify(o).onNext(Arrays.asList(1L, 2L)); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithBoundaryTake2() { Observable<Long> boundary = Observable.interval(60, 60, TimeUnit.MILLISECONDS, scheduler); Observable<Long> source = Observable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Observable<List<Long>> result = source.buffer(boundary).take(2); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); result.subscribe(o); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(o).onNext(Arrays.asList(0L)); inOrder.verify(o).onNext(Arrays.asList(1L)); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test(timeout = 2000) public void bufferWithStartEndBoundaryTake2() { Observable<Long> start = Observable.interval(61, 61, TimeUnit.MILLISECONDS, scheduler); Function<Long, Observable<Long>> end = new Function<Long, Observable<Long>>() { @Override public Observable<Long> apply(Long t1) { return Observable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler); } }; Observable<Long> source = Observable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Observable<List<Long>> result = source.buffer(start, end).take(2); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); result .doOnNext(new Consumer<List<Long>>() { @Override public void accept(List<Long> pv) { System.out.println(pv); } }) .subscribe(o); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(o).onNext(Arrays.asList(1L, 2L, 3L)); inOrder.verify(o).onNext(Arrays.asList(3L, 4L)); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void bufferWithSizeThrows() { PublishSubject<Integer> source = PublishSubject.create(); Observable<List<Integer>> result = source.buffer(2); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); result.subscribe(o); source.onNext(1); source.onNext(2); source.onNext(3); source.onError(new TestException()); inOrder.verify(o).onNext(Arrays.asList(1, 2)); inOrder.verify(o).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); verify(o, never()).onNext(Arrays.asList(3)); verify(o, never()).onComplete(); } @Test public void bufferWithTimeThrows() { PublishSubject<Integer> source = PublishSubject.create(); Observable<List<Integer>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); result.subscribe(o); source.onNext(1); source.onNext(2); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(3); source.onError(new TestException()); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); inOrder.verify(o).onNext(Arrays.asList(1, 2)); inOrder.verify(o).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); verify(o, never()).onNext(Arrays.asList(3)); verify(o, never()).onComplete(); } @Test public void bufferWithTimeAndSize() { Observable<Long> source = Observable.interval(30, 30, TimeUnit.MILLISECONDS, scheduler); Observable<List<Long>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler, 2).take(3); Observer<Object> o = TestHelper.mockObserver(); InOrder inOrder = inOrder(o); result.subscribe(o); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(o).onNext(Arrays.asList(0L, 1L)); inOrder.verify(o).onNext(Arrays.asList(2L)); inOrder.verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); } @Test public void bufferWithStartEndStartThrows() { PublishSubject<Integer> start = PublishSubject.create(); Function<Integer, Observable<Integer>> end = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { return Observable.never(); } }; PublishSubject<Integer> source = PublishSubject.create(); Observable<List<Integer>> result = source.buffer(start, end); Observer<Object> o = TestHelper.mockObserver(); result.subscribe(o); start.onNext(1); source.onNext(1); source.onNext(2); start.onError(new TestException()); verify(o, never()).onNext(any()); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test public void bufferWithStartEndEndFunctionThrows() { PublishSubject<Integer> start = PublishSubject.create(); Function<Integer, Observable<Integer>> end = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { throw new TestException(); } }; PublishSubject<Integer> source = PublishSubject.create(); Observable<List<Integer>> result = source.buffer(start, end); Observer<Object> o = TestHelper.mockObserver(); result.subscribe(o); start.onNext(1); source.onNext(1); source.onNext(2); verify(o, never()).onNext(any()); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test public void bufferWithStartEndEndThrows() { PublishSubject<Integer> start = PublishSubject.create(); Function<Integer, Observable<Integer>> end = new Function<Integer, Observable<Integer>>() { @Override public Observable<Integer> apply(Integer t1) { return Observable.error(new TestException()); } }; PublishSubject<Integer> source = PublishSubject.create(); Observable<List<Integer>> result = source.buffer(start, end); Observer<Object> o = TestHelper.mockObserver(); result.subscribe(o); start.onNext(1); source.onNext(1); source.onNext(2); verify(o, never()).onNext(any()); verify(o, never()).onComplete(); verify(o).onError(any(TestException.class)); } @Test(timeout = 3000) public void testBufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedException { final Observer<Object> o = TestHelper.mockObserver(); final CountDownLatch cdl = new CountDownLatch(1); DisposableObserver<Object> observer = new DisposableObserver<Object>() { @Override public void onNext(Object t) { o.onNext(t); } @Override public void onError(Throwable e) { o.onError(e); cdl.countDown(); } @Override public void onComplete() { o.onComplete(); cdl.countDown(); } }; Observable.range(1, 1).delay(1, TimeUnit.SECONDS).buffer(2, TimeUnit.SECONDS).subscribe(observer); cdl.await(); verify(o).onNext(Arrays.asList(1)); verify(o).onComplete(); verify(o, never()).onError(any(Throwable.class)); assertFalse(observer.isDisposed()); } @SuppressWarnings("unchecked") @Test public void bufferTimeSkipDefault() { Observable.range(1, 5).buffer(1, 1, TimeUnit.MINUTES) .test() .assertResult(Arrays.asList(1, 2, 3, 4, 5)); } @SuppressWarnings("unchecked") @Test public void bufferBoundaryHint() { Observable.range(1, 5).buffer(Observable.timer(1, TimeUnit.MINUTES), 2) .test() .assertResult(Arrays.asList(1, 2, 3, 4, 5)); } static HashSet<Integer> set(Integer... values) { return new HashSet<Integer>(Arrays.asList(values)); } @SuppressWarnings("unchecked") @Test public void bufferIntoCustomCollection() { Observable.just(1, 1, 2, 2, 3, 3, 4, 4) .buffer(3, new Callable<Collection<Integer>>() { @Override public Collection<Integer> call() throws Exception { return new HashSet<Integer>(); } }) .test() .assertResult(set(1, 2), set(2, 3), set(4)); } @SuppressWarnings("unchecked") @Test public void bufferSkipIntoCustomCollection() { Observable.just(1, 1, 2, 2, 3, 3, 4, 4) .buffer(3, 3, new Callable<Collection<Integer>>() { @Override public Collection<Integer> call() throws Exception { return new HashSet<Integer>(); } }) .test() .assertResult(set(1, 2), set(2, 3), set(4)); } @Test @SuppressWarnings("unchecked") public void supplierThrows() { Observable.just(1) .buffer(1, TimeUnit.SECONDS, Schedulers.single(), Integer.MAX_VALUE, new Callable<Collection<Integer>>() { @Override public Collection<Integer> call() throws Exception { throw new TestException(); } }, false) .test() .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void supplierThrows2() { Observable.just(1) .buffer(1, TimeUnit.SECONDS, Schedulers.single(), 10, new Callable<Collection<Integer>>() { @Override public Collection<Integer> call() throws Exception { throw new TestException(); } }, false) .test() .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void supplierThrows3() { Observable.just(1) .buffer(2, 1, TimeUnit.SECONDS, Schedulers.single(), new Callable<Collection<Integer>>() { @Override public Collection<Integer> call() throws Exception { throw new TestException(); } }) .test() .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void supplierThrows4() { Observable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), Integer.MAX_VALUE, new Callable<Collection<Integer>>() { int count; @Override public Collection<Integer> call() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<Integer>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void supplierThrows5() { Observable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), 10, new Callable<Collection<Integer>>() { int count; @Override public Collection<Integer> call() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<Integer>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void supplierThrows6() { Observable.<Integer>never() .buffer(2, 1, TimeUnit.MILLISECONDS, Schedulers.single(), new Callable<Collection<Integer>>() { int count; @Override public Collection<Integer> call() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<Integer>(); } } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void supplierReturnsNull() { Observable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), Integer.MAX_VALUE, new Callable<Collection<Integer>>() { int count; @Override public Collection<Integer> call() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<Integer>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test @SuppressWarnings("unchecked") public void supplierReturnsNull2() { Observable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), 10, new Callable<Collection<Integer>>() { int count; @Override public Collection<Integer> call() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<Integer>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test @SuppressWarnings("unchecked") public void supplierReturnsNull3() { Observable.<Integer>never() .buffer(2, 1, TimeUnit.MILLISECONDS, Schedulers.single(), new Callable<Collection<Integer>>() { int count; @Override public Collection<Integer> call() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<Integer>(); } } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test @SuppressWarnings("unchecked") public void boundaryBufferSupplierThrows() { Observable.never() .buffer(Functions.justCallable(Observable.never()), new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { throw new TestException(); } }) .test() .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void boundaryBoundarySupplierThrows() { Observable.never() .buffer(new Callable<ObservableSource<Object>>() { @Override public ObservableSource<Object> call() throws Exception { throw new TestException(); } }, new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test() .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void boundaryBufferSupplierThrows2() { Observable.never() .buffer(Functions.justCallable(Observable.timer(1, TimeUnit.MILLISECONDS)), new Callable<Collection<Object>>() { int count; @Override public Collection<Object> call() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<Object>(); } } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void boundaryBufferSupplierReturnsNull() { Observable.never() .buffer(Functions.justCallable(Observable.timer(1, TimeUnit.MILLISECONDS)), new Callable<Collection<Object>>() { int count; @Override public Collection<Object> call() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<Object>(); } } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test @SuppressWarnings("unchecked") public void boundaryBoundarySupplierThrows2() { Observable.never() .buffer(new Callable<ObservableSource<Long>>() { int count; @Override public ObservableSource<Long> call() throws Exception { if (count++ == 1) { throw new TestException(); } return Observable.timer(1, TimeUnit.MILLISECONDS); } }, new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void boundaryCancel() { PublishSubject<Object> ps = PublishSubject.create(); TestObserver<Collection<Object>> to = ps .buffer(Functions.justCallable(Observable.never()), new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test(); assertTrue(ps.hasObservers()); to.dispose(); assertFalse(ps.hasObservers()); } @Test @SuppressWarnings("unchecked") public void boundaryBoundarySupplierReturnsNull() { Observable.never() .buffer(new Callable<ObservableSource<Long>>() { int count; @Override public ObservableSource<Long> call() throws Exception { if (count++ == 1) { return null; } return Observable.timer(1, TimeUnit.MILLISECONDS); } }, new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test @SuppressWarnings("unchecked") public void boundaryBoundarySupplierReturnsNull2() { Observable.never() .buffer(new Callable<ObservableSource<Long>>() { int count; @Override public ObservableSource<Long> call() throws Exception { if (count++ == 1) { return null; } return Observable.empty(); } }, new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @SuppressWarnings("unchecked") @Test public void boundaryMainError() { PublishSubject<Object> ps = PublishSubject.create(); TestObserver<Collection<Object>> to = ps .buffer(Functions.justCallable(Observable.never()), new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test(); ps.onError(new TestException()); to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void boundaryBoundaryError() { PublishSubject<Object> ps = PublishSubject.create(); TestObserver<Collection<Object>> to = ps .buffer(Functions.justCallable(Observable.error(new TestException())), new Callable<Collection<Object>>() { @Override public Collection<Object> call() throws Exception { return new ArrayList<Object>(); } }) .test(); ps.onError(new TestException()); to.assertFailure(TestException.class); } @Test public void dispose() { TestHelper.checkDisposed(Observable.range(1, 5).buffer(1, TimeUnit.DAYS, Schedulers.single())); TestHelper.checkDisposed(Observable.range(1, 5).buffer(2, 1, TimeUnit.DAYS, Schedulers.single())); TestHelper.checkDisposed(Observable.range(1, 5).buffer(1, 2, TimeUnit.DAYS, Schedulers.single())); TestHelper.checkDisposed(Observable.range(1, 5) .buffer(1, TimeUnit.DAYS, Schedulers.single(), 2, Functions.<Integer>createArrayList(16), true)); TestHelper.checkDisposed(Observable.range(1, 5).buffer(1)); TestHelper.checkDisposed(Observable.range(1, 5).buffer(2, 1)); TestHelper.checkDisposed(Observable.range(1, 5).buffer(1, 2)); TestHelper.checkDisposed(PublishSubject.create().buffer(Observable.never())); TestHelper.checkDisposed(PublishSubject.create().buffer(Functions.justCallable(Observable.never()))); TestHelper.checkDisposed(PublishSubject.create().buffer(Observable.never(), Functions.justFunction(Observable.never()))); } @SuppressWarnings("unchecked") @Test public void restartTimer() { Observable.range(1, 5) .buffer(1, TimeUnit.DAYS, Schedulers.single(), 2, Functions.<Integer>createArrayList(16), true) .test() .assertResult(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5)); } @SuppressWarnings("unchecked") @Test public void bufferSupplierCrash2() { Observable.range(1, 2) .buffer(1, new Callable<List<Integer>>() { int calls; @Override public List<Integer> call() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<Integer>(); } }) .test() .assertFailure(TestException.class, Arrays.asList(1)); } @SuppressWarnings("unchecked") @Test public void bufferSkipSupplierCrash2() { Observable.range(1, 2) .buffer(2, 1, new Callable<List<Integer>>() { int calls; @Override public List<Integer> call() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<Integer>(); } }) .test() .assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void bufferSkipError() { Observable.<Integer>error(new TestException()) .buffer(2, 1) .test() .assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void bufferSkipOverlap() { Observable.range(1, 5) .buffer(5, 1) .test() .assertResult( Arrays.asList(1, 2, 3, 4, 5), Arrays.asList(2, 3, 4, 5), Arrays.asList(3, 4, 5), Arrays.asList(4, 5), Arrays.asList(5) ); } @SuppressWarnings("unchecked") @Test public void bufferTimedExactError() { Observable.error(new TestException()) .buffer(1, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void bufferTimedSkipError() { Observable.error(new TestException()) .buffer(1, 2, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void bufferTimedOverlapError() { Observable.error(new TestException()) .buffer(2, 1, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void bufferTimedExactEmpty() { Observable.empty() .buffer(1, TimeUnit.DAYS) .test() .assertResult(Collections.emptyList()); } @SuppressWarnings("unchecked") @Test public void bufferTimedSkipEmpty() { Observable.empty() .buffer(1, 2, TimeUnit.DAYS) .test() .assertResult(Collections.emptyList()); } @SuppressWarnings("unchecked") @Test public void bufferTimedOverlapEmpty() { Observable.empty() .buffer(2, 1, TimeUnit.DAYS) .test() .assertResult(Collections.emptyList()); } @SuppressWarnings("unchecked") @Test public void bufferTimedExactSupplierCrash() { TestScheduler scheduler = new TestScheduler(); PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<List<Integer>> to = ps .buffer(1, TimeUnit.MILLISECONDS, scheduler, 1, new Callable<List<Integer>>() { int calls; @Override public List<Integer> call() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<Integer>(); } }, true) .test(); ps.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); ps.onNext(2); to .assertFailure(TestException.class, Arrays.asList(1)); } @SuppressWarnings("unchecked") @Test public void bufferTimedExactBoundedError() { TestScheduler scheduler = new TestScheduler(); PublishSubject<Integer> ps = PublishSubject.create(); TestObserver<List<Integer>> to = ps .buffer(1, TimeUnit.MILLISECONDS, scheduler, 1, Functions.<Integer>createArrayList(16), true) .test(); ps.onError(new TestException()); to .assertFailure(TestException.class); } @Test public void withTimeAndSizeCapacityRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); final PublishSubject<Object> ps = PublishSubject.create(); TestObserver<List<Object>> to = ps.buffer(1, TimeUnit.SECONDS, scheduler, 5).test(); ps.onNext(1); ps.onNext(2); ps.onNext(3); ps.onNext(4); Runnable r1 = new Runnable() { @Override public void run() { ps.onNext(5); } }; Runnable r2 = new Runnable() { @Override public void run() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); } }; TestHelper.race(r1, r2); ps.onComplete(); int items = 0; for (List<Object> o : to.values()) { items += o.size(); } assertEquals("Round: " + i, 5, items); } } @SuppressWarnings("unchecked") @Test public void noCompletionCancelExact() { final AtomicInteger counter = new AtomicInteger(); Observable.<Integer>empty() .doOnDispose(new Action() { @Override public void run() throws Exception { counter.getAndIncrement(); } }) .buffer(5, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(Collections.<Integer>emptyList()); assertEquals(0, counter.get()); } @SuppressWarnings("unchecked") @Test public void noCompletionCancelSkip() { final AtomicInteger counter = new AtomicInteger(); Observable.<Integer>empty() .doOnDispose(new Action() { @Override public void run() throws Exception { counter.getAndIncrement(); } }) .buffer(5, 10, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(Collections.<Integer>emptyList()); assertEquals(0, counter.get()); } @SuppressWarnings("unchecked") @Test public void noCompletionCancelOverlap() { final AtomicInteger counter = new AtomicInteger(); Observable.<Integer>empty() .doOnDispose(new Action() { @Override public void run() throws Exception { counter.getAndIncrement(); } }) .buffer(10, 5, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(Collections.<Integer>emptyList()); assertEquals(0, counter.get()); } @Test @SuppressWarnings("unchecked") public void boundaryOpenCloseDisposedOnComplete() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> openIndicator = PublishSubject.create(); PublishSubject<Integer> closeIndicator = PublishSubject.create(); TestObserver<List<Integer>> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); assertTrue(source.hasObservers()); assertTrue(openIndicator.hasObservers()); assertFalse(closeIndicator.hasObservers()); openIndicator.onNext(1); assertTrue(openIndicator.hasObservers()); assertTrue(closeIndicator.hasObservers()); source.onComplete(); to.assertResult(Collections.<Integer>emptyList()); assertFalse(openIndicator.hasObservers()); assertFalse(closeIndicator.hasObservers()); } @Test public void bufferedCanCompleteIfOpenNeverCompletesDropping() { Observable.range(1, 50) .zipWith(Observable.interval(5, TimeUnit.MILLISECONDS), new BiFunction<Integer, Long, Integer>() { @Override public Integer apply(Integer integer, Long aLong) { return integer; } }) .buffer(Observable.interval(0, 200, TimeUnit.MILLISECONDS), new Function<Long, Observable<?>>() { @Override public Observable<?> apply(Long a) { return Observable.just(a).delay(100, TimeUnit.MILLISECONDS); } }) .test() .assertSubscribed() .awaitDone(3, TimeUnit.SECONDS) .assertComplete(); } @Test public void bufferedCanCompleteIfOpenNeverCompletesOverlapping() { Observable.range(1, 50) .zipWith(Observable.interval(5, TimeUnit.MILLISECONDS), new BiFunction<Integer, Long, Integer>() { @Override public Integer apply(Integer integer, Long aLong) { return integer; } }) .buffer(Observable.interval(0, 100, TimeUnit.MILLISECONDS), new Function<Long, Observable<?>>() { @Override public Observable<?> apply(Long a) { return Observable.just(a).delay(200, TimeUnit.MILLISECONDS); } }) .test() .assertSubscribed() .awaitDone(3, TimeUnit.SECONDS) .assertComplete(); } @Test @SuppressWarnings("unchecked") public void openClosemainError() { Observable.error(new TestException()) .buffer(Observable.never(), Functions.justFunction(Observable.never())) .test() .assertFailure(TestException.class); } @Test @SuppressWarnings("unchecked") public void openClosebadSource() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Observable<Object>() { @Override protected void subscribeActual(Observer<? super Object> observer) { Disposable bs1 = Disposables.empty(); Disposable bs2 = Disposables.empty(); observer.onSubscribe(bs1); assertFalse(bs1.isDisposed()); assertFalse(bs2.isDisposed()); observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); observer.onError(new IOException()); observer.onComplete(); observer.onNext(1); observer.onError(new TestException()); } } .buffer(Observable.never(), Functions.justFunction(Observable.never())) .test() .assertFailure(IOException.class); TestHelper.assertError(errors, 0, ProtocolViolationException.class); TestHelper.assertUndeliverable(errors, 1, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test @SuppressWarnings("unchecked") public void openCloseOpenCompletes() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> openIndicator = PublishSubject.create(); PublishSubject<Integer> closeIndicator = PublishSubject.create(); TestObserver<List<Integer>> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); openIndicator.onNext(1); assertTrue(closeIndicator.hasObservers()); openIndicator.onComplete(); assertTrue(source.hasObservers()); assertTrue(closeIndicator.hasObservers()); closeIndicator.onComplete(); assertFalse(source.hasObservers()); to.assertResult(Collections.<Integer>emptyList()); } @Test @SuppressWarnings("unchecked") public void openCloseOpenCompletesNoBuffers() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> openIndicator = PublishSubject.create(); PublishSubject<Integer> closeIndicator = PublishSubject.create(); TestObserver<List<Integer>> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); openIndicator.onNext(1); assertTrue(closeIndicator.hasObservers()); closeIndicator.onComplete(); assertTrue(source.hasObservers()); assertTrue(openIndicator.hasObservers()); openIndicator.onComplete(); assertFalse(source.hasObservers()); to.assertResult(Collections.<Integer>emptyList()); } @Test @SuppressWarnings("unchecked") public void openCloseTake() { PublishSubject<Integer> source = PublishSubject.create(); PublishSubject<Integer> openIndicator = PublishSubject.create(); PublishSubject<Integer> closeIndicator = PublishSubject.create(); TestObserver<List<Integer>> to = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .take(1) .test(); openIndicator.onNext(1); closeIndicator.onComplete(); assertFalse(source.hasObservers()); assertFalse(openIndicator.hasObservers()); assertFalse(closeIndicator.hasObservers()); to.assertResult(Collections.<Integer>emptyList()); } @Test @SuppressWarnings("unchecked") public void openCloseBadOpen() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { Observable.never() .buffer(new Observable<Object>() { @Override protected void subscribeActual(Observer<? super Object> observer) { assertFalse(((Disposable)observer).isDisposed()); Disposable bs1 = Disposables.empty(); Disposable bs2 = Disposables.empty(); observer.onSubscribe(bs1); assertFalse(bs1.isDisposed()); assertFalse(bs2.isDisposed()); observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); observer.onError(new IOException()); assertTrue(((Disposable)observer).isDisposed()); observer.onComplete(); observer.onNext(1); observer.onError(new TestException()); } }, Functions.justFunction(Observable.never())) .test() .assertFailure(IOException.class); TestHelper.assertError(errors, 0, ProtocolViolationException.class); TestHelper.assertUndeliverable(errors, 1, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test @SuppressWarnings("unchecked") public void openCloseBadClose() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { Observable.never() .buffer(Observable.just(1).concatWith(Observable.<Integer>never()), Functions.justFunction(new Observable<Object>() { @Override protected void subscribeActual(Observer<? super Object> observer) { assertFalse(((Disposable)observer).isDisposed()); Disposable bs1 = Disposables.empty(); Disposable bs2 = Disposables.empty(); observer.onSubscribe(bs1); assertFalse(bs1.isDisposed()); assertFalse(bs2.isDisposed()); observer.onSubscribe(bs2); assertFalse(bs1.isDisposed()); assertTrue(bs2.isDisposed()); observer.onError(new IOException()); assertTrue(((Disposable)observer).isDisposed()); observer.onComplete(); observer.onNext(1); observer.onError(new TestException()); } })) .test() .assertFailure(IOException.class); TestHelper.assertError(errors, 0, ProtocolViolationException.class); TestHelper.assertUndeliverable(errors, 1, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void bufferExactBoundaryDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable( new Function<Observable<Object>, ObservableSource<List<Object>>>() { @Override public ObservableSource<List<Object>> apply(Observable<Object> f) throws Exception { return f.buffer(Observable.never()); } } ); } @SuppressWarnings("unchecked") @Test public void bufferExactBoundarySecondBufferCrash() { PublishSubject<Integer> ps = PublishSubject.create(); PublishSubject<Integer> b = PublishSubject.create(); TestObserver<List<Integer>> to = ps.buffer(b, new Callable<List<Integer>>() { int calls; @Override public List<Integer> call() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<Integer>(); } }).test(); b.onNext(1); to.assertFailure(TestException.class); } @SuppressWarnings("unchecked") @Test public void bufferExactBoundaryBadSource() { Observable<Integer> ps = new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposables.empty()); observer.onComplete(); observer.onNext(1); observer.onComplete(); } }; final AtomicReference<Observer<? super Integer>> ref = new AtomicReference<Observer<? super Integer>>(); Observable<Integer> b = new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposables.empty()); ref.set(observer); } }; TestObserver<List<Integer>> to = ps.buffer(b).test(); ref.get().onNext(1); to.assertResult(Collections.<Integer>emptyList()); } @Test public void bufferBoundaryErrorTwice() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { BehaviorSubject.createDefault(1) .buffer(Functions.justCallable(new Observable<Integer>() { @Override protected void subscribeActual(Observer<? super Integer> observer) { observer.onSubscribe(Disposables.empty()); observer.onError(new TestException("first")); observer.onError(new TestException("second")); } })) .test() .assertError(TestException.class) .assertErrorMessage("first") .assertNotComplete(); TestHelper.assertUndeliverable(errors, 0, TestException.class, "second"); } finally { RxJavaPlugins.reset(); } } @Test public void bufferBoundarySupplierDisposed() { TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferBoundarySupplierObserver<Integer, List<Integer>, Integer> sub = new BufferBoundarySupplierObserver<Integer, List<Integer>, Integer>( to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), Functions.justCallable(Observable.<Integer>never()) ); Disposable bs = Disposables.empty(); sub.onSubscribe(bs); assertFalse(sub.isDisposed()); sub.dispose(); assertTrue(sub.isDisposed()); sub.next(); assertSame(DisposableHelper.DISPOSED, sub.other.get()); sub.dispose(); sub.dispose(); assertTrue(bs.isDisposed()); } @Test public void bufferBoundarySupplierBufferAlreadyCleared() { TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferBoundarySupplierObserver<Integer, List<Integer>, Integer> sub = new BufferBoundarySupplierObserver<Integer, List<Integer>, Integer>( to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), Functions.justCallable(Observable.<Integer>never()) ); Disposable bs = Disposables.empty(); sub.onSubscribe(bs); sub.buffer = null; sub.next(); sub.onNext(1); sub.onComplete(); } @Test public void timedDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() { @Override public Observable<List<Object>> apply(Observable<Object> f) throws Exception { return f.buffer(1, TimeUnit.SECONDS); } }); } @Test public void timedCancelledUpfront() { TestScheduler sch = new TestScheduler(); TestObserver<List<Object>> to = Observable.never() .buffer(1, TimeUnit.MILLISECONDS, sch) .test(true); sch.advanceTimeBy(1, TimeUnit.MILLISECONDS); to.assertEmpty(); } @Test public void timedInternalState() { TestScheduler sch = new TestScheduler(); TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferExactUnboundedObserver<Integer, List<Integer>> sub = new BufferExactUnboundedObserver<Integer, List<Integer>>( to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, TimeUnit.SECONDS, sch); sub.onSubscribe(Disposables.empty()); assertFalse(sub.isDisposed()); sub.onError(new TestException()); sub.onNext(1); sub.onComplete(); sub.run(); sub.dispose(); assertTrue(sub.isDisposed()); sub.buffer = new ArrayList<Integer>(); sub.enter(); sub.onComplete(); } @Test public void timedSkipDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() { @Override public Observable<List<Object>> apply(Observable<Object> f) throws Exception { return f.buffer(2, 1, TimeUnit.SECONDS); } }); } @Test public void timedSizedDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() { @Override public Observable<List<Object>> apply(Observable<Object> f) throws Exception { return f.buffer(2, TimeUnit.SECONDS, 10); } }); } @Test public void timedSkipInternalState() { TestScheduler sch = new TestScheduler(); TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferSkipBoundedObserver<Integer, List<Integer>> sub = new BufferSkipBoundedObserver<Integer, List<Integer>>( to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, 1, TimeUnit.SECONDS, sch.createWorker()); sub.onSubscribe(Disposables.empty()); sub.enter(); sub.onComplete(); sub.dispose(); sub.run(); } @Test public void timedSkipCancelWhenSecondBuffer() { TestScheduler sch = new TestScheduler(); final TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferSkipBoundedObserver<Integer, List<Integer>> sub = new BufferSkipBoundedObserver<Integer, List<Integer>>( to, new Callable<List<Integer>>() { int calls; @Override public List<Integer> call() throws Exception { if (++calls == 2) { to.cancel(); } return new ArrayList<Integer>(); } }, 1, 1, TimeUnit.SECONDS, sch.createWorker()); sub.onSubscribe(Disposables.empty()); sub.run(); assertTrue(to.isCancelled()); } @Test public void timedSizeBufferAlreadyCleared() { TestScheduler sch = new TestScheduler(); TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferExactBoundedObserver<Integer, List<Integer>> sub = new BufferExactBoundedObserver<Integer, List<Integer>>( to, Functions.justCallable((List<Integer>)new ArrayList<Integer>()), 1, TimeUnit.SECONDS, 1, false, sch.createWorker()) ; Disposable bs = Disposables.empty(); sub.onSubscribe(bs); sub.producerIndex++; sub.run(); assertFalse(sub.isDisposed()); sub.enter(); sub.onComplete(); sub.dispose(); assertTrue(sub.isDisposed()); sub.run(); sub.onNext(1); } @Test public void bufferExactDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<List<Object>>>() { @Override public ObservableSource<List<Object>> apply(Observable<Object> o) throws Exception { return o.buffer(1); } }); } @Test public void bufferExactState() { TestObserver<List<Integer>> to = new TestObserver<List<Integer>>(); BufferExactObserver<Integer, List<Integer>> sub = new BufferExactObserver<Integer, List<Integer>>( to, 1, Functions.justCallable((List<Integer>)new ArrayList<Integer>()) ); sub.onComplete(); sub.onNext(1); sub.onComplete(); } @Test public void bufferSkipDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<List<Object>>>() { @Override public ObservableSource<List<Object>> apply(Observable<Object> o) throws Exception { return o.buffer(1, 2); } }); } @Test public void bufferExactFailingSupplier() { Observable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Callable<List<Object>>() { @Override public List<Object> call() throws Exception { throw new TestException(); } }, false) .test() .awaitDone(1, TimeUnit.SECONDS) .assertFailure(TestException.class) ; } }
artem-zinnatullin/RxJava
src/test/java/io/reactivex/internal/operators/observable/ObservableBufferTest.java
Java
apache-2.0
70,705
const tsconfig = require('./tsconfig'); module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine', 'karma-typescript'], files: ['node_modules/tslib/tslib.js'] .concat(tsconfig.files) .concat(['test/setup.ts', 'test/**/*.ts']), exclude: [], preprocessors: { '**/*.ts': ['karma-typescript'] }, karmaTypescriptConfig: { compilerOptions: { noEmitHelpers: true, }, coverageOptions: { exclude: [ /(lib\/templates\.ts)/i, /(test\/.*\.ts)/i, ], } }, reporters: ['progress', 'coverage'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['ChromeHeadless'], singleRun: false, concurrency: Infinity, coverageReporter: { dir: 'coverage/', reporters: [{ type: 'lcov', subdir: 'report-lcov' }, { type: 'lcovonly', subdir: '.', file: 'lcov.info' }] } }); }
manudwarf/sterogrid
karma.conf.js
JavaScript
apache-2.0
1,028
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <stdlib.h> #include <stdio.h> #include <iostream> #include <boost/utility.hpp> #include <gtest/gtest.h> #include "util/bit_util.h" #include "util/cpu_info.h" namespace palo { TEST(BitUtil, Ceil) { EXPECT_EQ(BitUtil::ceil(0, 1), 0); EXPECT_EQ(BitUtil::ceil(1, 1), 1); EXPECT_EQ(BitUtil::ceil(1, 2), 1); EXPECT_EQ(BitUtil::ceil(1, 8), 1); EXPECT_EQ(BitUtil::ceil(7, 8), 1); EXPECT_EQ(BitUtil::ceil(8, 8), 1); EXPECT_EQ(BitUtil::ceil(9, 8), 2); } TEST(BitUtil, Popcount) { EXPECT_EQ(BitUtil::popcount(BOOST_BINARY(0 1 0 1 0 1 0 1)), 4); EXPECT_EQ(BitUtil::popcount_no_hw(BOOST_BINARY(0 1 0 1 0 1 0 1)), 4); EXPECT_EQ(BitUtil::popcount(BOOST_BINARY(1 1 1 1 0 1 0 1)), 6); EXPECT_EQ(BitUtil::popcount_no_hw(BOOST_BINARY(1 1 1 1 0 1 0 1)), 6); EXPECT_EQ(BitUtil::popcount(BOOST_BINARY(1 1 1 1 1 1 1 1)), 8); EXPECT_EQ(BitUtil::popcount_no_hw(BOOST_BINARY(1 1 1 1 1 1 1 1)), 8); EXPECT_EQ(BitUtil::popcount(0), 0); EXPECT_EQ(BitUtil::popcount_no_hw(0), 0); } } int main(int argc, char** argv) { std::string conffile = std::string(getenv("PALO_HOME")) + "/conf/be.conf"; if (!palo::config::init(conffile.c_str(), false)) { fprintf(stderr, "error read config file. \n"); return -1; } init_glog("be-test"); ::testing::InitGoogleTest(&argc, argv); palo::CpuInfo::init(); return RUN_ALL_TESTS(); }
lingbin/palo
be/test/util/bit_util_test.cpp
C++
apache-2.0
2,024
package com.mhq0123.officialwebsite.servicegateway; import org.mhq0123.springleaf.core.adapter.CorsConfigurerAdapter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Import; /** * project: mhq0123-officialwebsite * author: mhq0123 * date: 2016/12/28. * desc: */ @SpringBootApplication @EnableZuulProxy @EnableDiscoveryClient @Import(CorsConfigurerAdapter.class) // TODO 跨域支持 public class ServiceGatewayApplication { public static void main(String[] args) { SpringApplication.run(ServiceGatewayApplication.class, args); } }
mhq0123/mhq0123-officialwebsite
mhq0123-officialwebsite-service-gateway/src/main/java/com/mhq0123/officialwebsite/servicegateway/ServiceGatewayApplication.java
Java
apache-2.0
813
# Phyllosticta toxica Ellis & G. Martin SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Phyllosticta toxica Ellis & G. Martin ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Dothideomycetes/Botryosphaeriales/Botryosphaeriaceae/Phyllosticta/Phyllosticta toxica/README.md
Markdown
apache-2.0
203
#!/usr/bin/env python3 import argparse import datetime import getpass import json import logging import logging.config import os import re import sys import tabulate import uuid from critsapi.critsapi import CRITsAPI from critsapi.critsdbapi import CRITsDBAPI from lib.pt.common.config import Config from lib.pt.common.constants import PT_HOME from lib.pt.core.database import Database from lib.pt.ptapi import PTAPI from lib.crits.vocabulary.indicators import IndicatorTypes as it from operator import itemgetter from configparser import ConfigParser log = logging.getLogger() VERSION = "0.1337" # Check configuration directory local_config_dir = os.path.join(PT_HOME, 'etc', 'local') if not os.path.exists(local_config_dir): os.makedirs(local_config_dir) sys.exit('No etc/local/ directory. See README to create.') config = Config() # Check local data directory if config.core.cache_enabled: if not os.path.exists(config.core.cache_dir): log.info('Creating Cache directory in ' '{}'.format(config.core.cache_dir)) os.makedirs(config.core.cache_dir) # Initialize loggin log_path = os.path.join(PT_HOME, 'etc', 'local', 'logging.ini') try: logging.config.fileConfig(log_path) except Exception as e: sys.exit('unable to load logging configuration file {}: ' '{}'.format(log_path, str(e))) pt = PTAPI(username=config.core.pt_username, apikey=config.core.pt_apikey) pt.set_proxy(http=config.proxy.http, https=config.proxy.https) argparser = argparse.ArgumentParser() argparser.add_argument('QUERY', action='store', help='A value to send as a' ' query to PT. Email, phone, name, etc.') argparser.add_argument('--dev', dest='dev', action='store_true', default=False) argparser.add_argument('--crits', dest='crits', action='store_true', default=False, help='Write the results to CRITs with' ' appropriate relationships.') argparser.add_argument('--test', dest='test', action='store_true', default=False, help='Run with test data. (Save PT ' 'queries)') argparser.add_argument('-f', dest='force', action='store_true', default=False, help='Force a new API query (do not used cached ' 'results.') argparser.add_argument('-t', action='append', dest='tags', default=[], help='Bucket list tags for crits. Multiple -t options ' 'are allowed.') # Add our mutually exclusive items meg = argparser.add_mutually_exclusive_group() meg.add_argument('-n', dest='name', action='store_true', default=False, help='The query is a name and pt_query will not try to ' 'determine the type automatically.') meg.add_argument('-a', dest='address', action='store_true', default=False, help='The query is an address and pt_query will not ' 'try to determine the type automatically.') args = argparser.parse_args() # Patterns for determining which type of lookup to do # Some items cannot be differentiated via regex (name vs address), so we use # a flag to specify these # Load patterns for regexes pattern_config = ConfigParser() patterns = {} with open(os.path.join(PT_HOME, 'etc', 'patterns.ini')) as fp: pattern_config.readfp(fp) email_address_pattern = re.compile(pattern_config.get('email', 'pattern')) phone_pattern = re.compile(pattern_config.get('phone', 'pattern')) domain_pattern = re.compile(pattern_config.get('domain', 'pattern')) database = None if config.core.cache_enabled: database = Database() if args.crits: HOME = os.path.expanduser("~") if not os.path.exists(os.path.join(HOME, '.crits_api')): print('''Please create a file with the following contents: [crits] user = lolnate [keys] prod_api_key = keyhere dev_api_key = keyhere ''') raise SystemExit('~/.crits_api was not found or was not accessible.') crits_config = ConfigParser() crits_config.read(os.path.join(HOME, '.crits_api')) if crits_config.has_option("keys", "prod"): crits_api_prod = crits_config.get("keys", "prod") if crits_config.has_option("keys", "dev"): crits_api_dev = crits_config.get("keys", "dev") if crits_config.has_option("crits", "user"): crits_username = crits_config.get("crits", "user") if args.dev: crits_url = config.crits.crits_dev_api_url crits_api_key = crits_api_dev if len(crits_api_key) != 40: print("Dev API key in ~/.crits_api is the wrong length! Must be 40\ characters.") else: crits_url = config.crits.crits_prod_api_url crits_api_key = crits_api_prod if len(crits_api_key) != 40: print("Prod API key in ~/.crits_api is the wrong length! Must be 40\ characters.") crits_proxy = { 'http': config.crits.crits_proxy_url, 'https': config.crits.crits_proxy_url, } # Build our mongo connection if args.dev: crits_mongo = CRITsDBAPI(mongo_uri=config.crits.mongo_uri_dev, db_name=config.crits.database) else: crits_mongo = CRITsDBAPI(mongo_uri=config.crits.mongo_uri, db_name=config.crits.database) crits_mongo.connect() # Connect to the CRITs API crits = CRITsAPI( api_url=crits_url, api_key=crits_api_key, username=crits_username, proxies=crits_proxy, verify=config.crits.crits_verify ) query = args.QUERY.rstrip() # Get the user launching all this user = getpass.getuser() # Used to store the type of indicator in CRITs for the query object. crits_indicator_type = '' # Used to store the cache file location cache_file = None if database and not args.force and config.core.cache_enabled: cache_file = database.get_cache_file(query) if cache_file: log.info('Using cache file for query {}'.format(query)) with open(cache_file) as fp: results = json.loads(fp.read()) bucket_list = ['whois', 'pt:query'] for t in args.tags: bucket_list.append(t) if args.name or args.address: if args.name: field_str = 'name' if args.address: field_str = 'address' if args.test: results = pt.get_test_results(field=field_str) else: results = pt.whois_search(query=query, field=field_str) if database and not cache_file and config.core.cache_enabled: filepath = os.path.join(config.core.cache_dir, str(uuid.uuid4())) log.debug('Filepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/'\ '{}'.format(field_str) # Use our config defined indicator type of whois email objects if args.name: crits_indicator_type = it.WHOIS_NAME if args.address: crits_indicator_type = it.WHOIS_ADDR1 bucket_list.append('registrant') elif re.match(email_address_pattern, query): if args.test: results = pt.get_test_results(field='email') else: results = pt.whois_search(query=query, field='email') # Now add the results to the db if we have it if database and not cache_file and config.core.cache_enabled: filepath = os.path.join(config.core.cache_dir, str(uuid.uuid4())) log.debug('Filepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/email' # Use our config defined indicator type of whois email objects crits_indicator_type = it.WHOIS_REGISTRANT_EMAIL_ADDRESS bucket_list.append('registrant') elif re.match(phone_pattern, query): if args.test: results = pt.get_test_results(field='phone') else: results = pt.whois_search(query=query, field='phone') # Now add the results to the db if we have it if database and not cache_file and config.core.cache_enabled: filepath = os.path.join(config.core.cache_dir, str(uuid.uuid4())) log.debug('Filepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/phone' crits_indicator_type = it.WHOIS_TELEPHONE bucket_list.append('registrant') elif re.match(domain_pattern, query): if args.test: results = pt.get_test_results(field='domain') else: results = pt.whois_search(query=query, field='domain') # Now add the results to the db if we have it if database and not cache_file and config.core.cache_enabled: filepath = os.path.join(config.core.cache_dir, str(uuid.uuid4())) log.debug('Filepath is {}'.format(filepath)) database.add_results_to_cache(query, user, results, filepath) base_reference = 'https://www.passivetotal.org/search/whois/domain' crits_indicator_type = it.DOMAIN else: raise SystemExit("Your query didn't match a known pattern.") # Add the query to CRITs regardless of the number of results # TODO: Add campaigns if args.crits: found = False # Search for it with raw mongo because API is slow crits_result = crits_mongo.find('indicators', {'value': query, 'type': crits_indicator_type}) if crits_result.count() > 0: for r in crits_result: if r['value'] == query: indicator = r found = True if not found: indicator = crits.add_indicator( value=query, itype=crits_indicator_type, source=config.crits.default_source, reference='Added via pt_query.py', method='pt_query.py', bucket_list=bucket_list, indicator_confidence='low', indicator_impact='low', description='Queried with pt_query.py', ) # This is pretty hacky - Since we use both the raw DB and the API, we might # receive either an '_id' or an 'id' back. We are going to standardize on # 'id', rather than '_id' if 'id' not in indicator: if '_id' not in indicator: print(repr(indicator)) raise SystemExit('id and _id not found for query: ' '{} in new indicator'.format(query)) else: indicator['id'] = indicator['_id'] # Iterate through all results and print/add to CRITs (if args provided) formatted_results = [] for result in results['results']: if 'domain' in result: crits_indicators_to_add = [] # Row contains: # Domain, Registrant Email, Registrant Name, Registrant Date, # Expiration Date, Tags row = ['', '', '', '', '', ''] row[0] = result['domain'] # Email address used to register if 'registrant' in result: # Append the registrant email if 'email' in result['registrant']: row[1] = result['registrant']['email'] email_obj = { 'value': result['registrant']['email'], 'type': it.WHOIS_REGISTRANT_EMAIL_ADDRESS, 'related_to': result['domain'] } crits_indicators_to_add.append(email_obj) if 'name' in result['registrant']: row[2] = result['registrant']['name'] name_obj = { 'value': result['registrant']['name'], 'type': it.WHOIS_NAME, 'related_to': result['domain'] } crits_indicators_to_add.append(name_obj) if 'telephone' in result['registrant']: row[3] = result['registrant']['telephone'] phone_obj = { 'value': result['registrant']['telephone'], 'type': it.WHOIS_TELEPHONE, 'related_to': result['domain'] } crits_indicators_to_add.append(phone_obj) if 'street' in result['registrant']: addr1_obj = { 'value': result['registrant']['street'], 'type': it.WHOIS_ADDR1, 'related_to': result['domain'] } crits_indicators_to_add.append(addr1_obj) # Date the domain was registered if 'registered' in result: row[4] = result['registered'] if 'expiresAt' in result: row[5] = result['expiresAt'] formatted_results.append(row) # TODO: Tags. They appear to be an extra API query which is annoying reference = '{0}/{1}'.format(base_reference, query) if args.crits: # Let's try getting the confidence and impact from the parent whois # indicator confidence = 'low' impact = 'low' if 'confidence' in indicator: if 'rating' in indicator['confidence']: confidence = indicator['confidence']['rating'] if 'impact' in indicator: if 'rating' in indicator['impact']: impact = indicator['impact']['rating'] # If not in CRITs, add all the associated indicators bucket_list = ['whois pivoting', 'pt:found'] for t in args.tags: bucket_list.append(t) new_ind = crits.add_indicator( value=result['domain'], itype=it.DOMAIN, source=config.crits.default_source, reference=reference, method='pt_query.py', bucket_list=bucket_list, indicator_confidence=confidence, indicator_impact=impact, description='Discovered through PT whois pivots' ) # The CRITs API allows us to add a campaign to the indicator, but # not multiple campaigns at one time, # so we will do it directly with the DB. # We want to replicate the campaigns of the WHOIS indicator (if # a campaign exists) to the new indicator. if 'campaign' in indicator: for campaign in indicator['campaign']: crits_mongo.add_embedded_campaign( new_ind['id'], 'indicators', campaign['name'], campaign['confidence'], campaign['analyst'], datetime.datetime.now(), campaign['description'] ) # If the new indicator and the indicator are not related, # relate them. if not crits.has_relationship(indicator['id'], 'Indicator', new_ind['id'], 'Indicator', rel_type='Registered'): crits.forge_relationship(indicator['id'], 'Indicator', new_ind['id'], 'Indicator', rel_type='Registered') # Now we can add the rest of the WHOIS indicators (if necessary) for ind in crits_indicators_to_add: # If the indicator exists, just get the id and use it to build # relationships. We will look for one with the same source. # If not in CRITs, add it and relate it. whois_indicator = crits_mongo.find_one( 'indicators', { 'value': ind['value'], 'type': ind['type'], 'source.name': config.crits.default_source, }) if not whois_indicator: bucket_list = ['whois pivoting', 'pt:found'] for t in args.tags: bucket_list.append(t) whois_indicator = crits.add_indicator( value=ind['value'], itype=ind['type'], source=config.crits.default_source, reference=reference, method='pt_query.py', bucket_list=bucket_list, indicator_confidence=confidence, indicator_impact=impact, description='Discovered through PT whois pivots' ) # This is pretty hacky - Since we use both the raw DB and the # API, we might receive either an '_id' or an 'id' back. We # are going to standardize on 'id', rather than '_id' if 'id' not in whois_indicator: if '_id' not in whois_indicator: print(repr(whois_indicator)) raise SystemExit('id and _id not found for query: ' '{} in whois indicator'.format(query)) whois_indicator['id'] = whois_indicator['_id'] # Not a huge deal, but make sure we don't waste time adding # a relationship to itself if whois_indicator['id'] == new_ind['id']: continue # The CRITs API allows us to add a campaign to the indicator, # but not multiple campaigns at one time, # so we will do it directly with the DB. # We want to replicate the campaigns of the WHOIS indicator (if # a campaign exists) to the new indicator. # Continue with the same campaign if 'campaign' in indicator: for campaign in indicator['campaign']: crits_mongo.add_embedded_campaign( whois_indicator['id'], 'indicators', campaign['name'], campaign['confidence'], campaign['analyst'], datetime.datetime.now(), campaign['description'] ) # If the new indicator and the indicator are not related, # relate them. if not crits.has_relationship(whois_indicator['id'], 'Indicator', new_ind['id'], 'Indicator', rel_type='Registered'): crits.forge_relationship(whois_indicator['id'], 'Indicator', new_ind['id'], 'Indicator', rel_type='Registered') # Add a bucket_list item to track that we searched for this whois indicator if args.crits: crits_mongo.add_bucket_list_item(indicator['id'], 'indicators', 'pt:whois_search_completed') # SORT BY DATE formatted_results = sorted(formatted_results, key=itemgetter(3), reverse=True) # Row contains: # Domain, Registrant Email, Registrant Name, Registrant Telephone, # Registrant Date, Expiration Date, Tags headers = ['Domain', 'Registrant Email', 'Registrant Name', 'Registrant Telephone', 'Registrant Date', 'Expiration Date', 'Tags'] print(tabulate.tabulate(formatted_results, headers))
IntegralDefense/ptauto
bin/pt_query.py
Python
apache-2.0
19,839
package com.siahmsoft.soundwaper; import android.graphics.Bitmap; import android.graphics.Matrix; /* * Copyright (C) 2010 Siahmsoft * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public final class BitmapHelper { public static Bitmap scale(Bitmap b, float scale) { Matrix matrix = new Matrix(); matrix.postScale(scale, scale); b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(), matrix, true); return b; } }
ahmontero/Soundwaper
src/com/siahmsoft/soundwaper/BitmapHelper.java
Java
apache-2.0
944
/* * Copyright 2018 iserge. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cesiumjs.cs.datasources; import jsinterop.annotations.*; import org.cesiumjs.cs.core.Event; import org.cesiumjs.cs.datasources.options.EntityClusterOptions; /** * @author Serge Silaev aka iSergio */ @JsType(isNative = true, namespace = "Cesium", name = "EntityCluster") public class EntityCluster { /** * Gets the event that will be raised when a new cluster will be displayed. The * signature of the event listener is EntityCluster~newClusterCallback. */ @JsProperty public Event clusterEvent; /** * Gets or sets whether clustering is enabled. */ @JsProperty public boolean enabled; /** * Gets or sets the minimum number of screen space objects that can be * clustered. */ @JsProperty public int minimumClusterSize; /** * Gets or sets the pixel range to extend the screen space bounding box. */ @JsProperty public int pixelRange; /** * Whether or not to cluster the billboards of an entity. * Default: true */ @JsProperty public boolean clusterBillboards; /** * Whether or not to cluster the labels of an entity. * Default: true */ @JsProperty public boolean clusterLabels; /** * Whether or not to cluster the points of an entity. * Default: true */ @JsProperty public boolean clusterPoints; /** * Determines if the entities in the cluster will be shown. * Default: true */ @JsProperty public boolean show; /** * Defines how screen space objects (billboards, points, labels) are clustered. */ @JsConstructor public EntityCluster() { } /** * Defines how screen space objects (billboards, points, labels) are clustered. * * @param options {@link EntityClusterOptions}. */ @JsConstructor public EntityCluster(EntityClusterOptions options) { } /** * Destroys the WebGL resources held by this object. Destroying an object allows * for deterministic release of WebGL resources, instead of relying on the * garbage collector to destroy this object. * <p> * Unlike other objects that use WebGL resources, this object can be reused. For * example, if a data source is removed from a data source collection and added * to another. */ @JsMethod public native void destroy(); // TODO: Example @JsFunction public interface newClusterCallback { /** * A event listener function used to style clusters. * * @param clusteredEntities An array of the entities contained in the cluster. * @param cluster An object containing billboard, label, and point * properties. The values are the same as billboard, * label and point entities, but must be the values of * the ConstantProperty. */ void function(Entity[] clusteredEntities, EntityClusterObject cluster); } }
iSergio/gwt-cs
cesiumjs4gwt-main/src/main/java/org/cesiumjs/cs/datasources/EntityCluster.java
Java
apache-2.0
3,664
<html><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>ContainerGadget3D</title></head> <body bgcolor="#EFF1F0" link="#3A3966" vlink="#000000" alink="#000000"> <font face="Verdana, sans-serif" size="2"><p align="center"><b><font size="4">ContainerGadget3D()</font></b></p> <p><b>语法</b></p><blockquote> Result = <font color="#3A3966"><b>ContainerGadget3D</b></font>(#Gadget3D, x, y, Width, Height)</blockquote> </blockquote> <b>概要</b><br><blockquote> Creates a container gadget in the current GadgetList. It's a simple panel gadget which can contain other gadgets. Once the gadget is created, all future created gadgets will be created inside the container. When all the needed gadgets have been created, <a href="closegadgetlist3d.html">CloseGadgetList3D()</a> must be called to return to the previous GadgetList. <a href="opengadgetlist3d.html">OpenGadgetList3D()</a> can be used later to add others gadgets on the fly in the container area. </blockquote><p><b>参数</b></p><blockquote> <style type="text/css"> table.parameters { border-spacing: 0px; border-style: none; border-collapse: collapse; } table.parameters td { border-width: 1px; padding: 6px; border-style: solid; border-color: gray; vertical-align: top; font-family:Arial; font-size:10pt; } </style> <table width="90%" class="parameters"> <tr><td width="10%"><i>#Gadget3D</i></td> <td width="90%"> A number to identify the new 3D gadget. <a href="../reference/purebasic_objects.html">#PB_Any</a> 可以用来自动生成这个编码. </td></tr> <tr><td><i>x, y, Width, Height</i></td> <td> The position and dimensions of the new gadget. </td></tr> </table> </blockquote><p><b>返回值</b></p><blockquote> Nonzero on success, zero otherwise. If <font color="#924B72">#PB_Any</font> was used as the #Gadget3D parameter then the return-value is the auto-generated gadget number on success. </blockquote><p><b>备注</b></p><blockquote> To add a 'mini help' to this gadget, use <a href="gadgettooltip3d.html">GadgetToolTip3D()</a>. </Blockquote><p><b>已支持操作系统 </b><Blockquote>所有</Blockquote></p><center>&lt;- <a href=comboboxgadget3d.html>ComboBoxGadget3D()</a> - <a href="index.html">Gadget3D Index</a> - <a href="countgadgetitems3d.html">CountGadgetItems3D()</a> -&gt;<br><br> </body></html>
PureBasicCN/PureBasicPreference
target_dir/documentation/gadget3d/containergadget3d.html
HTML
apache-2.0
2,360
// // detail/io_control.hpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_DETAIL_IO_CONTROL_HPP #define BOOST_ASIO_DETAIL_IO_CONTROL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <cstddef> #include <boost/config.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/detail/push_options.hpp> namespace riakboost{} namespace boost = riakboost; namespace riakboost{ namespace asio { namespace detail { namespace io_control { // IO control command for non-blocking I/O. class non_blocking_io { public: // Default constructor. non_blocking_io() : value_(0) { } // Construct with a specific command value. non_blocking_io(bool value) : value_(value ? 1 : 0) { } // Get the name of the IO control command. int name() const { return static_cast<int>(FIONBIO); } // Set the value of the I/O control command. void set(bool value) { value_ = value ? 1 : 0; } // Get the current value of the I/O control command. bool get() const { return value_ != 0; } // Get the address of the command data. detail::ioctl_arg_type* data() { return &value_; } // Get the address of the command data. const detail::ioctl_arg_type* data() const { return &value_; } private: detail::ioctl_arg_type value_; }; // I/O control command for getting number of bytes available. class bytes_readable { public: // Default constructor. bytes_readable() : value_(0) { } // Construct with a specific command value. bytes_readable(std::size_t value) : value_(static_cast<detail::ioctl_arg_type>(value)) { } // Get the name of the IO control command. int name() const { return static_cast<int>(FIONREAD); } // Set the value of the I/O control command. void set(std::size_t value) { value_ = static_cast<detail::ioctl_arg_type>(value); } // Get the current value of the I/O control command. std::size_t get() const { return static_cast<std::size_t>(value_); } // Get the address of the command data. detail::ioctl_arg_type* data() { return &value_; } // Get the address of the command data. const detail::ioctl_arg_type* data() const { return &value_; } private: detail::ioctl_arg_type value_; }; } // namespace io_control } // namespace detail } // namespace asio } // namespace riakboost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_DETAIL_IO_CONTROL_HPP
basho-labs/riak-cxx-client
deps/boost-1.47.0/boost/asio/detail/io_control.hpp
C++
apache-2.0
2,801
# Ten Lines or Less Python scripts that are short but useful or interesting. GitHub Repos ------------ | Script Name | Description | | --------------------------- | ------------- | | [files_and_folders][ccc] | Get tuples of the files and folders in a directory | | [pyui_from_clipboard][ccc] | Create a .pyui file from the text on the iOS clipboard | | [pyui_print][ccc] | Print out .pyiu or other json formatted files | | [pyui_to_clipboard][ccc] | Put the contents of a pyui file onto the clipboard | | [zap_carriage_returns][ccc] | Make those Windows text files more friendly | | [tweetme][tjferry14] | Allows you to tweet whatever you type into a dialog | | [count_text][tjferry14] | Counts the amount of letters or numbers in text you ask it to | | [iBright][] | Change the brightness of your device | | [iSay][] | Complete TextToSpeech | GitHub Gists ------------ [ccc]: https://github.com/cclauss/Ten-lines-or-less [tjferry14]: https://github.com/tjferry14/My-Pythonista-Projects [iBright]: https://github.com/GoDzM4TT3O/iBright [iSay]: https://github.com/GoDzM4TT3O/iSay
Pythonista-Tools/Pythonista-Tools
Ten Lines or Less.md
Markdown
apache-2.0
1,121
# Eurotium appendiculatum Blaser, 1976 SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Sydowia 28(1-6): 38 (1976) #### Original name Eurotium appendiculatum Blaser, 1976 ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Eurotiomycetes/Eurotiales/Trichocomaceae/Eurotium/Eurotium appendiculatum/README.md
Markdown
apache-2.0
248
<?php session_start(); ?> <!DOCTYPE html> <html lang="fr"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" type="image/png" href="statics/pictures/fav_icon.png"/> <title>banding tracking</title> <link href="statics/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="statics/sweet_alert/sweet-alert.css"> <link rel="stylesheet" type="text/css" href="statics/datepicker/css/datepicker.css"> <link rel="stylesheet" type="text/css" href="statics/home_made/css/style.css"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <nav class="navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="index.php?url=home">Accueil</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a href="index.php?url=form">Vous avez vu un gravelot ?</a></li> <li><a href="index.php?url=admin">Administration</a></li> <li><a href="index.php?url=about">A propos</a></li> <li><a href="http://crbpo.mnhn.fr/">Le CRBPO</a></li> </ul> </div> </div> </nav> <div class ="container padding-content"> <?php include "core/database_operations.php"; $db = new Database_operations(); if (isset($_GET["url"])) { include "content/" . $_GET["url"]. ".php"; } else { include "content/home.php"; } ?> </div> <?php if(isset($_GET["url"]) && $_GET["url"] == "form") { echo '<script src="http://maps.googleapis.com/maps/api/js"></script>'; echo '<script src="statics/home_made/js/geolocalisation.js"></script>'; } ?> <script src="statics/sweet_alert/sweet-alert.min.js"></script> <script src="statics/jquery/jquery-2.1.3.min.js"></script> <script src="statics/bootstrap/js/bootstrap.min.js"></script> <script src="statics/datepicker/js/bootstrap-datepicker.js"></script> <script src="statics/home_made/js/banding-tracking.js"></script> <?php // Displays an error when the form does not return anything if (isset($_SESSION["alert"])) { if($_SESSION["alert"]) { echo '<script type="text/javascript"> (swal("Aucune donnée retournée", "Aucun oiseau bagué portant ces couleur et ce chiffre n\'a été trouvé", "error"));</script>'; } } unset($_SESSION["alert"]); ?> </body> </html>
Carmain/Banding-tracking
index.php
PHP
apache-2.0
3,636
/*! * SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5) * (c) Copyright 2009-2015 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ /** * SAPUI5 base classes * * @namespace * @name sap.ui.base * @public */ // Provides class sap.ui.base.Object sap.ui.define(['jquery.sap.global', './Interface', './Metadata'], function(jQuery, Interface, Metadata) { "use strict"; /** * Constructor for a sap.ui.base.Object. * * @class Base class for all SAPUI5 Objects * @abstract * @author Malte Wedel * @version 1.30.4-SNAPSHOT * @public * @alias sap.ui.base.Object */ var BaseObject = Metadata.createClass("sap.ui.base.Object", { constructor : function() { // complain if 'this' is not an instance of a subclass if ( !(this instanceof BaseObject) ) { throw Error("Cannot instantiate object: \"new\" is missing!"); } } }); /** * Destructor method for objects * @public */ BaseObject.prototype.destroy = function() { }; /** * Returns the public interface of the object. * * @return {sap.ui.base.Interface} the public interface of the object * @public */ BaseObject.prototype.getInterface = function() { // New implementation that avoids the overhead of a dedicated member for the interface // initially, an Object instance has no associated Interface and the getInterface // method is defined only in the prototype. So the code here will be executed. // It creates an interface (basically the same code as in the old implementation) var oInterface = new Interface(this, this.getMetadata().getAllPublicMethods()); // Now this Object instance gets a new, private implementation of getInterface // that returns the newly created oInterface. Future calls of getInterface on the // same Object therefore will return the already created interface this.getInterface = jQuery.sap.getter(oInterface); // as the first caller doesn't benefit from the new method implementation we have to // return the created interface as well. return oInterface; }; /** * Returns the metadata for the class that this object belongs to. * * This method is only defined when metadata has been declared by using {@link sap.ui.base.Object.defineClass} * or {@link sap.ui.base.Object.extend}. * * @return {sap.ui.base.Metadata] metadata for the class of the object * @name sap.ui.base.Object#getMetadata * @function * @public */ /** * Creates a subclass of class sap.ui.base.Object with name <code>sClassName</code> * and enriches it with the information contained in <code>oClassInfo</code>. * * <code>oClassInfo</code> might contain three kinds of informations: * <ul> * <li><code>metadata:</code> an (optional) object literal with metadata about the class. * The information in the object literal will be wrapped by an instance of {@link sap.ui.base.Metadata Metadata} * and might contain the following information * <ul> * <li><code>interfaces:</code> {string[]} (optional) set of names of implemented interfaces (defaults to no interfaces)</li> * <li><code>publicMethods:</code> {string[]} (optional) list of methods that should be part of the public * facade of the class</li> * <li><code>abstract:</code> {boolean} (optional) flag that marks the class as abstract (purely informational, defaults to false)</li> * <li><code>final:</code> {boolean} (optional) flag that marks the class as final (defaults to false)</li> * </ul> * Subclasses of sap.ui.base.Object can enrich the set of supported metadata (e.g. see {@link sap.ui.core.Element.extend}). * </li> * * <li><code>constructor:</code> a function that serves as a constructor function for the new class. * If no constructor function is given, the framework creates a default implementation that delegates all * its arguments to the constructor function of the base class. * </li> * * <li><i>any-other-name:</i> any other property in the <code>oClassInfo</code> is copied into the prototype * object of the newly created class. Callers can thereby add methods or properties to all instances of the * class. But be aware that the given values are shared between all instances of the class. Usually, it doesn't * make sense to use primitive values here other than to declare public constants. * </li> * * </ul> * * The prototype object of the newly created class uses the same prototype as instances of the base class * (prototype chaining). * * A metadata object is always created, even if there is no <code>metadata</code> entry in the <code>oClassInfo</code> * object. A getter for the metadata is always attached to the prototype and to the class (constructor function) * itself. * * Last but not least, with the third argument <code>FNMetaImpl</code> the constructor of a metadata class * can be specified. Instances of that class will be used to represent metadata for the newly created class * and for any subclass created from it. Typically, only frameworks will use this parameter to enrich the * metadata for a new class hierarchy they introduce (e.g. {@link sap.ui.core.Element.extend Element}). * * @param {string} sClassName name of the class to be created * @param {object} [oClassInfo] structured object with informations about the class * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.base.Metadata. * @return {function} the created class / constructor function * @public * @static * @name sap.ui.base.Object.extend * @function * @since 1.3.1 */ /** * Creates metadata for a given class and attaches it to the constructor and prototype of that class. * * After creation, metadata can be retrieved with getMetadata(). * * The static info can at least contain the following entries: * <ul> * <li>baseType: {string} fully qualified name of a base class or empty * <li>publicMethods: {string} an array of method names that will be visible in the interface proxy returned by {@link #getInterface} * </ul> * * @param {string} sClassName name of an (already declared) constructor function * @param {object} oStaticInfo static info used to create the metadata object * @param {string} oStaticInfo.baseType qualified name of a base class * @param {string[]} oStaticInfo.publicMethods array of names of public methods * @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.base.Metadata. * * @return {sap.ui.base.Metadata} the created metadata object * @public * @static * @deprecated Since 1.3.1. Use the static <code>extend</code> method of the desired base class (e.g. {@link sap.ui.base.Object.extend}) */ BaseObject.defineClass = function(sClassName, oStaticInfo, FNMetaImpl) { // create Metadata object var oMetadata = new (FNMetaImpl || Metadata)(sClassName, oStaticInfo); var fnClass = oMetadata.getClass(); fnClass.getMetadata = fnClass.prototype.getMetadata = jQuery.sap.getter(oMetadata); // enrich function if ( !oMetadata.isFinal() ) { fnClass.extend = function(sSCName, oSCClassInfo, fnSCMetaImpl) { return Metadata.createClass(fnClass, sSCName, oSCClassInfo, fnSCMetaImpl || FNMetaImpl); }; } jQuery.sap.log.debug("defined class '" + sClassName + "'" + (oMetadata.getParent() ? " as subclass of " + oMetadata.getParent().getName() : "") ); return oMetadata; }; return BaseObject; }, /* bExport= */ true);
fconFGDCA/DetailCADA
resources/sap/ui/base/Object-dbg.js
JavaScript
apache-2.0
7,548
package lx.af.utils.UIL.displayer; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.os.Build; import android.renderscript.Allocation; import android.renderscript.Element; import android.renderscript.RSRuntimeException; import android.renderscript.RenderScript; import android.renderscript.ScriptIntrinsicBlur; import android.view.View; /** * Copyright (C) 2015 Wasabeef * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * import from https://github.com/wasabeef/Blurry */ class Blur { public static Bitmap of(View view, BlurFactor factor) { view.setDrawingCacheEnabled(true); view.destroyDrawingCache(); view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW); Bitmap cache = view.getDrawingCache(); Bitmap bitmap = of(view.getContext(), cache, factor); cache.recycle(); return bitmap; } public static Bitmap of(Context context, Bitmap source, BlurFactor factor) { int width = factor.width / factor.sampling; int height = factor.height / factor.sampling; if (width == 0 || height == 0) { return null; } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.scale(1 / (float) factor.sampling, 1 / (float) factor.sampling); Paint paint = new Paint(); paint.setFlags(Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG); PorterDuffColorFilter filter = new PorterDuffColorFilter(factor.color, PorterDuff.Mode.SRC_ATOP); paint.setColorFilter(filter); canvas.drawBitmap(source, 0, 0, paint); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { try { bitmap = Blur.rs(context, bitmap, factor.radius); } catch (RSRuntimeException e) { bitmap = Blur.stack(bitmap, factor.radius, true); } } else { bitmap = Blur.stack(bitmap, factor.radius, true); } if (factor.sampling == BlurFactor.DEFAULT_SAMPLING) { return bitmap; } else { Bitmap scaled = Bitmap.createScaledBitmap(bitmap, factor.width, factor.height, true); bitmap.recycle(); return scaled; } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public static Bitmap rs(Context context, Bitmap bitmap, int radius) throws RSRuntimeException { RenderScript rs = null; try { rs = RenderScript.create(context); Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); Allocation output = Allocation.createTyped(rs, input.getType()); ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); blur.setInput(input); blur.setRadius(radius); blur.forEach(output); output.copyTo(bitmap); } finally { if (rs != null) { rs.destroy(); } } return bitmap; } public static Bitmap stack(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) { // Stack Blur v1.0 from // http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html // // Java Author: Mario Klingemann <mario at quasimondo.com> // http://incubator.quasimondo.com // created Feburary 29, 2004 // Android port : Yahel Bouaziz <yahel at kayenko.com> // http://www.kayenko.com // ported april 5th, 2012 // This is a compromise between Gaussian Blur and Box blur // It creates much better looking blurs than Box Blur, but is // 7x faster than my Gaussian Blur implementation. // // I called it Stack Blur because this describes best how this // filter works internally: it creates a kind of moving stack // of colors whilst scanning through the image. Thereby it // just has to add one new block of color to the right side // of the stack and remove the leftmost color. The remaining // colors on the topmost layer of the stack are either added on // or reduced by one, depending on if they are on the right or // on the left side of the stack. // // If you are using this algorithm in your code please add // the following line: // // Stack Blur Algorithm by Mario Klingemann <mario@quasimondo.com> Bitmap bitmap; if (canReuseInBitmap) { bitmap = sentBitmap; } else { bitmap = sentBitmap.copy(sentBitmap.getConfig(), true); } if (radius < 1) { return (null); } int w = bitmap.getWidth(); int h = bitmap.getHeight(); int[] pix = new int[w * h]; bitmap.getPixels(pix, 0, w, 0, 0, w, h); int wm = w - 1; int hm = h - 1; int wh = w * h; int div = radius + radius + 1; int r[] = new int[wh]; int g[] = new int[wh]; int b[] = new int[wh]; int rsum, gsum, bsum, x, y, i, p, yp, yi, yw; int vmin[] = new int[Math.max(w, h)]; int divsum = (div + 1) >> 1; divsum *= divsum; int dv[] = new int[256 * divsum]; for (i = 0; i < 256 * divsum; i++) { dv[i] = (i / divsum); } yw = yi = 0; int[][] stack = new int[div][3]; int stackpointer; int stackstart; int[] sir; int rbs; int r1 = radius + 1; int routsum, goutsum, boutsum; int rinsum, ginsum, binsum; for (y = 0; y < h; y++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; for (i = -radius; i <= radius; i++) { p = pix[yi + Math.min(wm, Math.max(i, 0))]; sir = stack[i + radius]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rbs = r1 - Math.abs(i); rsum += sir[0] * rbs; gsum += sir[1] * rbs; bsum += sir[2] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } } stackpointer = radius; for (x = 0; x < w; x++) { r[yi] = dv[rsum]; g[yi] = dv[gsum]; b[yi] = dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (y == 0) { vmin[x] = Math.min(x + radius + 1, wm); } p = pix[yw + vmin[x]]; sir[0] = (p & 0xff0000) >> 16; sir[1] = (p & 0x00ff00) >> 8; sir[2] = (p & 0x0000ff); rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[(stackpointer) % div]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi++; } yw += w; } for (x = 0; x < w; x++) { rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0; yp = -radius * w; for (i = -radius; i <= radius; i++) { yi = Math.max(0, yp) + x; sir = stack[i + radius]; sir[0] = r[yi]; sir[1] = g[yi]; sir[2] = b[yi]; rbs = r1 - Math.abs(i); rsum += r[yi] * rbs; gsum += g[yi] * rbs; bsum += b[yi] * rbs; if (i > 0) { rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; } else { routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; } if (i < hm) { yp += w; } } yi = x; stackpointer = radius; for (y = 0; y < h; y++) { // Preserve alpha channel: ( 0xff000000 & pix[yi] ) pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum]; rsum -= routsum; gsum -= goutsum; bsum -= boutsum; stackstart = stackpointer - radius + div; sir = stack[stackstart % div]; routsum -= sir[0]; goutsum -= sir[1]; boutsum -= sir[2]; if (x == 0) { vmin[y] = Math.min(y + r1, hm) * w; } p = x + vmin[y]; sir[0] = r[p]; sir[1] = g[p]; sir[2] = b[p]; rinsum += sir[0]; ginsum += sir[1]; binsum += sir[2]; rsum += rinsum; gsum += ginsum; bsum += binsum; stackpointer = (stackpointer + 1) % div; sir = stack[stackpointer]; routsum += sir[0]; goutsum += sir[1]; boutsum += sir[2]; rinsum -= sir[0]; ginsum -= sir[1]; binsum -= sir[2]; yi += w; } } bitmap.setPixels(pix, 0, w, 0, 0, w, h); return (bitmap); } static class BlurFactor { public static final int DEFAULT_RADIUS = 25; public static final int DEFAULT_SAMPLING = 1; public int width; public int height; public int radius = DEFAULT_RADIUS; public int sampling = DEFAULT_SAMPLING; public int color = Color.TRANSPARENT; } }
liuxu0703/AppFrame
lib_frame/src/main/java/lx/af/utils/UIL/displayer/Blur.java
Java
apache-2.0
11,479
package org.wso2.carbon.apimgt.rest.api.store.v1; import org.wso2.carbon.apimgt.rest.api.store.v1.*; import org.wso2.carbon.apimgt.rest.api.store.v1.dto.*; import org.apache.cxf.jaxrs.ext.MessageContext; import org.apache.cxf.jaxrs.ext.multipart.Attachment; import org.apache.cxf.jaxrs.ext.multipart.Multipart; import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ErrorDTO; import java.io.File; import java.util.List; import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; public interface ExportApiService { public Response exportApplicationsGet(String appId, MessageContext messageContext); }
pubudu538/carbon-apimgt
components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/ExportApiService.java
Java
apache-2.0
656
# -*- coding: utf-8 -*- # # Copyright 2013 - Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import json from pecan import rest from pecan import abort from wsme import types as wtypes import wsmeext.pecan as wsme_pecan from mistral import exceptions as ex from mistral.api.controllers.v1 import task from mistral.openstack.common import log as logging from mistral.api.controllers import resource from mistral.db import api as db_api from mistral.engine import engine LOG = logging.getLogger(__name__) class Execution(resource.Resource): """Execution resource.""" id = wtypes.text workbook_name = wtypes.text task = wtypes.text state = wtypes.text # Context is a JSON object but since WSME doesn't support arbitrary # dictionaries we have to use text type convert to json and back manually. context = wtypes.text def to_dict(self): d = super(Execution, self).to_dict() if d.get('context'): d['context'] = json.loads(d['context']) return d @classmethod def from_dict(cls, d): e = cls() for key, val in d.items(): if hasattr(e, key): if key == 'context' and val: val = json.dumps(val) setattr(e, key, val) return e class Executions(resource.Resource): """A collection of Execution resources.""" executions = [Execution] class ExecutionsController(rest.RestController): tasks = task.TasksController() @wsme_pecan.wsexpose(Execution, wtypes.text, wtypes.text) def get(self, workbook_name, id): LOG.debug("Fetch execution [workbook_name=%s, id=%s]" % (workbook_name, id)) values = db_api.execution_get(workbook_name, id) if not values: abort(404) else: return Execution.from_dict(values) @wsme_pecan.wsexpose(Execution, wtypes.text, wtypes.text, body=Execution) def put(self, workbook_name, id, execution): LOG.debug("Update execution [workbook_name=%s, id=%s, execution=%s]" % (workbook_name, id, execution)) values = db_api.execution_update(workbook_name, id, execution.to_dict()) return Execution.from_dict(values) @wsme_pecan.wsexpose(Execution, wtypes.text, body=Execution, status_code=201) def post(self, workbook_name, execution): LOG.debug("Create execution [workbook_name=%s, execution=%s]" % (workbook_name, execution)) try: context = None if execution.context: context = json.loads(execution.context) values = engine.start_workflow_execution(execution.workbook_name, execution.task, context) except ex.MistralException as e: #TODO(nmakhotkin) we should use thing such a decorator here abort(400, e.message) return Execution.from_dict(values) @wsme_pecan.wsexpose(None, wtypes.text, wtypes.text, status_code=204) def delete(self, workbook_name, id): LOG.debug("Delete execution [workbook_name=%s, id=%s]" % (workbook_name, id)) db_api.execution_delete(workbook_name, id) @wsme_pecan.wsexpose(Executions, wtypes.text) def get_all(self, workbook_name): LOG.debug("Fetch executions [workbook_name=%s]" % workbook_name) executions = [Execution.from_dict(values) for values in db_api.executions_get(workbook_name)] return Executions(executions=executions)
dzimine/mistral
mistral/api/controllers/v1/execution.py
Python
apache-2.0
4,285
# Lobaria flava var. tarokoensis Inumaru VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Lobaria flava var. tarokoensis Inumaru ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Lecanoromycetes/Peltigerales/Lobariaceae/Lobaria/Lobaria flava/Lobaria flava tarokoensis/README.md
Markdown
apache-2.0
205
# # Cookbook Name:: apache2 # Recipe:: setenvif # # Copyright 2008-2013, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # apache_module 'setenvif' do conf true end
roshan4074/mychefwork
cookbooks/apache2/recipes/mod_setenvif.rb
Ruby
apache-2.0
702
// Copyright 2015 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import module from 'config/module'; import {resolveResource} from 'config/stateconfig'; describe('StateConfig for config list', () => { /** @type {!common/dataselect/dataselect_service.DataSelectService} */ let kdDataSelectService; beforeEach(() => { angular.mock.module(module.name); angular.mock.inject((_kdDataSelectService_) => { kdDataSelectService = _kdDataSelectService_; }); }); it('should resolve config', angular.mock.inject(($q) => { let promise = $q.defer().promise; let resource = jasmine.createSpyObj('$resource', ['get']); resource.get.and.callFake(function() { return {$promise: promise}; }); let actual = resolveResource(resource, {namespace: 'foo-ns'}, kdDataSelectService); expect(resource.get) .toHaveBeenCalledWith(kdDataSelectService.getDefaultResourceQuery('foo-ns')); expect(actual).toBe(promise); })); });
danielromlein/dashboard
src/test/frontend/config/stateconfig_test.js
JavaScript
apache-2.0
1,519
package com.seleniumtests.connectors.tms.squash; import org.json.JSONObject; import org.testng.ITestResult; import com.seleniumtests.connectors.tms.TestManager; import com.seleniumtests.connectors.tms.squash.entities.Campaign; import com.seleniumtests.connectors.tms.squash.entities.Iteration; import com.seleniumtests.connectors.tms.squash.entities.IterationTestPlanItem; import com.seleniumtests.connectors.tms.squash.entities.TestPlanItemExecution.ExecutionStatus; import com.seleniumtests.core.utils.TestNGResultUtils; import com.seleniumtests.customexception.ConfigurationException; public class SquashTMConnector extends TestManager { private String user; private String password; private String serverUrl; private String project; private SquashTMApi api; public SquashTMConnector() { // to be called with init method } public SquashTMConnector(String url, String user, String password, String project) { this(); JSONObject config = new JSONObject(); config.put(TMS_SERVER_URL, url); config.put(TMS_USER, user); config.put(TMS_PASSWORD, password); config.put(TMS_PROJECT, project); init(config); } @Override public void recordResult() { // Nothing to do } @Override public void recordResultFiles() { // Nothing to do } @Override public void login() { // no login } @Override public void init(JSONObject connectParams) { String serverUrlVar = connectParams.optString(TMS_SERVER_URL, null); String projectVar = connectParams.optString(TMS_PROJECT, null); String userVar = connectParams.optString(TMS_USER, null); String passwordVar = connectParams.optString(TMS_PASSWORD, null); if (serverUrlVar == null || projectVar == null || userVar == null || passwordVar == null) { throw new ConfigurationException(String.format("SquashTM access not correctly configured. Environment configuration must contain variables" + "%s, %s, %s, %s", TMS_SERVER_URL, TMS_PASSWORD, TMS_USER, TMS_PROJECT)); } serverUrl = serverUrlVar; project = projectVar; user = userVar; password = passwordVar; initialized = true; } @Override public void logout() { // no logout } public SquashTMApi getApi() { if (api == null) { api = new SquashTMApi(serverUrl, user, password, project); } return api; } @Override public void recordResult(ITestResult testResult) { try { SquashTMApi sapi = getApi(); Integer testId = TestNGResultUtils.getTestCaseId(testResult); if (testId == null) { return; } Campaign campaign = sapi.createCampaign("Selenium " + testResult.getTestContext().getName(), ""); Iteration iteration = sapi.createIteration(campaign, TestNGResultUtils.getSeleniumRobotTestContext(testResult).getApplicationVersion()); IterationTestPlanItem tpi = sapi.addTestCaseInIteration(iteration, testId); if (testResult.isSuccess()) { sapi.setExecutionResult(tpi, ExecutionStatus.SUCCESS); } else if (testResult.getStatus() == 2){ // failed sapi.setExecutionResult(tpi, ExecutionStatus.FAILURE); } else { // skipped or other reason sapi.setExecutionResult(tpi, ExecutionStatus.BLOCKED); } } catch (Exception e) { logger.error(String.format("Could not record result for test method %s: %s", TestNGResultUtils.getTestName(testResult), e.getMessage())); } } @Override public void recordResultFiles(ITestResult testResult) { // TODO Auto-generated method stub } }
bhecquet/seleniumRobot
core/src/main/java/com/seleniumtests/connectors/tms/squash/SquashTMConnector.java
Java
apache-2.0
3,438
name 'test' version '0.0.0' depends 'systemd' depends 'yum' depends 'apt' depends 'debian' depends 'chef-sugar'
nathwill/chef-systemd
test/fixtures/cookbooks/test/metadata.rb
Ruby
apache-2.0
113
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags --> <title>Crawling Result</title> <!-- Bootstrap core CSS --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> <style> .row > div > img { max-width: 100%; height: auto; display: block; } </style> </head> <body> <div class="container"> <div class="page-header"> <h1>Crawling Result</h1> </div> <div id="summary"> <h3>Summary (<a href="state.html" target="_blank">State diagram</a>)</h3> <div class="row"> <div class="col-md-4">Depth of crawling</div> <div class="col-md-8"><span id="depth">2</span></div> </div> <div class="row"> <div class="col-md-4">Time elapsed</div> <div class="col-md-8"><span id="time">0.97</span> minutes</div> </div> <div class="row"> <div class="col-md-4">Candidate clickables found</div> <div class="col-md-8"><span id="total">20</span></div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3">Triggering</div> <div class="col-md-8"><span id="true">8</span></div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3">Non-triggering</div> <div class="col-md-8"><span id="false">12</span></div> </div> <div class="row"> <div class="col-md-1"></div> <div class="col-md-3">Unexamined</div> <div class="col-md-8"><span id="unexamined">0</span></div> </div> <div class="row"> <div class="col-md-4">Found forms</div> <div class="col-md-8"><span id="form-summary">1</span></div> </div> <div class="row"> <div class="col-md-4">Violated invariants</div> <div class="col-md-8"><span id="invariant-summary">2</span></div> </div> </div> <div id="form"> <h3>Forms (<span id="form-header"></span>)</h3> <div class="row"> <div class="col-md-4"><img src="http://placekitten.com/160/255"></div> <div class="col-md-8"> state: 3, form-id: b2g-monkey-5 (xpath: //html/body/form[1]) <br /> input_value: <br /> type: text, id: id_username (xpath: //html/body/form[1]/p[1]/input[1]), value: pjshzzza <br /> type: password, id: id_password (xpath: //html/body/form[1]/p[2]/input[1]), value: !qaz2wsX <br /> path-to-form: <br /> id: b2g-monkey-3 (xpath: //html/body/p[3]/a[1]) <br /> clickables in the form: <br /> id: b2g-monkey-6 (xpath: //html/body/form[1]/p[3]/a[1]) <br /> id: b2g-monkey-7 (xpath: //html/body/form[1]/p[3]/button[1]) <br /> </div> </div> </div> <div id="invariant"> <h3>Invariants (<span id="invariant-header"></span>)</h3> <div class="row"> <div class="col-md-4"><img src="http://placekitten.com/160/255"></div> <div class="col-md-8"> state: 2, violated invariant: {"name": "file-not-found"} <br /> execution sequence: <br /> id: b2g-monkey-2 (xpath: //html/body/p[2]/a[1]) <br /> </div> </div> </div> <hr> <p class="footer">(c) b2g-monkey</p> </div> <!-- /container --> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="js/bootstrap.min.js"></script> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="js/ie10-viewport-bug-workaround.js"></script> <script> $('#form-header').text($('#form-summary').text()) $('#invariant-header').text($('#invariant-summary').text()) </script> </body> </html>
jwlin/b2g-monkey
web/report.html
HTML
apache-2.0
4,630
# # Cookbook:: jenkins # Attributes:: executor # # Author: Seth Vargo <sethvargo@gmail.com> # # Copyright:: 2013-2016, Chef Software, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default['jenkins']['executor'].tap do |executor| # # This is the number of seconds to wait for Jenkins to become "ready" after a # start, restart, or reload. Since the Jenkins service returns immediately # and the actual Java process is started in the background, we block the Chef # Client run until the service endpoint(s) are _actually_ ready to accept # requests. # executor['timeout'] = 120 # # Deprecated: please use +node.run_state[:jenkins_private_key]+ instead. # executor['private_key'] = nil # # If you need to pass through a proxy to communicate between your masters and # slaves, you will need to set this node attribute. It should be set in the # form `HOST:PORT`: # # node.normal['jenkins']['executor']['proxy'] = '1.2.3.4' # # Please see the +Proxies+ section of the README for more information. # executor['proxy'] = nil # # If you need to specify jvm options for the jenkins cli call, specify them here # You can specify items such as a trust store if you need custom ca certs, for example. # executor['jvm_options'] = nil # # CLI protocol [ssh|http|remoting] # executor['protocol'] = 'remoting' # # CLI user to pass for ssh/https protocol # # executor['cli_user'] = 'example_chef_user' end
dshvedchenko/jenkins
attributes/executor.rb
Ruby
apache-2.0
1,975
#!/bin/bash #set -o xtrace #This script use for generate gamegrop of #blew function is used to generate xml for virtualhost #create asher 20150114 #modifyed 20151130 add two line and diffirent infrastraction game #modifyed change to No Pxe Pc game intall , used direct change disk basepath=$(dirname "$(readlink -f "$0")") #绝对路径 #DATE=`date +%Y%m%d` DATE=`date "+%Y%m%d%H%M"` #DATE=`date +%Y_%m_%d_%H_%M` RESULTS=/export/works/createvhost INSTALLPATH=/export/tmp PATHFILE=${INSTALLPATH}/$DATE mkdir -p $RESULTS > /dev/null mkdir -p $INSTALLPATH > /dev/null mkdir -p $PATHFILE > /dev/null VhostImage=/export/VirMachines #宿主机上虚拟机的磁盘文件位置 InforForCMDB=$PATHFILE/ForImportCMDB_${DATE}.csv #此文件用于生成导入cmdb的信息 XMLPATH=${basepath}/NoPxePcGame/XML PathImag=/export/idcs/kvm_img/ #PathImag=/export/KVM_IMG function Coloer() { ## just some color YS='\033[0m' YSr='\033[31m' #red YSg='\033[32m' #green YSy='\033[33m' #yellow YSbl='\033[34m' #blue YSp='\033[35m' #purple YSsb='\033[36m' #sky blue YSw='\033[37m' #white YSwbk='\033[40;37m' #white on black YSwr='\033[41;37m' #white on red YSwg='\033[42;37m' #white on green YSwy='\033[43;37m' #white on yellow YSwbe='\033[44;37m' #white on blue YSwp='\033[45;37m' #white on purple YSwp='\033[46;37m' #white on purple YSbkw='\033[47;30m' #black on white } function GenerateXml() { yes | /bin/cp $XMLPATH/M_MODEL.xml $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml VHOST=`echo v_${GroupName}_${gameserver}` UUID1=`uuidgen` MAC1=`python -c "from virtinst.util import randomMAC;print randomMAC(type='qemu')"` FMAC=`echo $MAC1 |awk -F: '{print $1":"$2":"$3":"$4":"$5}'` LMAC=`echo $MAC1 |awk -F: '{print $6}'` NUM16=`echo $((16#$LMAC))` if [ $NUM16 = "255" ] then GenerateXml fi REMAC=`echo $[$NUM16 + 1]` LMAC2=`printf "%02x" $REMAC` MAC2=${FMAC}":"${LMAC2} sed -i "s/TVHOST/$VHOST/g" $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml sed -i "s/TUUID1/$UUID1/g" $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml sed -i "s/TMAC1/$MAC1/g" $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml sed -i "s/TMAC2/$MAC2/g" $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml sed -i "s/MEMORY/$VMEMORY/g" $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml sed -i "s/VNCIP/$WNIP/g" $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml if [ $NUM16 = "255" ] then GenerateXml fi } function EditImg() { #eth1 1 ip address and eth0 1 ip if 2 ipress on eth1 ,this function cant do it. /usr/bin/guestfish -a $PATHFILE/$WNIP/v_${GroupName}_${gameserver}_root.img -i <<EOF glob rm-rf /etc/sysconfig/network-scripts/ifcfg-eth* glob rm-rf /etc/sysconfig/network-scripts/route-* glob rm-rf /etc/openvpn/*254* write /etc/hosts "127.0.0.1 localhost.localdomain localhost\n${GroupIP}.254 manager\n${GroupIP}.11 game1\n${GroupIP}.31 database\n${GroupIP}.32 backup\n" write /etc/udev/rules.d/70-persistent-net.rules "" write /etc/sysconfig/network "NETWORKING=yes\nHOSTNAME=${gameserver}\n" write /etc/sysconfig/network-scripts/ifcfg-eth0 "DEVICE=eth0\nBOOTPROTO=static\nONBOOT=yes\nADDRESS=$MAC1\nIPADDR=${NIP1}\nNETMASK=255.255.255.0\nTYPE=Ethernet\n" write /etc/sysconfig/network-scripts/ifcfg-eth1 "DEVICE=eth1\nBOOTPROTO=static\nONBOOT=yes\nADDRESS=$MAC2\nIPADDR=${asher1}\nNETMASK=${asher2}\nGATEWAY=${asher3}\n" EOF } function EditBkImg() { #just for two ip address on eth1 /usr/bin/guestfish -a $PATHFILE/$WNIP/v_${GroupName}_${gameserver}_root.img -i <<EOF glob rm-rf /etc/openvpn/*254* glob rm-rf /etc/sysconfig/network-scripts/ifcfg-eth* write /etc/hosts "127.0.0.1 localhost.localdomain localhost\n${GroupIP}.254 manager\n${GroupIP}.11 game1\n${GroupIP}.31 database\n${GroupIP}.32 backup\n" write /etc/udev/rules.d/70-persistent-net.rules " " write /etc/sysconfig/network "NETWORKING=yes\nHOSTNAME=${gameserver}\n" write /etc/sysconfig/network-scripts/ifcfg-eth0 "DEVICE=eth0\nBOOTPROTO=static\nONBOOT=yes\nADDRESS=$MAC1\nIPADDR=${NIP1}\nNETMASK=255.255.255.0\nTYPE=Ethernet\n" write /etc/sysconfig/network-scripts/ifcfg-eth1 "DEVICE=eth1\nBOOTPROTO=static\nONBOOT=yes\nADDRESS=$MAC2\nIPADDR=${asher1}\nNETMASK=${asher2}\nGATEWAY=${asher3}\n" write /etc/sysconfig/network-scripts/ifcfg-${ETH} "DEVICE=eth1:1\nBOOTPROTO=static\nONBOOT=yes\nADDRESS=$MAC2\nIPADDR=${asher4}\nNETMASK=${asher2}\n" EOF } function DoDisk () { if [ "$gameserver" = 'backup' ] then if [ "$OS_ver" = '4.8' ] then ETH=eth1\.1 else ETH=eth1\:1 fi asher1=$WIP2 asher2=${GMASK} asher3=${GGATEWAY} asher4=$WIP3 EditBkImg elif [ "$gameserver" = 'manager' ] then asher1=$WIP1 asher2=${GMASK} asher3=${GGATEWAY} EditImg elif [ "$Line" = '2' ] then if [ "$gameserver" = 'game1' ] then if [ "$OS_ver" = '4.8' ] then ETH=eth1\.1 else ETH=eth1\:1 fi asher1=${ANWIP} asher2=${ANGMASK} asher3=${ANGATEWAY} asher4=$${ANWIP2} EditBkImg EditImg else asher1=0 asher2=0 asher3=0 EditImg fi else asher1=0 asher2=0 asher3=0 EditImg fi } #get stg from phycical server function GetStg() { S1=`/usr/bin/ssh -p$Port_SSH $WNIP "dmidecode | grep 'Serial Number' | head -n1 |awk -F: '{print $2}'"` STG=`echo $S1 | awk '{print $3}'` ssh -p$Port_SSH $WNIP "mkdir -p $VhostImage" } #use for update to asset platform function Makexls() { if [ "$gameserver" = 'manager' ] then printf "%s,%s,6,%s,\"/dev/vda1|/|100G,/dev/vdb|/export|500G\",%s,\"\"\"游戏\"\"\",CentOS release %s,64,3.4.95.R620.CentOS6.5-x86_64.OpenBeta.KVM,\"\"\"是\"\"\",\"eth0|%s|%s,eth1|%s|%s\" \n" $STG $UUID1 $VMEMORY $gameserver $OS_ver $MAC1 $NIP1 $MAC2 $WWIPS >> $InforForCMDB elif [ "$gameserver" = 'backup' ] then printf "%s,%s,6,%s,\"/dev/vda|/|500G\",%s,\"\"\"游戏\"\"\",CentOS release %s,64,3.4.95.R620.CentOS6.5-x86_64.OpenBeta.KVM,\"\"\"是\"\"\",\"eth0|%s|%s,eth1|%s|%s,eth1:1|%s|%s\" \n" $STG $UUID1 $VMEMORY $gameserver $OS_ver $MAC1 $NIP1 $MAC2 $WWIPS $MAC2 $WWIPS1 >> $InforForCMDB elif [ "$Line" = '2' ] then if [ "$gameserver" = 'game1' ] then printf "%s,%s,6,%s,\"/dev/vda|/|500G\",%s,\"\"\"游戏\"\"\",CentOS release %s,64,3.4.95.R620.CentOS6.5-x86_64.OpenBeta.KVM,\"\"\"是\"\"\",\"eth0|%s|%s,eth1|%s|%s,eth1:1|%s|%s\" \n" $STG $UUID1 $VMEMORY $gameserver $OS_ver $MAC1 $NIP1 $MAC2 $ANWIP $MAC2 $ANWIP2 >> $InforForCMDB # printf "%s,%s,6,%s,\"/dev/vda1|/|100G,/dev/vdb|/export|500G\",%s,\"\"\"游戏\"\"\",CentOS release %s,64,3.4.95.R620.CentOS6.5-x86_64.OpenBeta.KVM,\"\"\"是\"\"\",\"eth0|%s|%s,eth1|%s|%s\" \n" $STG $UUID1 $VMEMORY $gameserver $OS_ver $MAC1 $NIP1 $MAC2 $ANWIP >> $InforForCMDB else printf "%s,%s,6,%s,\"/dev/vda|/|300G\",%s,\"\"\"游戏\"\"\",CentOS release %s,64,3.4.95.R620.CentOS6.5-x86_64.OpenBeta.KVM,\"\"\"是\"\"\",\"eth0|%s|%s\" \n" $STG $UUID1 $VMEMORY $gameserver $OS_ver $MAC1 $NIP1 >> $InforForCMDB fi else printf "%s,%s,6,%s,\"/dev/vda|/|300G\",%s,\"\"\"游戏\"\"\",CentOS release %s,64,3.4.95.R620.CentOS6.5-x86_64.OpenBeta.KVM,\"\"\"是\"\"\",\"eth0|%s|%s\" \n" $STG $UUID1 $VMEMORY $gameserver $OS_ver $MAC1 $NIP1 >> $InforForCMDB fi } #copy virtual server xml to phycical server. function SCopyXml() { scp -P $Port_SSH $PATHFILE/$WNIP/v_${GroupName}_$gameserver.xml $WNIP:/etc/libvirt/qemu/ } function StartVM() { ssh -p $Port_SSH $WNIP "virsh create /etc/libvirt/qemu/v_${GroupName}_$gameserver.xml" } function ScpDisk() { scp -P $Port_SSH $PATHFILE/$WNIP/v_${GroupName}_$gameserver*.img $WNIP:/${VhostImage} rm -f $PATHFILE/$WNIP/v_${GroupName}_$gameserver*.img } function CopyDisk() { if [ "$gameserver" = 'manager' ] then /bin/cp ${PathImag}/${ImgName}_manager_root.img $PATHFILE/$WNIP/v_${GroupName}_${gameserver}_root.img /bin/cp ${PathImag}/${ImgName}_manager_export.img $PATHFILE/$WNIP/v_${GroupName}_${gameserver}_export.img else /bin/cp ${PathImag}/${ImgName}_others_root.img $PATHFILE/$WNIP/v_${GroupName}_${gameserver}_root.img /bin/cp ${PathImag}/${ImgName}_others_export.img $PATHFILE/$WNIP/v_${GroupName}_${gameserver}_export.img fi } function ChooseIMG() { echo "选择要创建的虚拟机模板,并复制镜像名称" ALLIMG=`ls $PathImag -l | grep img | awk '{print $9}' | grep -v '^$' | awk -F_ '{print $1"_"$2}' | uniq` echo "${ALLIMG}" echo -n "请选择>:" read ImgName echo } function ChooseGW(){ echo -e "${YSg}根据选项选择或者输入网关:${YS}" select var in "$1.1" "$1.254" "others" do case $var in "$1.1") ;; "$1.254") ;; "others") echo -n -e "${YSg}please input gateway ip:${YS}" read var;; *) echo -e "${YSr}Wrong select${YS}" exit 0;; esac break done } function ChooseMASK(){ echo -e "${YSg}根据选项选择或者输入掩码:${YS}" select var in "255.255.255.0" "255.255.255.128" "others" do case $var in "255.255.255.0") ;; "255.255.255.128") ;; "others") echo -n -e "${YSr}please input mask:>${YS}" read var;; *) echo "${YSr}Wrong select.${YS}" exit 0;; esac break done } #generate vhost xml for start and create vhost on each phycical host #generate asset info use it to input cmdb function Operate() { GetStg GenerateXml Makexls CopyDisk DoDisk SCopyXml ScpDisk sleep 2 StartVM } #main script start: function SelectOS() { #echo -e "\t" "\e[0;33mInput Which GameServer,OS System and Network Line \e[00m" select var in "CentOS4.8" "CentOS5.7" "CentOS6.3" "CentOS6.4" "CentOS6.5" "Others" do case $var in "CentOS4.8") OS_ver=4.8;; "CentOS5.7") OS_ver=5.7;; "CentOS6.3") OS_ver=6.3;; "CentOS6.4") OS_ver=6.4;; "CentOS6.5") OS_ver=6.5;; "Others") echo "Input the OS version" echo -e -n "${YSg}Just input number like${YS} ${YSr}4.8${YS}:" read OS_ver echo -e "${YSg}Your input OS system is:${YS} ${YSr} ${OS_ver}${YS}";; *) echo "Wrong Select" exit 0;; esac break done } function SelectGlobalIP() { # because some game group use game1 for it's anothers Global line, Tel or Unicom # so this function use for this selection #. coloer.sh #echo -e "${YSr}I'm red coloer${Cend}" echo -e "${YSg}Select the Global ip if game1 use a${YS} ${YSbl}diffent ip address with backup${YS}, select ${YSr}2 or 1${YS}>" echo -e -n "${YSg}多线还是单线${YS}, 单线选择2,单线选择1: ${YSr}2 or 1${YS}>" read Line ### one line or two line must input below inforation before if echo -e "${YSg}please input Global ip address like:${YS}${YSr} 123.234.456 10>${YS}" echo -n -e "${YSg}输入manager、backup外网ip地址:${YS}${YSr} 123.234.456 10>${YS}" read WIPD WP1 WIP1=${WIPD}"."${WP1} ((WP1++)) WIP2=${WIPD}"."${WP1} ((WP1++)) WIP3=${WIPD}"."${WP1} echo "please select Globle ip netmask address :" echo -e "虚拟机外网掩码:>" ChooseMASK GMASK=$var echo "please select Globle ip gateway address :" echo -e "虚拟机外网网关:" ChooseGW $WIPD GGATEWAY=$var ###### #echo "Globle ip is :$WIP1,$WIP2,${WIP3}. mask:$GMASK,gateway:$GGATEWAY" ### if [ "$Line" = "2" ]; then echo -e "${YSg}Please input Anothers Global ip and it's relation information${YS}" echo -e "${YSg}输入game1外网ip及其他相关信息${YS}" echo -n -e "${YSg}Input anothers globle ip for game1:${YS} ${YSwg} 211.100.255.1>${YS}" read ANWIP echo -e -n "${YSr}Input ${ANWIP}'s Mask:>${YS}" echo -e "虚拟机外网掩码:>" ChooseMASK ANGMASK=$var echo -e -n "${YSr}Input ${ANWIP} gateway:>${YS}" echo -e "虚拟机外网网关:" ANWIPPRE=`echo $ANWIP | awk -F. '{print $1"."$2"."$3}'` ANWIPPRES=`echo $ANWIP | awk -F. '{print $4}'` ChooseGW $ANWIPPRE ANWIP2=${ANWIPPRE}.$((ANWIPPRES + 1)) ANGATEWAY=$var fi if [ "$Line" = "2" ]; then python -c "print('*' * 50)" echo -e "${YSg}Globle ip is :${YS}${YSbkw}$WIP1,$WIP2,${WIP3}.${YS} mask:${YSbkw}$GMASK${YS},gateway:${YSbkw}$GGATEWAY${YS}" echo -e "${YSg}manager、backup外网ip:${YS}${YSbkw}$WIP1,$WIP2,${WIP3}.${YS} mask:${YSbkw}$GMASK${YS},gateway:${YSbkw}$GGATEWAY${YS}" python -c "print('*' * 50)" echo -e "${YSg}Anothers line Global ip:${YS}${YSbkw}${ANWIP} 和 ${ANWIP2} ${YS} Mask:${YSbkw}${ANGMASK}${YS}.Gateway:${YSbkw}${ANGATEWAY}${YS}" echo -e "${YSg}game1外网 ip:${YS}${YSbkw}${ANWIP} 和 ${ANWIP2} ${YS} Mask:${YSbkw}${ANGMASK}${YS}.Gateway:${YSbkw}${ANGATEWAY}${YS}" else python -c "print('*' * 50)" echo -e "${YSg}Globle ip is :${YS}${YSbkw}$WIP1,$WIP2,${WIP3}.${YS} mask:${YSbkw}$GMASK${YS},gateway:${YSbkw}$GGATEWAY${YS}" echo -e "${YSg}manager、backup外网ip:${YS}${YSbkw}$WIP1,$WIP2,${WIP3}.${YS} mask:${YSbkw}$GMASK${YS},gateway:${YSbkw}$GGATEWAY${YS}" fi } function ChooseSshPort(){ echo -e "${YSg}请输入管理机到宿主机的ssh端口:${YS}" select var in "22" "22222" "others port" do case $var in "22") Port_SSH=$var;; "22222") Port_SSH=$var;; "others port") echo -n -e "${YSr}please input your ssh port:>${YS}" read Port_SSH;; *) echo "${YSr}Wrong select.${YS}" exit 0;; esac break done } function CmdbTitle() { echo ams_st","os_st","os_cpu","os_memory","os_disk","os_hostname","os_purpose","os_os","os_os_bits","os_kernel","os_is_virtual","os_net > $InforForCMDB } function Main() { # input the vhost host echo -e "${YSg}input PhycialHost ip address in order to run virtul server${YS}" echo -e "${YSg}输入运行虚拟机的的物理机的ip地址(内网):${YS}" echo -e "${YSg}Input 2 PhycialServer Ip: ${YS}" echo -e "${YSg}such as:${YS}${YSwg} 192.168.100.4${YS} ${YSbl}192.168.100.5:>${YS}" echo -e -n "${YSg}输入2台内网ip地址,或者 输入2个一样的内网地址: ${YS}" read PHOSTIP1 PHOSTIP2 /bin/mkdir -p $PATHFILE/$PHOSTIP1 /bin/mkdir -p $PATHFILE/$PHOSTIP2 echo -e "${YSg}Input Group of virtual game server name and ip:${YS}${YSwg}wuxi100>${YS}" echo -n -e "${YSg}输入虚拟机游戏组名称:${YS}${YSwg}wuxi100>${YS}" #GroupName is the name of group fo this virtul host read GroupName echo -e "${YSg}Input Group of virtual game server's ip:${YS}${YSwg}172.16.10>${YS}" echo -n -e "${YSg}输入虚拟机组的内网ip段:${YS}${YSwg}172.16.10>${YS}" #GroupName is the name of group fo this virtul host read GroupIP InforForCMDB=$RESULTS/${Date}_${GroupName}${GroupIP}${Date}_${PHOSTIP1}_${PHOSTIP2}_importCMDB.csv echo -e "${YSr}please check you input info:${YS}" echo -e "${YSr}请检查:${YS}" python -c "print('*' * 50)" echo -e "${YSg}PhycialHost ip:${YS}${YSbl}$PHOSTIP1 $PHOSTIP2${YS}" echo -e "${YSg}GroupName is :${YS}${YSbl}$GroupName${YS}" echo -e "${YSg}GroupIP is :${YS}${YSbl}$GroupIP${YS}" python -c "print('*' * 50)" ChooseSshPort } function Choose(){ echo -e "${YSg}please check, if info is right yes or no${YS}" echo -e -n "${YSwp}yes or no:$YS" read anser python -c "print('*' * 50)" if [ "$anser" = "yes" ] then echo else exit 0 fi } function Run() { GroupServer1='manager database backup game1' GroupServer=$GroupServer1 CmdbTitle for gameserver in $GroupServer do case $gameserver in manager) { VMEMORY='25165824' NIP1=${GroupIP}"."254 echo $gameserver echo $NIP1 WWIPS=$WIP1 #Global ip for this vhost WNIP=`echo $PHOSTIP1` Operate #run }& ;; game1) { VMEMORY='33554432' echo $gameserver NIP1=${GroupIP}"."11 echo $NIP1 WNIP=`echo $PHOSTIP2` Operate #run }& ;; database) { VMEMORY='33554432' echo $gameserver NIP1=${GroupIP}"."31 echo $NIP1 WNIP=`echo $PHOSTIP1` Operate & #run }& ;; backup) { VMEMORY='25165824' echo $gameserver NIP1=${GroupIP}"."32 echo $NIP1 WWIPS="$WIP2" WWIPS1="$WIP3" WNIP=`echo $PHOSTIP2` Operate #run }& ;; esac done } ###################################everything is run ######################### Coloer # put Coloer in ChooseIMG Main #input groupname and phycical server SelectOS #choose which os SelectGlobalIP #input Global ip address Choose # choose go and reinput Run # main function echo "........................... 配置虚拟机脚本已在后台执行中,需等待3~5分钟多.................." #GenerateInstallScript #generate instal script for pxe system install #/bin/cp $PATHFILE/${GroupName}.xml $INSTALLPATH #cat $PATHFILE/virtinfo >>${INSTALLPATH}/virinfo
lichengshuang/createvhost
others/oldcreatevhosts/noPxePcGame/chiBi-toPcGameVirthost.sh
Shell
apache-2.0
16,858
package com.sksamuel.scapegoat.inspections.empty import com.sksamuel.scapegoat._ /** * @author Stephen Samuel */ class EmptyIfBlock extends Inspection( text = "Empty if expression", defaultLevel = Levels.Warning, description = "Checks for empty if blocks.", explanation = "An empty if block is considered as dead code." ) { def inspector(context: InspectionContext): Inspector = new Inspector(context) { override def postTyperTraverser = new context.Traverser { import context.global._ override def inspect(tree: Tree): Unit = { tree match { case If(_, Literal(Constant(())), _) => context.warn(tree.pos, self, tree.toString.take(500)) case _ => continue(tree) } } } } }
sksamuel/scalac-scapegoat-plugin
src/main/scala/com/sksamuel/scapegoat/inspections/empty/EmptyIfBlock.scala
Scala
apache-2.0
840
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/imagebuilder/Imagebuilder_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/imagebuilder/model/Platform.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace imagebuilder { namespace Model { /** * <p>An image semantic version.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/imagebuilder-2019-12-02/ImageVersion">AWS * API Reference</a></p> */ class AWS_IMAGEBUILDER_API ImageVersion { public: ImageVersion(); ImageVersion(Aws::Utils::Json::JsonView jsonValue); ImageVersion& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline const Aws::String& GetArn() const{ return m_arn; } /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; } /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline ImageVersion& WithArn(const Aws::String& value) { SetArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline ImageVersion& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the image semantic version.</p> */ inline ImageVersion& WithArn(const char* value) { SetArn(value); return *this;} /** * <p>The name of the image semantic version.</p> */ inline const Aws::String& GetName() const{ return m_name; } /** * <p>The name of the image semantic version.</p> */ inline bool NameHasBeenSet() const { return m_nameHasBeenSet; } /** * <p>The name of the image semantic version.</p> */ inline void SetName(const Aws::String& value) { m_nameHasBeenSet = true; m_name = value; } /** * <p>The name of the image semantic version.</p> */ inline void SetName(Aws::String&& value) { m_nameHasBeenSet = true; m_name = std::move(value); } /** * <p>The name of the image semantic version.</p> */ inline void SetName(const char* value) { m_nameHasBeenSet = true; m_name.assign(value); } /** * <p>The name of the image semantic version.</p> */ inline ImageVersion& WithName(const Aws::String& value) { SetName(value); return *this;} /** * <p>The name of the image semantic version.</p> */ inline ImageVersion& WithName(Aws::String&& value) { SetName(std::move(value)); return *this;} /** * <p>The name of the image semantic version.</p> */ inline ImageVersion& WithName(const char* value) { SetName(value); return *this;} /** * <p>The semantic version of the image semantic version.</p> */ inline const Aws::String& GetVersion() const{ return m_version; } /** * <p>The semantic version of the image semantic version.</p> */ inline bool VersionHasBeenSet() const { return m_versionHasBeenSet; } /** * <p>The semantic version of the image semantic version.</p> */ inline void SetVersion(const Aws::String& value) { m_versionHasBeenSet = true; m_version = value; } /** * <p>The semantic version of the image semantic version.</p> */ inline void SetVersion(Aws::String&& value) { m_versionHasBeenSet = true; m_version = std::move(value); } /** * <p>The semantic version of the image semantic version.</p> */ inline void SetVersion(const char* value) { m_versionHasBeenSet = true; m_version.assign(value); } /** * <p>The semantic version of the image semantic version.</p> */ inline ImageVersion& WithVersion(const Aws::String& value) { SetVersion(value); return *this;} /** * <p>The semantic version of the image semantic version.</p> */ inline ImageVersion& WithVersion(Aws::String&& value) { SetVersion(std::move(value)); return *this;} /** * <p>The semantic version of the image semantic version.</p> */ inline ImageVersion& WithVersion(const char* value) { SetVersion(value); return *this;} /** * <p>The platform of the image semantic version.</p> */ inline const Platform& GetPlatform() const{ return m_platform; } /** * <p>The platform of the image semantic version.</p> */ inline bool PlatformHasBeenSet() const { return m_platformHasBeenSet; } /** * <p>The platform of the image semantic version.</p> */ inline void SetPlatform(const Platform& value) { m_platformHasBeenSet = true; m_platform = value; } /** * <p>The platform of the image semantic version.</p> */ inline void SetPlatform(Platform&& value) { m_platformHasBeenSet = true; m_platform = std::move(value); } /** * <p>The platform of the image semantic version.</p> */ inline ImageVersion& WithPlatform(const Platform& value) { SetPlatform(value); return *this;} /** * <p>The platform of the image semantic version.</p> */ inline ImageVersion& WithPlatform(Platform&& value) { SetPlatform(std::move(value)); return *this;} /** * <p>The owner of the image semantic version.</p> */ inline const Aws::String& GetOwner() const{ return m_owner; } /** * <p>The owner of the image semantic version.</p> */ inline bool OwnerHasBeenSet() const { return m_ownerHasBeenSet; } /** * <p>The owner of the image semantic version.</p> */ inline void SetOwner(const Aws::String& value) { m_ownerHasBeenSet = true; m_owner = value; } /** * <p>The owner of the image semantic version.</p> */ inline void SetOwner(Aws::String&& value) { m_ownerHasBeenSet = true; m_owner = std::move(value); } /** * <p>The owner of the image semantic version.</p> */ inline void SetOwner(const char* value) { m_ownerHasBeenSet = true; m_owner.assign(value); } /** * <p>The owner of the image semantic version.</p> */ inline ImageVersion& WithOwner(const Aws::String& value) { SetOwner(value); return *this;} /** * <p>The owner of the image semantic version.</p> */ inline ImageVersion& WithOwner(Aws::String&& value) { SetOwner(std::move(value)); return *this;} /** * <p>The owner of the image semantic version.</p> */ inline ImageVersion& WithOwner(const char* value) { SetOwner(value); return *this;} /** * <p>The date at which this image semantic version was created.</p> */ inline const Aws::String& GetDateCreated() const{ return m_dateCreated; } /** * <p>The date at which this image semantic version was created.</p> */ inline bool DateCreatedHasBeenSet() const { return m_dateCreatedHasBeenSet; } /** * <p>The date at which this image semantic version was created.</p> */ inline void SetDateCreated(const Aws::String& value) { m_dateCreatedHasBeenSet = true; m_dateCreated = value; } /** * <p>The date at which this image semantic version was created.</p> */ inline void SetDateCreated(Aws::String&& value) { m_dateCreatedHasBeenSet = true; m_dateCreated = std::move(value); } /** * <p>The date at which this image semantic version was created.</p> */ inline void SetDateCreated(const char* value) { m_dateCreatedHasBeenSet = true; m_dateCreated.assign(value); } /** * <p>The date at which this image semantic version was created.</p> */ inline ImageVersion& WithDateCreated(const Aws::String& value) { SetDateCreated(value); return *this;} /** * <p>The date at which this image semantic version was created.</p> */ inline ImageVersion& WithDateCreated(Aws::String&& value) { SetDateCreated(std::move(value)); return *this;} /** * <p>The date at which this image semantic version was created.</p> */ inline ImageVersion& WithDateCreated(const char* value) { SetDateCreated(value); return *this;} private: Aws::String m_arn; bool m_arnHasBeenSet; Aws::String m_name; bool m_nameHasBeenSet; Aws::String m_version; bool m_versionHasBeenSet; Platform m_platform; bool m_platformHasBeenSet; Aws::String m_owner; bool m_ownerHasBeenSet; Aws::String m_dateCreated; bool m_dateCreatedHasBeenSet; }; } // namespace Model } // namespace imagebuilder } // namespace Aws
cedral/aws-sdk-cpp
aws-cpp-sdk-imagebuilder/include/aws/imagebuilder/model/ImageVersion.h
C
apache-2.0
9,773
package com.afollestad.appthemeengine.prefs; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.view.View; import com.afollestad.appthemeengine.ATE; import com.afollestad.appthemeengine.Config; import com.afollestad.appthemeengine.R; import com.afollestad.materialdialogs.prefs.MaterialListPreference; /** * @author Aidan Follestad (afollestad) */ public class ATEMultiSelectPreference extends MaterialListPreference { public ATEMultiSelectPreference(Context context) { super(context); init(context, null); } public ATEMultiSelectPreference(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public ATEMultiSelectPreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } public ATEMultiSelectPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs); } private String mKey; private void init(Context context, AttributeSet attrs) { setLayoutResource(R.layout.ate_preference_custom); if (attrs != null) { TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.ATEMultiSelectPreference, 0, 0); try { mKey = a.getString(R.styleable.ATEMultiSelectPreference_ateKey_pref_multiSelect); } finally { a.recycle(); } } if (!Config.usingMaterialDialogs(context, mKey)) { ATE.config(context, mKey) .usingMaterialDialogs(true) .commit(); } } @Override protected void onBindView(View view) { super.onBindView(view); ATE.apply(view, mKey); } }
guoxiaoxing/material-design-music-player
library/src/main/java/com/afollestad/appthemeengine/prefs/ATEMultiSelectPreference.java
Java
apache-2.0
1,944
// Copyright 2016 InnerFunction Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Created by Julian Goacher on 12/03/2016. // Copyright © 2016 InnerFunction. All rights reserved. // #import <UIKit/UIKit.h> #import "SCViewBehaviour.h" /** * A default do-nothing implementation of the view behaviour protocol. * Provides empty implementations of the required methods. */ @interface SCViewBehaviourObject : NSObject <SCViewBehaviour> @end
innerfunction/SCFFLD-ios
SCFFLD/ioc/ui/SCViewBehaviourObject.h
C
apache-2.0
960
/******************************************************************************* * Copyright (c) 2014 University of Stuttgart. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and the Apache License 2.0 which both accompany this distribution, * and are available at http://www.eclipse.org/legal/epl-v10.html * and http://www.apache.org/licenses/LICENSE-2.0 * * Contributors: * Oliver Kopp - initial API and implementation * Lukas Harzenetter - add id to groups *******************************************************************************/ package org.eclipse.winery.repository.datatypes.select2; import java.util.SortedSet; import java.util.TreeSet; public class Select2OptGroup implements Comparable<Select2OptGroup> { private final String id; private final String text; private final SortedSet<Select2DataItem> children; public Select2OptGroup(String id, String text) { this.text = text; this.id = id; this.children = new TreeSet<>(); } public String getText() { return this.text; } public String getId() { return this.id; } /** * Returns the internal SortedSet for data items. */ public SortedSet<Select2DataItem> getChildren() { return this.children; } public void addItem(Select2DataItem item) { this.children.add(item); } /** * Quick hack to test Select2OptGroups for equality. Only the text is * tested, not the contained children. This might cause issues later, but * currently not. */ @Override public boolean equals(Object o) { if (!(o instanceof Select2OptGroup)) { return false; } return this.text.equals(((Select2OptGroup) o).text); } /** * Quick hack to compare Select2OptGroups. Only the text is compared, not * the contained children. This might cause issues later, but currently not. */ @Override public int compareTo(Select2OptGroup o) { return this.getText().compareTo(o.getText()); } }
YannicSowoidnich/winery
org.eclipse.winery.repository/src/main/java/org/eclipse/winery/repository/datatypes/select2/Select2OptGroup.java
Java
apache-2.0
1,996
WeaponSpeak =========== Sprite Game as 2014 Senior Project for Huntington University, Lead Artist and Designer : Daniel Burnworth, Programmer : Nicholas "Coffeeholic" Barlow, Artist : Jonathan Willard, Artist : Ryan Woods
HuntingtonUniversity/WeaponSpeak
README.md
Markdown
apache-2.0
223
# Chilita microcarpa (Engelm.) Buxb. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Chilita/Chilita microcarpa/README.md
Markdown
apache-2.0
184
# Elaeocarpus orohensis Schltr. & A.C.Sm. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Elaeocarpaceae/Elaeocarpus/Elaeocarpus orohensis/README.md
Markdown
apache-2.0
189
# Opuntia ficus-indica var. amyclaea (Ten.) A.Berger VARIETY #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Opuntia/Opuntia ficus-indica/Opuntia ficus-indica amyclaea/README.md
Markdown
apache-2.0
200
# Aulaya purpurea Benth. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Aulaya/Aulaya purpurea/README.md
Markdown
apache-2.0
172
// https://snazzymaps.com/style/25/blue-water module.exports = [ { featureType: 'administrative', elementType: 'labels.text.fill', stylers: [{ color: '#444444' }], }, { featureType: 'landscape', elementType: 'all', stylers: [{ color: '#f2f2f2' }] }, { featureType: 'poi', elementType: 'all', stylers: [{ visibility: 'off' }] }, { featureType: 'road', elementType: 'all', stylers: [{ saturation: -100 }, { lightness: 45 }] }, { featureType: 'road.highway', elementType: 'all', stylers: [{ visibility: 'simplified' }] }, { featureType: 'road.arterial', elementType: 'labels.icon', stylers: [{ visibility: 'off' }] }, { featureType: 'transit', elementType: 'all', stylers: [{ visibility: 'off' }] }, { featureType: 'water', elementType: 'all', stylers: [{ color: '#46bcec' }, { visibility: 'on' }], }, ];
appbaseio/reactivesearch
packages/maps/src/components/result/addons/styles/BlueWater.js
JavaScript
apache-2.0
824
<?php include 'Manager.php'; class ArticleManager extends Manager { const TABLE_NAME = "articles"; function __construct($sqlMgr) { parent::__construct($sqlMgr, self::TABLE_NAME); } /** 返回当前页面所有数据 */ function pagedata($pageIndex, $maxCount) { $index = $pageIndex * $maxCount; $cols = array("_id", "title", "content", "visited", "praise"); $result = $this->tableQuery->query_colums_limit($cols, $index, $maxCount); $data = array(); while ($row = mysql_fetch_array($result)) { $ele = array(); $ele['_id'] = $row['_id']; $ele['title'] = $row['title']; $ele['content'] = $row['content']; $ele['visited'] = $row['visited']; $ele['praise'] = $row['praise']; $data[] = $ele; } return $data; } /** 返回总页面数 */ function pagecount($maxCount) { $count = $this->tableQuery->record_count(); $pageCount = floor($count / $maxCount); $remain = $count % $maxCount; if($pageCount == 0) $pageCount = 1; else $pageCount = $pageCount + ($remain > 0 ? 1 : 0); return $pageCount; } function add($title, $content) { $createdTime = $this->current_time(); $fp = $this->fingerprint(); return $this->tableQuery->query_add(array("title", "content", "createdTime", "visied", "praise", "fingerprint"), array($title, $content, $createdTime, 0, 0, $fp)); } function delete($articleId) { return $this->tableQuery->query_delete("_id", $articleId); } function modify($articleId, $title, $content) { $modifiedTime = $this->current_time(); $fieldArray = array("title", "content", "modifiedTime"); $valueArray = array($title, $content, $modifiedTime); return $this->tableQuery->query_modify("_id", $articleId, $fieldArray, $valueArray); } /** 递增文章访问人数 */ function inc_visited($articleId) { $reslut = $this->tableQuery->query_colums(array("visited")); $reslut = mysql_fetch_array($reslut); $visited = intval($reslut["visited"]) + 1; return $this->tableQuery->query_modify("_id", $articleId, array("visited"), array($visited)); } /** 递增赞人数 */ function inc_praise($articleId) { $reslut = $this->tableQuery->query_colums(array("praise")); $reslut = mysql_fetch_array($reslut); $praise = intval($reslut["praise"]) + 1; return $this->tableQuery->query_modify("_id", $articleId, array("praise"), array($praise)); } } ?>
soxfmr/blog
controller/ArticleManager.php
PHP
apache-2.0
2,444
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ToyBox.SsmsAddIn.UserInterface.Actions { public interface IActionParameters { } }
marceln/SSMS-ToyBox
ToyBox.AddIn/UserInterface/Actions/IActionParameters.cs
C#
apache-2.0
205
/* * tinyapp.c * * Created on: 7 Dec 2014 * Author: mike */ #include <stdint.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include "common.h" #include "tinyapp.h" #if WITH_TINYMAC_COORDINATOR /* * Conversion tables for mapping TAP profiles and data items * to MQTT/JSON. */ const tinyapp_item_info_t tinyapp_item_info_status[] = { { "battery", tinyappType_Unsigned }, { "runtime", tinyappType_Unsigned }, { "coord_rssi", tinyappType_Signed }, { NULL }, }; const tinyapp_item_info_t tinyapp_item_info_devinfo[] = { { "type", tinyappType_Unsigned }, { "name", tinyappType_String }, { "update_rate", tinyappType_Unsigned }, { NULL }, }; const tinyapp_item_info_t tinyapp_item_info_generic[] = { { "ana0", tinyappType_Signed }, { "ana1", tinyappType_Signed }, { "ana2", tinyappType_Signed }, { "ana3", tinyappType_Signed }, { "ana4", tinyappType_Signed }, { "ana5", tinyappType_Signed }, { "ana6", tinyappType_Signed }, { "ana7", tinyappType_Signed }, { "digin", tinyappType_Unsigned }, { "digout", tinyappType_Unsigned }, { "floattest", tinyappType_SingleFloat }, { "doubletest", tinyappType_DoubleFloat }, { NULL }, }; const tinyapp_item_info_t tinyapp_item_info_env[] = { { "temperature", tinyappType_Signed }, { "rh", tinyappType_Unsigned }, { "visible_lux", tinyappType_Unsigned }, { "uv_lux", tinyappType_Unsigned }, { "ir_lux", tinyappType_Unsigned }, { "ph", tinyappType_Signed }, { "level", tinyappType_Signed }, { "wind_speed_avg", tinyappType_Unsigned }, { "wind_speed_gust", tinyappType_Unsigned }, { "wind_direction", tinyappType_Unsigned }, { "rainfall", tinyappType_Unsigned }, { "pressure", tinyappType_Signed }, { "spl_rms", tinyappType_Signed }, { "spl_peak", tinyappType_Signed }, { NULL }, }; const tinyapp_item_info_t tinyapp_item_info_hvac[] = { { "temperature", tinyappType_Signed }, { "target", tinyappType_Signed }, { "heat_demand", tinyappType_Unsigned }, { "cool_demand", tinyappType_Unsigned }, { "flow_temp", tinyappType_Signed }, { "return_temp", tinyappType_Signed }, { "fan_speed", tinyappType_Unsigned }, { "burner_power", tinyappType_Unsigned }, { NULL }, }; const tinyapp_item_info_t tinyapp_item_info_energy[] = { { NULL }, }; const tinyapp_item_info_t tinyapp_item_info_ha[] = { { NULL }, }; /* Map profiles to MQTT topics. Must be in the same order * as \see tinyapp_profile_t */ const char* tinyapp_profile_tags[] = { "status", "info", "generic", "env", "hvac", "energy", "ha", }; /* Map device types to textual description. Must be in the same order * as \see tinyapp_nodetype_t */ const char* tinyapp_nodetype_str[] = { "Generic", "Generic Sensor", "Generic Actuator", "Environmental Sensor", "Heating Control", "Lighting Control", "Energy Monitoring", "Occupancy Detector", "Switch", }; /* Map profiles to item tables. Must be in the same order * as \see tinyapp_profile_t */ const tinyapp_item_info_t* tinyapp_profile_items[] = { tinyapp_item_info_status, tinyapp_item_info_devinfo, tinyapp_item_info_generic, tinyapp_item_info_env, tinyapp_item_info_hvac, tinyapp_item_info_energy, tinyapp_item_info_ha, }; #endif /*****************/ /* Serialisation */ /*****************/ void tinyapp_init(tinyapp_t *ctx, uint8_t flags, uint8_t *buf, size_t size) { ctx->packet_start = ctx->packet_ptr = buf; ctx->packet_end = &buf[size]; *ctx->packet_ptr++ = flags; } void tinyapp_serialise8(tinyapp_t *ctx, uint8_t type, uint8_t value) { assert(ctx->packet_end >= ctx->packet_ptr + 2); *ctx->packet_ptr++ = TINYAPP_LENGTH_1 | type; *ctx->packet_ptr++ = value; } void tinyapp_serialise16(tinyapp_t *ctx, uint8_t type, uint16_t value) { assert(ctx->packet_end >= ctx->packet_ptr + 3); *ctx->packet_ptr++ = TINYAPP_LENGTH_2 | type; *((uint16_t*)ctx->packet_ptr) = value; ctx->packet_ptr += 2; } void tinyapp_serialise32(tinyapp_t *ctx, uint8_t type, uint32_t value) { assert(ctx->packet_end >= ctx->packet_ptr + 5); *ctx->packet_ptr++ = TINYAPP_LENGTH_4 | type; *((uint32_t*)ctx->packet_ptr) = value; ctx->packet_ptr += 4; } void tinyapp_serialise_string(tinyapp_t *ctx, uint8_t type, const char *str, size_t len) { assert(len < 256); assert(ctx->packet_end >= ctx->packet_ptr + 2 + len); *ctx->packet_ptr++ = TINYAPP_LENGTH_VAR | type; *ctx->packet_ptr++ = (uint8_t)len; memcpy(ctx->packet_ptr, str, len); ctx->packet_ptr += len; } /*******************/ /* Deserialisation */ /*******************/ void tinyapp_deserialise(const uint8_t *buf, size_t size, tinyapp_item_cb_t cb) { const uint8_t *ptr = buf; size_t len = 0; uint8_t profile = 0; /* default profile */ /* Skip flags byte */ ptr++; size--; while ((int)size > 0) { uint8_t id = *ptr & TINYAPP_ITEM_ID_MASK; uint8_t type = *ptr & TINYAPP_LENGTH_MASK; ptr++; size--; switch (type) { case TINYAPP_LENGTH_1: len = 1; break; case TINYAPP_LENGTH_2: len = 2; break; case TINYAPP_LENGTH_4: len = 4; break; case TINYAPP_LENGTH_VAR: /* Variable length - consume another byte */ len = (size_t)*ptr; ptr++; size--; break; } if (id == TINYAPP_ITEM_ID_PROFILE) { /* Decode profile selection */ /* TODO: Could handle profile numbers > 8 bits */ TRACE("New profile %u\n", (unsigned int)*ptr); profile = *ptr; } else { /* Everything else gets routed to callback */ cb(profile, id, (void*)ptr, len); } /* Consume data */ ptr += len; size -= len; } } #if WITH_TINYMAC_COORDINATOR /*******************/ /* Table Utilities */ /*******************/ int tinyapp_get_profile_id(const char *tag) { int n; for (n = 0; n < ARRAY_SIZE(tinyapp_profile_tags); n++) { if (strcasecmp(tag, tinyapp_profile_tags[n]) == 0) { return n; } } return -1; /* not found */ } const char* tinyapp_get_profile_tag(uint8_t profile) { /* Return pointer to profile tag name or NULL if profile ID out of range */ return (profile < ARRAY_SIZE(tinyapp_profile_tags)) ? tinyapp_profile_tags[profile] : NULL; } int tinyapp_get_item_id(uint8_t profile, const char *tag) { const tinyapp_item_info_t *item_info; int n; if (profile < ARRAY_SIZE(tinyapp_profile_tags)) { item_info = tinyapp_profile_items[profile]; for (n = 0; item_info->tag; item_info++, n++) { if (strcasecmp(tag, item_info->tag) == 0) { return n; } } } return -1; /* not found */ } const tinyapp_item_info_t* tinyapp_get_item_info(uint8_t profile, uint8_t item) { /* FIXME: Validate item index, currently requires walking the table */ return (profile < ARRAY_SIZE(tinyapp_profile_items)) ? &tinyapp_profile_items[profile][item] : NULL; } #endif
mikestir/tinyhan
lib/tinyapp.c
C
apache-2.0
6,702
package com.twitter.scalding.jdbc import org.scalatest.WordSpec class ExampleMysqlJdbcSource() extends JDBCSource with MysqlDriver { override val tableName = TableName("test") override val columns: Iterable[ColumnDefinition] = Iterable( int("hey"), bigint("you"), varchar("get"), datetime("off"), text("of"), double("my"), smallint("cloud") ) override def currentConfig = ConnectionSpec(ConnectUrl("how"), UserName("are"), Password("you")) } class ExampleVerticaJdbcSource() extends JDBCSource with VerticaJdbcDriver { override val tableName = TableName("test") override val columns: Iterable[ColumnDefinition] = Iterable( int("hey"), bigint("you"), varchar("get"), datetime("off"), text("of"), double("my"), smallint("cloud") ) override def currentConfig = ConnectionSpec(ConnectUrl("how"), UserName("are"), Password("you")) } class JDBCSourceCompileTest extends WordSpec { "JDBCSource" should { "Pick up correct column definitions for MySQL Driver" in { new ExampleMysqlJdbcSource().toSqlCreateString } } }
twitter/scalding
scalding-jdbc/src/test/scala/com/twitter/scalding/jdbc/JDBCSourceCompileTest.scala
Scala
apache-2.0
1,103
import logging from sys import exc_info from socket import socket, AF_INET, SOCK_STREAM, SOCK_DGRAM, SHUT_RD, SOL_SOCKET, SO_REUSEADDR, error as socketError from traceback import format_exception from struct import Struct from .common import * from .models import * from .exceptions import * class ClientHost(): def __init__(self, host): self.host = host self.active = 0 self.udpsocks = set() class ZeallectProxy(ZeallectSocketEntity): def __init__(self, c): self.config = c self.remotedets = (c.host, int(c.port)) def run(self): binding = (self.config.bindhost, int(self.config.bindport)) # create tcp socket/server tcpsock = socket(AF_INET, SOCK_STREAM) tcpsock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) tcpsock.bind(binding) tcpsock.listen(5) # create udp socket/server udpsock = socket(AF_INET, SOCK_DGRAM) udpsock.bind(binding) # maps client UDP bindings to socket objects # destined for the server self.udpmap = {} self.sockets = { tcpsock: None, udpsock: None, } # maps tcp sockets and addresses to ClientHost objects self.hostmap = {} # shortcuts remotedets = self.remotedets socketdict = self.sockets nextsocket = self.selectReadable() ignore_exc = (None, socketError, EndOfStreamException) self.alive = True for sock in nextsocket: # client -> us if sock is udpsock: data, details = sock.recvfrom(Z_SOCKET_RECV_SIZE) host = details[0] if host in self.hostmap: if details not in self.udpmap: newsock = socket(AF_INET, SOCK_DGRAM) self.udpmap[details] = newsock socketdict[newsock] = details self.hostmap[host].udpsocks.add(newsock) self.udpmap[details].sendto(data, remotedets) # server -> us elif SOCK_DGRAM == sock.type: data, details = sock.recvfrom(Z_SOCKET_RECV_SIZE) if details == remotedets: udpsock.sendto(data, socketdict[sock]) # client -> us (connect()) elif sock is tcpsock: newsock, details = sock.accept() # create connection to server newservsock = socket(AF_INET, SOCK_STREAM) newservsock.settimeout(Z_SOCKET_SERVER_TIMEOUT) try: newservsock.connect(remotedets) socketdict[newsock] = newservsock socketdict[newservsock] = newsock host = details[0] if host not in self.hostmap: clienthost = ClientHost(host) else: clienthost = self.hostmap[host] clienthost.active += 1 self.hostmap[newsock] = clienthost self.hostmap[newservsock] = clienthost self.hostmap[details[0]] = clienthost logging.info('Client connected from [/%s:%d]', *details) except: logging.warning('Failed to create tcp relay for [/%s:%d]', *details) exception = exc_info() logging.warning(''.join(format_exception(*exception))) # tcp relay else: try: data = sock.recv(Z_SOCKET_RECV_SIZE) if data: socketdict[sock].send(data) else: self.removeRelay(sock) except: exception = exc_info() if exception[0] not in ignore_exc: logging.warning('An exception occurred while processing a socket!') logging.warning(''.join(format_exception(*exception))) self.removeRelay(sock) def removeRelay(self, sock): sockpair = self.sockets[sock] for _sock in (sockpair, sock): try: _sock.shutdown(SHUT_RD) _sock.close() except socketError: pass self.sockets.pop(_sock) clienthost = self.hostmap[sock] if clienthost.active == 1: logging.debug('Freeing up all UDP sockets to %s', clienthost.host) # pop all udp socks that the host has connected dets = map(self.sockets.pop, clienthost.udpsocks) # pop all udp socks from the udpmap map(self.udpmap.pop, dets) # remove all referernces to the clienthost self.hostmap.pop(sockpair) self.hostmap.pop(sock) self.hostmap.pop(clienthost.host) else: clienthost.active -= 1 logging.info('Client from %s disconnected', clienthost.host) def disconnect(self): socks = [s for s in self.sockets.keys() if SOCK_STREAM == s.type] for sock in socks: try: sock.shutdown(SHUT_RD) sock.close() except socketError: pass
jm-/zeallect
zeallect/proxy.py
Python
apache-2.0
5,351
# Smart App Rate Smart app rate dialog for Android which takes user rating into consideration. If the user rates the app below the defined threshold rating, the dialog will change into a feedback form. Otherwise, It will take the user to the Google PlayStore. ![](preview/preview.png) ## Features - Auto fetches the app icon to appear on top of the dialog - Make the dialog appear on a defined app session - Opens Feedback form if the user rates below the minimum threshold - Extracts the accent color from your app's theme - Customizable title, positive button and negative button texts - Customizable button colors and backgrounds - Override dialog redirection to Google Play or Feedback form according to your needs If you want the dialog to appear on the Nth session of the app, just add the `session(N)` to the dialog builder method and move the code to the `onCreate()` method of your Activity class. The dialog will appear when the app is opened for the Nth time. ## How to use Use the dialog as it is ```java final RatingDialog ratingDialog = new RatingDialog.Builder(this) .threshold(3) .session(7) .onRatingBarFormSumbit(new RatingDialog.Builder.RatingDialogFormListener() { @Override public void onFormSubmitted(String feedback) { } }).build(); ratingDialog.show(); ``` or use the dialog builder class to customize the rating dialog to match your app's UI. ```java final RatingDialog ratingDialog = new RatingDialog.Builder(this) .icon(drawable) .session(7) .threshold(3) .title("How was your experience with us?") .titleTextColor(R.color.black) .positiveButtonText("Not Now") .negativeButtonText("Never") .positiveButtonTextColor(R.color.white) .negativeButtonTextColor(R.color.grey_500) .formTitle("Submit Feedback") .formHint("Tell us where we can improve") .formSubmitText("Submit") .formCancelText("Cancel") .ratingBarColor(R.color.yellow) .playstoreUrl("YOUR_URL") .onThresholdCleared(new RatingDialog.Builder.RatingThresholdClearedListener() { @Override public void onThresholdCleared(RatingDialog ratingDialog, float rating, boolean thresholdCleared) { //do something ratingDialog.dismiss(); } }) .onThresholdFailed(new RatingDialog.Builder.RatingThresholdFailedListener() { @Override public void onThresholdFailed(RatingDialog ratingDialog, float rating, boolean thresholdCleared) { //do something ratingDialog.dismiss(); } }) .onRatingChanged(new RatingDialog.Builder.RatingDialogListener() { @Override public void onRatingSelected(float rating, boolean thresholdCleared) { } }) .onRatingBarFormSumbit(new RatingDialog.Builder.RatingDialogFormListener() { @Override public void onFormSubmitted(String feedback) { } }).build(); ratingDialog.show(); ``` ### Note * Don't use `session()` if you want to show the dialog on a click event. * Remove the `threshold()` from the builder if you don't want to show the feedback form to the user. * Use `onThresholdCleared()` to override the default redirection to Google Play. * Use `onThresholdFailed()` to show your custom feedback form. ## Installation ### Gradle Add it as a dependency in your app's build.gradle file ```groovy dependencies { compile 'com.codemybrainsout.rating:ratingdialog:1.0.8' } ``` ## Credits This project was initiated by **Code My Brains Out**. You can contribute to this project by submitting issues or/and by forking this repo and sending a pull request. ![](http://codemybrainsout.com/files/img/logo-small.png) Follow us on: [![Facebook](http://codemybrainsout.com/files/img/fb.png)](https://www.facebook.com/codemybrainsout)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[![Twitter](http://codemybrainsout.com/files/img/tw.png)](https://twitter.com/codemybrainsout) Author: [Rahul Juneja](https://github.com/ahulr) # License ``` Copyright (C) 2016 Code My Brains Out Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ```
codemybrainsout/smart-app-rate
README.md
Markdown
apache-2.0
5,707
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.tonyu.js; import java.util.List; import java.util.Map; import jp.tonyu.debug.Log; import jp.tonyu.js.Wrappable; import org.mozilla.javascript.Context; import org.mozilla.javascript.NativeArray; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.mozilla.javascript.WrapFactory; public class SafeWrapFactory extends WrapFactory { public SafeWrapFactory() { setJavaPrimitiveWrap(false); } @Override public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class<?> staticType) { /*if (javaObject instanceof String || javaObject instanceof Number || javaObject instanceof Boolean || javaObject instanceof org.mozilla.javascript.EvaluatorException || javaObject instanceof org.mozilla.javascript.EcmaError || javaObject instanceof org.mozilla.javascript.JavaScriptException || //javaObject instanceof org.mozilla.javascript.JavaException || javaObject instanceof Wrappable ) { return super.wrapAsJavaObject(cx, scope, javaObject, staticType); }*/ //System.out.println("Wrap "+javaObject+"("+javaObject.getClass()+") in scope "+scope); if (javaObject instanceof Map) { return new MapScriptable((Map)javaObject); } /*if (javaObject instanceof List) { List ls = (List) javaObject; NativeArray na = new NativeArray(ls.toArray()); System.out.println("shift="+ScriptableObject.getProperty(na, "shift")); return na; } if (javaObject instanceof Object[]) { Object[] ar = (Object[]) javaObject; return new NativeArray(ar); }*/ return super.wrapAsJavaObject(cx, scope, javaObject, staticType); //Log.die(javaObject.getClass()+": Only Wrappable can be wrapped."); //return null; } }
hoge1e3/tonyuedit
src/jp/tonyu/js/SafeWrapFactory.java
Java
apache-2.0
2,624
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs.server.federation.router; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.hadoop.fs.permission.FsAction; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.server.federation.store.records.MountTable; import org.apache.hadoop.hdfs.server.namenode.FSPermissionChecker; import org.apache.hadoop.hdfs.server.namenode.NameNode; import org.apache.hadoop.security.AccessControlException; import org.apache.hadoop.security.UserGroupInformation; /** * Class that helps in checking permissions in Router-based federation. */ public class RouterPermissionChecker extends FSPermissionChecker { static final Logger LOG = LoggerFactory.getLogger(RouterPermissionChecker.class); /** Mount table default permission. */ public static final short MOUNT_TABLE_PERMISSION_DEFAULT = 00755; /** Name of the super user. */ private final String superUser; /** Name of the super group. */ private final String superGroup; public RouterPermissionChecker(String user, String group, UserGroupInformation callerUgi) { super(user, group, callerUgi, null); this.superUser = user; this.superGroup = group; } public RouterPermissionChecker(String user, String group) throws IOException { super(user, group, UserGroupInformation.getCurrentUser(), null); this.superUser = user; this.superGroup = group; } /** * Whether a mount table entry can be accessed by the current context. * * @param mountTable * MountTable being accessed * @param access * type of action being performed on the mount table entry * @throws AccessControlException * if mount table cannot be accessed */ public void checkPermission(MountTable mountTable, FsAction access) throws AccessControlException { if (isSuperUser()) { return; } FsPermission mode = mountTable.getMode(); if (getUser().equals(mountTable.getOwnerName()) && mode.getUserAction().implies(access)) { return; } if (isMemberOfGroup(mountTable.getGroupName()) && mode.getGroupAction().implies(access)) { return; } if (!getUser().equals(mountTable.getOwnerName()) && !isMemberOfGroup(mountTable.getGroupName()) && mode.getOtherAction().implies(access)) { return; } throw new AccessControlException( "Permission denied while accessing mount table " + mountTable.getSourcePath() + ": user " + getUser() + " does not have " + access.toString() + " permissions."); } /** * Check the superuser privileges of the current RPC caller. This method is * based on Datanode#checkSuperuserPrivilege(). * @throws AccessControlException If the user is not authorized. */ @Override public void checkSuperuserPrivilege() throws AccessControlException { // Try to get the ugi in the RPC call. UserGroupInformation ugi = null; try { ugi = NameNode.getRemoteUser(); } catch (IOException e) { // Ignore as we catch it afterwards } if (ugi == null) { LOG.error("Cannot get the remote user name"); throw new AccessControlException("Cannot get the remote user name"); } // Is this by the Router user itself? if (ugi.getShortUserName().equals(superUser)) { return; } // Is the user a member of the super group? List<String> groups = Arrays.asList(ugi.getGroupNames()); if (groups.contains(superGroup)) { return; } // Not a superuser throw new AccessControlException( ugi.getUserName() + " is not a super user"); } }
plusplusjiajia/hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/RouterPermissionChecker.java
Java
apache-2.0
4,583
import logging from event_consumer.conf import settings from event_consumer.errors import PermanentFailure from event_consumer.handlers import message_handler _logger = logging.getLogger(__name__) class IntegrationTestHandlers(object): """ Basic message handlers that log or raise known exceptions to allow interactive testing of the RabbitMQ config. """ @staticmethod def py_integration_ok(body): """ Should always succeed, never retry, never archive. """ msg = 'py_integration_ok, {}'.format(body) _logger.info(msg) @staticmethod def py_integration_raise(body): """ Should retry until there are no attempts left, then archive. """ msg = 'py_integration_raise, {}'.format(body) _logger.info(msg) raise Exception(msg) @staticmethod def py_integration_raise_permanent(body): """ Should cause the message to be archived on first go. """ msg = 'py_integration_raise_permanent, {}'.format(body) _logger.info(msg) raise PermanentFailure(msg) if settings.TEST_ENABLED: # Add tasks for interactive testing (call decorators directly) message_handler('py.integration.ok')( IntegrationTestHandlers.py_integration_ok) message_handler('py.integration.raise')( IntegrationTestHandlers.py_integration_raise) message_handler('py.integration.raise.permanent')( IntegrationTestHandlers.py_integration_raise_permanent)
depop/celery-message-consumer
event_consumer/test_utils/handlers.py
Python
apache-2.0
1,527
#include <bits/stdc++.h> #define for0(i, n) for(i = 0; i < n; i++) #define for1(i, n) for(i = 1; i <= n; i++) #define fora(i, a, n) for(i = a; i < n; i++) #define dprc(x) printf("| %c\n", x) #define dprd(x) printf("| %d\n", x) #define dprd2(x,y) printf("| %d %d\n", x, y) #define prd(x) printf("%d\n", x) #define prd2(x,y) printf("%d %d\n", x, y) #define scd(x) scanf("%d", &x) #define scd2(x, y) scanf("%d%d", &x, &y) #define NL() printf("\n") #define PB push_back #define MP make_pair #define MT(x, y, z) MP(MP(x, y), z) #define MTi(x, y, z) MP(x, MP(y, z)) #define MAX(x, y) ((x>y)?x:y) #define X first #define Y second using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; typedef pair<int, pair<int, int> > iii; typedef long long ll; typedef unsigned long long ull; const int MAX = 200100; int n, a, b, i, j, A[MAX], M, B[MAX]; map<int, int> v, m, k; map<int, int>::iterator it; set<int> u; int I; void solve(int p){ it = m.find(p); if(it != m.end()){ solve(it->second); } if(u.find(p) == u.end()){ //cerr << "."<< p << " "; B[I++] = p; u.insert(p); } } void solve2(int p){ it = v.find(p); if(u.find(p) == u.end()){ B[I++] = p; u.insert(p); } if(it != v.end()){ solve2(it->second); } } int main() { memset(A, 0, sizeof A); memset(B, 0, sizeof B); I = 0; cin >> n; for0(i, n){ cin >> a >> b; v.insert(MP(a, b)); m.insert(MP(b, a)); } i = 0; a = 1; while(a < n) { it = v.find(i); if(it == v.end()) break; if(a > 1){ A[a-2] = i; } A[a] = it->second; v.erase(it); m.erase(m.find(it->second)); i = it->second; a+=2; } if(n%2 == 0){ i = 0; a = n-2; while(a >= 0) { it = m.find(i); if(it == m.end()) break; if(a > 1){ A[a-2] = i; } A[a] = it->second; i = it->second; a-=2; } } else { m.erase(0); M = m.begin()->first; //cerr << M << endl; //for(it = m.begin(); it != m.end(); it++)cout << it->first << ", " << it->second << endl; solve(M); solve2(M); //for0(i, n){cout << B[i] << " ";} i = 0; j = 0; while(i < n){ A[i] = B[j++]; i+=2; } } for0(i, n){ cout << A[i] << " "; } NL(); }
MartinAparicioPons/Competitive-Programming
Codeforces/Queue.cpp
C++
apache-2.0
2,133
package Entities; /** * * @author Moamenovic */ public class Flower { private int ID; private String country; private String name; private ImageEntity image; public ImageEntity getImage() { return image; } public void setImage(ImageEntity image) { this.image = image; } public int getID() { return ID; } public void setID(int ID) { this.ID = ID; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Flower{" + "ID=" + ID + ", country=" + country + ", name=" + name + '}'; } }
AllaaAmer/jspFlowers
FlowersCart1/src/java/Entities/Flower.java
Java
apache-2.0
922
package storage // Driver is the interface for a storage engine. type Driver interface { Open(uri string) (err error) Close() (err error) Get(key string) (value string, err error) Set(key, value string) (err error) Delete(key string) (err error) }
tenchoufansubs/go-lolicon
storage/driver.go
GO
apache-2.0
255
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ /** * Created by dongwang47 on 2016/8/11. */ package com.creditease.dbus.tools; import com.alibaba.otter.canal.client.CanalConnector; import com.alibaba.otter.canal.client.CanalConnectors; import com.alibaba.otter.canal.protocol.CanalEntry.*; import com.alibaba.otter.canal.protocol.Message; import java.net.InetSocketAddress; import java.util.List; public class SimpleCanalClientExample { // 输入参数: dbus-n1 11111 testdb public static void main(String args[]) { //args = new String[]{"vdbus-4", "10000", "mysql_db2"}; args = new String[]{"vdbus-4", "10000", "mysql_db2"}; if (args.length != 3) { System.out.println("args: dbus-n1 11111 testdb"); return; } String ip = args[0]; int port = Integer.parseInt(args[1]); String dbname = args[2]; // 创建链接 CanalConnector connector = null; int batchSize = 1000; int emptyCount = 0; try { connector = CanalConnectors.newSingleConnector(new InetSocketAddress(ip, port), dbname, "", ""); //connector = CanalConnectors.newClusterConnector("vdbus-7:2181/DBus/Canal/mysql_db1", dbname, "", ""); connector.connect(); connector.subscribe(""); connector.rollback(); int totalEmtryCount = 120; while (emptyCount < totalEmtryCount) { Message message = connector.getWithoutAck(batchSize); // 获取指定数量的数据 long batchId = message.getId(); int size = message.getEntries().size(); if (batchId == -1 || size == 0) { emptyCount++; System.out.print("."); try { Thread.sleep(1000); } catch (InterruptedException e) { } } else { emptyCount = 0; // System.out.printf("message[batchId=%s,size=%s] \n", batchId, size); System.out.println(""); printEntry(message.getEntries(), batchId); } connector.ack(batchId); // 提交确认 // connector.rollback(batchId); // 处理失败, 回滚数据 } System.out.println("empty too many times, exit"); } finally { if (connector != null) { connector.disconnect(); } } } private static void printEntry(List<Entry> entries, long batchId) { // CanalPacket.Messages.Builder builder = CanalPacket.Messages.newBuilder(); // builder.setBatchId(batchId); for (Entry entry : entries) { //System.out.printf("entrytype: %s, entry size: %d\n", entry.getEntryType().toString(), entry.getSerializedSize()); // builder.addMessages(entry.toByteString()); if (entry.getEntryType() == EntryType.TRANSACTIONBEGIN || entry.getEntryType() == EntryType.TRANSACTIONEND) { continue; } String namespace = entry.getHeader().getSchemaName() + "." + entry.getHeader().getTableName(); System.out.println(namespace + ": header.eventType:" + entry.getHeader().getEventType()); System.out.println(namespace + ": header.getEventLength:" + entry.getHeader().getEventLength()); System.out.println(namespace + ": header.getServerId:" + entry.getHeader().getServerId()); System.out.println(namespace + ": header.getVersion:" + entry.getHeader().getVersion()); System.out.println(namespace + ": header.getPropsCount:" + entry.getHeader().getPropsCount()); if (entry.getHeader().getPropsCount() > 0) { System.out.println(namespace + ": header.getHeader().getProps(0).getKey():" + entry.getHeader().getProps(0).getKey()); System.out.println(namespace + ": header.getHeader().getProps(0).getValue():" + entry.getHeader().getProps(0).getValue()); } RowChange rowChage = null; try { rowChage = RowChange.parseFrom(entry.getStoreValue()); } catch (Exception e) { throw new RuntimeException("ERROR ## parser of eromanga-event has an error , data:" + entry.toString(), e); } EventType eventType = rowChage.getEventType(); System.out.println(String.format(namespace + ": ================> binlog[%s:%s] , name[%s,%s] , eventType : %s, header.eventType: %s", entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(), entry.getHeader().getSchemaName(), entry.getHeader().getTableName(), eventType, entry.getHeader().getEventType())); System.out.println(namespace + ": sql:" + rowChage.getSql()); for (RowData rowData : rowChage.getRowDatasList()) { if (eventType == EventType.DELETE) { printColumn(namespace, rowData.getBeforeColumnsList()); } else if (eventType == EventType.INSERT) { printColumn(namespace, rowData.getAfterColumnsList()); } else if (eventType == EventType.UPDATE) { System.out.println(namespace + ": -------> before"); printColumn(namespace, rowData.getBeforeColumnsList()); System.out.println(namespace + ": -------> after"); printColumn(namespace, rowData.getAfterColumnsList()); } else { ; } } } // CanalPacket.Messages msgsOld = builder.build(); // byte[] byteArray = msgsOld.toByteArray(); // // try { // CanalPacket.Messages msgs = CanalPacket.Messages.parseFrom(byteArray); // List<ByteString> list = msgs.getMessagesList(); // for (ByteString str : list) { // Entry ent = CanalEntry.Entry.parseFrom(str); // System.out.println(ent.getSerializedSize()); // } // }catch (InvalidProtocolBufferException ex) { // System.out.printf(ex.getMessage()); // } // byte[] byteArray = output.toByteArray(); // System.out.printf("byteArray : %d\n", byteArray.length); // // InputStream input = new ByteArrayInputStream(byteArray); // Entry entry = null; // // List<Entry> list = new ArrayList<>(); // try { // // 反序列化 // while (input.available() != 0) { // entry = CanalEntry.Entry.parseFrom(input); // list.add(entry); // System.out.printf("skip : %d\n", entry.getSerializedSize()); // //input.skip(entry.getSerializedSize()); // } // }catch (IOException ex) { // System.out.printf(ex.getMessage()); // return; // } } private static void printColumn(String namespace, List<Column> columns) { for (Column column : columns) { System.out.println(namespace + ": " + column.getName() + " : " + column.getValue() + " update=" + column.getUpdated() + ", sqltype=" + column.getMysqlType() + ", isnull=" + column.getIsNull()); } } }
BriData/DBus
dbus-tools/src/main/java/com/creditease/dbus/tools/SimpleCanalClientExample.java
Java
apache-2.0
8,034
# Folio Publishing Platform # This is Folio, an open-source content management platform: - Its core is built on well established free and open-source frameworks - Runs on any server with [Java] 11 or later installed - Can be plugged into any standard Java application server such as [Tomcat] - Can use its own internal database or most common datastore platforms The goal of WurstWorks Folio is provide a flexible, extensible, and performant publishing platform that is also open, comprehensible, and lends itself well to importing content from, exporting content to, and exchanging content with other Folio installations, as well as with other publishing installations on other platforms such as [Drupal], [WordPress], and more. > Stand by for news... ### Version 0.1 ### Tech WurstWorks Folio uses a number of open source projects to work properly: * [Spring Boot] is the primary framework for the back-end service components ### Installation TBD. ### Reporting Issues R ### Development Want to contribute? Great! I don't really have anything to do yet though. The source code is available from the [Folio GitHub repository]. ### TO-DOs - Everything License ---- [Simplified 2-Clause BSD] **Free Software, Hell Yeah!** [Java]:https://java.oracle.com [Tomcat]:https://tomcat.apache.org [Drupal]:https://www.drupal.org/ [WordPress]:https://wordpress.org [Folio GitHub repository]:https://github.com/WurstWorks/Folio [Simplified 2-Clause BSD]:https://opensource.org/licenses/Apache-2.0
WurstWorks/Folio
README.md
Markdown
apache-2.0
1,517
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class PreviewControl Inherits System.Windows.Forms.UserControl 'UserControl overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.webPreview = New System.Windows.Forms.WebBrowser Me.Bar1 = New DevComponents.DotNetBar.Bar Me.ckbShowAssignedVariables = New DevComponents.DotNetBar.CheckBoxItem Me.ckbShowVariableName = New DevComponents.DotNetBar.CheckBoxItem Me.ckbShowValues = New DevComponents.DotNetBar.CheckBoxItem Me.ckbShowConditions = New DevComponents.DotNetBar.CheckBoxItem Me.ckbMetaData = New DevComponents.DotNetBar.CheckBoxItem Me.ckbRoute = New DevComponents.DotNetBar.CheckBoxItem Me.ckbPageBreak = New DevComponents.DotNetBar.CheckBoxItem Me.ckbHiddenLV = New DevComponents.DotNetBar.CheckBoxItem CType(Me.Bar1, System.ComponentModel.ISupportInitialize).BeginInit() Me.SuspendLayout() ' 'webPreview ' Me.webPreview.Dock = System.Windows.Forms.DockStyle.Fill Me.webPreview.Location = New System.Drawing.Point(0, 42) Me.webPreview.MinimumSize = New System.Drawing.Size(20, 20) Me.webPreview.Name = "webPreview" Me.webPreview.Size = New System.Drawing.Size(588, 409) Me.webPreview.TabIndex = 0 ' 'Bar1 ' Me.Bar1.AntiAlias = True Me.Bar1.DisplayMoreItemsOnMenu = True Me.Bar1.Dock = System.Windows.Forms.DockStyle.Top Me.Bar1.EqualButtonSize = True Me.Bar1.Items.AddRange(New DevComponents.DotNetBar.BaseItem() {Me.ckbShowAssignedVariables, Me.ckbShowVariableName, Me.ckbShowValues, Me.ckbShowConditions, Me.ckbMetaData, Me.ckbRoute, Me.ckbPageBreak, Me.ckbHiddenLV}) Me.Bar1.Location = New System.Drawing.Point(0, 0) Me.Bar1.Name = "Bar1" Me.Bar1.Size = New System.Drawing.Size(588, 42) Me.Bar1.Stretch = True Me.Bar1.TabIndex = 2 Me.Bar1.TabStop = False Me.Bar1.Text = "Bar1" Me.Bar1.ThemeAware = True Me.Bar1.WrapItemsDock = True ' 'ckbShowAssignedVariables ' Me.ckbShowAssignedVariables.Name = "ckbShowAssignedVariables" Me.ckbShowAssignedVariables.Text = "Assigned Variables" Me.ckbShowAssignedVariables.ThemeAware = True ' 'ckbShowVariableName ' Me.ckbShowVariableName.Name = "ckbShowVariableName" Me.ckbShowVariableName.Text = "Variable Names" Me.ckbShowVariableName.ThemeAware = True ' 'ckbShowValues ' Me.ckbShowValues.Name = "ckbShowValues" Me.ckbShowValues.Text = "Values of Legal Values " Me.ckbShowValues.ThemeAware = True ' 'ckbShowConditions ' Me.ckbShowConditions.Name = "ckbShowConditions" Me.ckbShowConditions.Text = "Conditions" Me.ckbShowConditions.ThemeAware = True ' 'ckbMetaData ' Me.ckbMetaData.Name = "ckbMetaData" Me.ckbMetaData.Text = "Metadata" Me.ckbMetaData.ThemeAware = True ' 'ckbRoute ' Me.ckbRoute.Name = "ckbRoute" Me.ckbRoute.Text = "Route" Me.ckbRoute.ThemeAware = True ' 'ckbPageBreak ' Me.ckbPageBreak.Name = "ckbPageBreak" Me.ckbPageBreak.Text = "Page Breaks" Me.ckbPageBreak.ThemeAware = True ' 'ckbHiddenLV ' Me.ckbHiddenLV.Name = "ckbHiddenLV" Me.ckbHiddenLV.Text = "Hidden Legal Values" Me.ckbHiddenLV.ThemeAware = True ' 'PreviewControl ' Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!) Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.Controls.Add(Me.webPreview) Me.Controls.Add(Me.Bar1) Me.Name = "PreviewControl" Me.Size = New System.Drawing.Size(588, 451) CType(Me.Bar1, System.ComponentModel.ISupportInitialize).EndInit() Me.ResumeLayout(False) End Sub Friend WithEvents webPreview As System.Windows.Forms.WebBrowser Friend WithEvents Bar1 As DevComponents.DotNetBar.Bar Friend WithEvents ckbShowAssignedVariables As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbShowVariableName As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbShowValues As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbShowConditions As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbMetaData As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbRoute As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbPageBreak As DevComponents.DotNetBar.CheckBoxItem Friend WithEvents ckbHiddenLV As DevComponents.DotNetBar.CheckBoxItem End Class
QMDevTeam/QMDesigner
UI/UserControls/PreviewControl.Designer.vb
Visual Basic
apache-2.0
5,562
package com.ugurcan.spring.training; public class HappyFortuneService implements FortuneService { @Override public String getFortune() { return "This is from HappyFortuneService class"; } @Override public void testFortune() { System.out.println("Test for the Happy Fortune Class"); } }
ugurcancetin/Spring-Training
02-Hello-Spring-DI/src/com/ugurcan/spring/training/HappyFortuneService.java
Java
apache-2.0
303
<?php class MainPageCest { public function _before(AcceptanceTester $I) { } public function _after(AcceptanceTester $I) { } // tests public function testThatUserSeeNewsList(AcceptanceTester $I) { $I->wantTo('see news list'); $I->amOnPage('index.html#/dashboard/home'); $I->wait(1); $I->see('Latest news'); } public function testThatUserSeeOneNews(AcceptanceTester $I) { $I->wantTo('see one news page'); $I->amOnPage('index.html#/dashboard/home'); $I->wait(1); $I->see('Read more', 'a'); $I->click('//*[@id="page-wrapper"]/div/div/div/div[1]/div/div[2]/div[1]/div/div[2]/div[2]/p[2]/a'); $I->wait(1); $I->seeElement('.news-div'); } public function testThatUserSeeSchedule(AcceptanceTester $I) { $I->wantTo('see schedule'); $I->amOnPage('index.html#/dashboard/home'); $I->wait(1); $I->seeElement('div.tabs-schedule'); } public function testScheduleTabToggle(AcceptanceTester $I) { $I->wantTo('toggle schedule tabs'); $I->amOnPage('index.html#/dashboard/home'); $I->wait(1); $I->seeElement('a[data-target="#month"]'); $I->click('a[data-target="#month"]'); $I->wait(1); $I->dontSeeElement('div[id="day"]'); } }
polinart/bachelor
acceptance-tests/tests/acceptance/MainPageCest.php
PHP
apache-2.0
1,355
# Sphaeria mesaedema Berk. & M.A. Curtis SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Sphaeria mesaedema Berk. & M.A. Curtis ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Xylariales/Xylariaceae/Sphaeria/Sphaeria mesaedema/README.md
Markdown
apache-2.0
205
# Edit this file to CATALINA_BASE/bin/setenv.sh to set custom options # Tomcat accepts two parameters JAVA_OPTS and CATALINA_OPTS # JAVA_OPTS are used during START/STOP/RUN # CATALINA_OPTS are used during START/RUN # JVM memory settings - general GENERAL_JVM_OPTS="-server -Xmx8192m -Xss192k -Djava.awt.headless=true" # JVM Sun specific settings # For a complete list http://blogs.sun.com/watt/resource/jvm-options-list.html SUN_JVM_OPTS="-XX:MaxPermSize=256m \ -XX:MaxGCPauseMillis=500 \ -XX:-UseGCLogFileRotation \ -Xloggc:$CATALINA_HOME/logs/gc.log \ -XX:+PrintHeapAtGC \ -XX:+PrintGCDetails \ -XX:+PrintGCTimeStamps \ -XX:NumberOfGCLogFiles=10 \ -XX:GCLogFileSize=20M \ -XX:-HeapDumpOnOutOfMemoryError" # Set any custom application options here APPLICATION_OPTS="-Dlogback.configurationFile=$CATALINA_BASE/conf/logback.xml \ -Dsolr.solr.home=$CATALINA_BASE/solr-home/ \ -Dsolr.data.dir=$CATALINA_BASE/hmp-home/solr/data \ -Dhmp.home=$CATALINA_BASE/hmp-home" JVM_OPTS="$GENERAL_JVM_OPTS $SUN_JVM_OPTS" CATALINA_OPTS="$JVM_OPTS $APPLICATION_OPTS"
KRMAssociatesInc/eHMP
ehmp/product/production/hmp-main/src/main/assembly/tomcat/setenv.sh
Shell
apache-2.0
1,189
# Bertia submoriformis (Plowr.) Sacc. SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Sphaeria submoriformis Plowr. ### Remarks null
mdoering/backbone
life/Fungi/Ascomycota/Sordariomycetes/Coronophorales/Bertiaceae/Bertia/Bertia submoriformis/README.md
Markdown
apache-2.0
193
<!DOCTYPE html> <html lang="en"> <link rel="shortcut icon" href="img/favicon.png"> <head> <meta charset="utf-8"> <meta http-equiv="X-Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'"> <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="The MAASU Spring Conference will be from April 7-8, 2017 at the University of Michigan in Ann Arbor."> <meta name="author" content="Kelvin Tam"> <title>MAASU 2017 | University of Michigan</title> <!-- Bootstrap Core CSS --> <link href="css/bootstrap.css" rel="stylesheet"> <!-- Custom CSS --> <link href="mobile/css/mobile.css" rel="stylesheet"> <!-- Custom Fonts --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css"> <link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Raleway:400,600' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Lato:400,300,300italic,400italic,700,700italic,900' rel='stylesheet' type='text/css'> <link href='css/toastr.min.css' rel='stylesheet' type='text/css'> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top"> <!--=== PAGE PRELOADER ===--> <div id="page-loader"><span class="page-loader-gif"></span></div> <!-- Navigation --> <nav class="navbar navbar-custom navbar-fixed-top top-nav-collapse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse"> <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="#page-top"> <i class="fa fa-hashtag"></i>United<span class="light">We</span>Stand </a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse navbar-right navbar-main-collapse"> <ul class="nav navbar-nav"> <!-- Hidden li included to remove active class from about link when scrolled up past about section --> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a href="#page-top">About</a> </li> <li> <a href="./schedule">Schedule</a> </li> <li> <a href="./board">The Board</a> </li> <li> <a href="./workshops">Workshops</a> </li> <li> <a href="./contact">Contact</a> </li> <li> <a href="./sponsors">Sponsors</a> </li> <li> <a href="./survey">Survey</a> </li> <li> <a href="./img/campusmap.pdf" download>Map</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container --> </nav> <section id="about" class="container content-section text-center about"> <div class="row"> <div class="col-xs-12 big_logo"> <img src="img/big_logo.png" style="max-width: 99%"/> </div> </div> <!-- <h2 class="section-title gray scrollimation scale-in">Who we are<i class="fa fa-university"></i></h2> --> <div class="row about-row"> <div class="col-xs-12"> <h4 class="section-header center">Spring Conference 2017</h4> <p class="about-font center"><hr>University of Michigan | April 7 - April 8<br/><hr> Banquet is located at: <br/> 46100 Grand River Ave.</br> Novi, MI 48374</p> </div> </div> <div class="row gray-row about-row"> <div class="col-xs-12"> <h4 class="section-header center">The Theme</h4> <p class="about-font center"> As one of MAASU's missions is to "unite and strengthen the A/PIA community's stance against all forms of oppression," #UnitedWeStand is aimed towards uniting the A/PIA community with one another to discover the history of our roots and our identities that serve as the grounds of current social justice movements. The conference aims to provide an inclusive space where we are able to strengthen our connections with other people of color and people with diverse religions, abilities, sexualities, and experiences, to unite for the common causes of intersectionality and bettering the quality of our lives.</p> </div> <div class="col-xs-12"> <img src="img/maasu-logo.png" style="max-width: 50%"/> </div> </div> <div class="row about-row"> <div class="col-xs-12"> <h4 class="section-header center">The University of Michigan</h4> <p class="about-font center">Founded in 1817, the University of Michigan (UM or UMich) has had a long history of excellence both inside and outside the classroom. According to the 2015 U.S. World News and Report, UM is ranked fourth best among public universities across the country. The university consists of a robust, diverse undergraduate community of over 25,000 students, a third of which are students of color. The Asian/Pacific Islander American (A/PIA) student population hovers around 14% every year. As a college town, Ann Arbor is a lively and instructive conduit for students to learn and grow. UM has fostered a long and supportive relationship with Midwest Asian American Student Union (MAASU), having hosted the MAASU spring conference seven times in the past. The most recent time was in 2013, when registration peaked over 980 participants.</p> </div> <div class="col-xs-12 logos"> <img src="img/um-logo.png" style="max-width: 50%"/> </div> </div> <div class="row gray-row about-row"> <div class="col-xs-12"> <h4 class="section-header center">United Asian American Organizations</h4> <p class="about-font center">The United Asian American Organizations (UAAO) was established to work in unity to provide education on issues facing Asian Pacific Islander Americans. We promote awareness of A/PIA cultures and establish a communication core for the A/PIA organizations and individuals at the University of Michigan in Ann Arbor. UAAO is a coalition of about 20 A/PIA organizations on the University of Michigan campus. UAAO participants are diverse in heritage and culture, each with a unique background and intersection of identities. UAAO provides a forum for discussion regarding social issues surrounding the A/PIA community and acts as a liaison between member organizations and external organizations.</p> </div> <div class="col-xs-12 logos"> <img src="img/uaao-logo.png" style="max-width: 50%"/> </div> </div> </section> <!-- Footer --> <footer> <div class="container footer center"> <div class="footer-brand"> <i class="fa fa-hashtag"></i> United<span class="light">We</span>Stand </div> <nav class="navbar" role="navigation"> <ul class="nav navbar-nav"> <!-- Hidden li included to remove active class from about link when scrolled up past about section --> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a href="#page-top">About</a> </li> <li> <a href="./schedule">Schedule</a> </li> <li> <a href="./board">The Board</a> </li> <li> <a href="./workshops">Workshops</a> </li> <li> <a href="./contact">Contact</a> </li> <li> <a href="./sponsors">Sponsors</a> </li> <li> <a href="./survey">Survey</a> </li> <li> <a href="./img/campusmap.pdf" download>Map</a> </li> </ul> </nav> <p class="center">Copyright &copy; Midwest Asian American Students Union </p> </div> </footer> </body> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="js/jquery.easing.min.js"></script> <script src="js/jquery.backstretch.min.js"></script> <script src="js/waypoint.min.js"></script> <!-- <script src="js/validator.min.js"></script> --> <script src="mobile/js/mobile.js"></script> <!-- <script src="js/main.js"></script> <script src="js/toastr.min.js"></script> <script src="js/typed.min.js"></script> --> <!-- <script src="js/bootstrap-table.js"></script> <script src="js/bootstrap-table-select2-filter.js"></script> -->
maasu2017/maasu2017.github.io
mobile.html
HTML
apache-2.0
10,477
/* * Copyright 2016-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.cluster; import org.onlab.packet.IpAddress; import com.google.common.collect.Sets; import org.onosproject.core.Version; /** * Test adapter for the ClusterMetadata service. */ public class ClusterMetadataServiceAdapter implements ClusterMetadataService { @Override public ClusterMetadata getClusterMetadata() { final NodeId nid = new NodeId("test-node"); final IpAddress addr = IpAddress.valueOf(0); final Partition p = new DefaultPartition(PartitionId.from(1), Version.version("1.0.0"), Sets.newHashSet(nid)); return new ClusterMetadata("test-cluster", Sets.newHashSet(new DefaultControllerNode(nid, addr)), Sets.newHashSet(p)); } @Override public ControllerNode getLocalNode() { return null; } @Override public void addListener(ClusterMetadataEventListener listener) { } @Override public void removeListener(ClusterMetadataEventListener listener) { } }
osinstom/onos
core/api/src/test/java/org/onosproject/cluster/ClusterMetadataServiceAdapter.java
Java
apache-2.0
1,664
package dao import ( "context" "flag" "log" "math/rand" "os" "strconv" "testing" "time" . "github.com/smartystreets/goconvey/convey" "go-common/app/service/main/dapper/conf" "go-common/app/service/main/dapper/model" ) func init() { rand.Seed(time.Now().UnixNano()) } var cfg *conf.Config var flagMap = map[string]string{ "app_id": "main.common-arch.dapper-service", "conf_token": "528dd7e00bb411e894c14a552f48fef8", "tree_id": "5172", "conf_version": "server-1", "deploy_env": "uat", "conf_host": "config.bilibili.co", "conf_path": os.TempDir(), "region": "sh", "zone": "sh001", } func TestMain(m *testing.M) { for key, val := range flagMap { flag.Set(key, val) } flag.Parse() if err := conf.Init(); err != nil { log.Printf("init config from remote error: %s", err) } cfg = conf.Conf if cfg.InfluxDB != nil { cfg.InfluxDB.Database = "dapper_ut" } if cfg.HBase != nil { cfg.HBase.Namespace = "dapperut" } if hbaseAddrs := os.Getenv("TEST_HBASE_ADDRS"); hbaseAddrs != "" { cfg.HBase = &conf.HBaseConfig{Addrs: hbaseAddrs, Namespace: "dapperut"} if influxdbAddr := os.Getenv("TEST_INFLUXDB_ADDR"); influxdbAddr != "" { cfg.InfluxDB = &conf.InfluxDBConfig{Addr: influxdbAddr, Database: "dapper_ut"} } } os.Exit(m.Run()) } func TestDao(t *testing.T) { if cfg == nil { t.Skipf("no config provide skipped") } daoImpl, err := New(cfg) if err != nil { t.Fatalf("new dao error: %s", err) } ctx := context.Background() Convey("test fetch serviceName and operationName", t, func() { serviceNames, err := daoImpl.FetchServiceName(ctx) So(err, ShouldBeNil) So(serviceNames, ShouldNotBeEmpty) for _, serviceName := range serviceNames { operationNames, err := daoImpl.FetchOperationName(ctx, serviceName) So(err, ShouldBeNil) t.Logf("%s operationNames: %v", serviceName, operationNames) } }) Convey("test write rawtrace", t, func() { if err := daoImpl.WriteRawTrace( context.Background(), strconv.FormatUint(rand.Uint64(), 16), map[string][]byte{strconv.FormatUint(rand.Uint64(), 16): []byte("hello world")}, ); err != nil { t.Error(err) } }) Convey("test batchwrite span point", t, func() { points := []*model.SpanPoint{ &model.SpanPoint{ ServiceName: "service_a", OperationName: "opt1", PeerService: "peer_service_a", SpanKind: "client", Timestamp: time.Now().Unix() - rand.Int63n(3600), MaxDuration: model.SamplePoint{ SpanID: rand.Uint64(), TraceID: rand.Uint64(), Value: rand.Int63n(1024), }, MinDuration: model.SamplePoint{ SpanID: rand.Uint64(), TraceID: rand.Uint64(), Value: rand.Int63n(1024), }, AvgDuration: model.SamplePoint{ SpanID: rand.Uint64(), TraceID: rand.Uint64(), Value: rand.Int63n(1024), }, Errors: []model.SamplePoint{ model.SamplePoint{ SpanID: rand.Uint64(), TraceID: rand.Uint64(), Value: 1, }, model.SamplePoint{ SpanID: rand.Uint64(), TraceID: rand.Uint64(), Value: 1, }, }, }, &model.SpanPoint{ ServiceName: "service_b", OperationName: "opt2", PeerService: "peer_service_b", SpanKind: "server", Timestamp: time.Now().Unix() - rand.Int63n(3600), }, &model.SpanPoint{ ServiceName: "service_c", OperationName: "opt3", PeerService: "peer_service_c", SpanKind: "client", Timestamp: time.Now().Unix() - rand.Int63n(3600), }, } err := daoImpl.BatchWriteSpanPoint(context.Background(), points) if err != nil { t.Error(err) } }) }
LQJJ/demo
126-go-common-master/app/service/main/dapper/dao/dao_test.go
GO
apache-2.0
3,660
/* * Copyright 2010 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.simpledb.model; import com.amazonaws.AmazonServiceException; /** * <p> * The specified domain does not exist. * </p> */ public class NoSuchDomainException extends AmazonServiceException { private static final long serialVersionUID = 1L; private Float boxUsage; /** * Constructs a new NoSuchDomainException with the specified error * message. * * @param message Describes the error encountered. */ public NoSuchDomainException(String message) { super(message); } /** * Returns the value of the BoxUsage property for this object. * * @return The value of the BoxUsage property for this object. */ public Float getBoxUsage() { return boxUsage; } /** * Sets the value of the BoxUsage property for this object. * * @param boxUsage The new value for this object's BoxUsage property. */ public void setBoxUsage(Float boxUsage) { this.boxUsage = boxUsage; } }
amahule/aws-sdk-for-android
src/com/amazonaws/services/simpledb/model/NoSuchDomainException.java
Java
apache-2.0
1,652
<include file="__THEME__/public_header" /> <div id="page-wrap"> <div id="main-wrap" class=" bd-not"> <div class="extend"> <div style="margin:50px 0"> 搜索用户:{:W('SearchUser', array('name' => 'selectUser', 'uids' => array(10000,14983),'follow'=>0,'max'=>10,'editable'=>1))} </div> <div> <pre> 调用:W('SearchUser', array('name' => 'selectUser', 'uids' => array(10000,14983),'follow'=>0,'max'=>10,'editable'=>0)) 参数说明: name 存储uid的input名称 uids 已选择的用户id集合 follow 是否只能选择已关注的人(0表示可以选择全部用户,1表示只能选择已关注的人) max 最多可选择的用户个数 editable是否可修改选择的结果,如果为0则不能选择用户,不能删除已经选择的用户 </pre> </div> </div> </div> </div> <include file="__THEME__/public_footer" />
kindlejiang/jkb
apps/public/Tpl/default/Test/searchUser.html
HTML
apache-2.0
925
#!/usr/bin/env python # -*- coding: iso-8859-2 -*- import string import copy import os import gzip import gtk import commands try: from backports import lzma except ImportError: from lzma import LZMAFile as lzma import singletons from common import * import common; _ = common._ from Source import * from Package import * from Category import * def czfind(istr): l = len(istr) i = 0 word = '' flag = False while i < l: if istr[i] == '\n': if flag: flag = False else: break word = '' elif istr[i] == ' ': flag = True else: word += istr[i] i += 1 return word class PackagePool: """This class retrieves and structures every packages that are accessible from the system.""" HASHED_LEN = 2 # used by GetUpgradeableState def __init__(self): self.initialized = False def Init(self): """Reinitialize the inner state of the package pool. Must be called in case of manipulating the package registry.""" self.initialized = False self.all_packages = [] self.package_name_pool = {} self.installed_package_names = {} singletons.application.DisplayProgress(_('Reading package sources')) self.RegisterUpgradablePackages() self.all_sources = self.GetSources() singletons.application.DisplayProgress(_('Querying installed packages')) self.RegisterInstalledPackages() self.RegisterInstallablePackages() self.initialized = True def GetSources(self): """Retrieve and return the Source objects containted in urpmi.cfg.""" def get_source_name(line): """Extract the source name from the line of the file.""" prev_chr = line[0] name = line[0] for c in line[1:-1]: if c == ' ': if prev_chr == '\\': name += ' ' else: break elif c != '\\': name += c prev_chr = c return name file = open('/etc/urpmi/urpmi.cfg') sources = [] word = '' flag0 = False flag1 = False name_flag = False while 1: c = file.read(1) if c == '': break elif c == '{': if flag0 == False: flag0 = True else: name_flag = False name = get_source_name(word) source = Source(name) source.hdlist = czfind(commands.getoutput('find /var/lib/urpmi/ | grep cz | grep ' + name)) print 'HL:', source.hdlist if source.hdlist != '': sources.append(source) word = '' elif c == '}': if flag1 == False: flag1 = True name_flag = True else: name_flag = True elif name_flag == True and c not in ['\\', '\n']: word += c return sources def GetActiveSources(self, new=False): """Return the active Source objects.""" if new: all_sources = self.GetSources() else: all_sources = self.all_sources return [source for source in all_sources if not source.ignore] def RegisterInstalledPackages(self): """Retrieve a dictionary containing every installed packages on the system.""" file = os.popen('rpmquery --all "--queryformat=%{name}-%{version}-%{release}.%{arch}:%{size}:%{group}:%{installtime}\n"') for line in file: fields = line.strip().split(':') name = fields[0] size = int(fields[1]) category = fields[2] btime = int(fields[3]) self.AddPackage(name, size, category, time=btime) def RegisterInstallablePackages(self): """Get the list of every packages that are installable on the system.""" for source in self.GetActiveSources(): #disable gzip file = gzip.open(source.hdlist) # print "DEBUG " + lzma.open(source.hdlist).read() file = lzma(source.hdlist) for line in file: if line[:6] != '@info@': continue fields = line.strip()[7:].split('@') longname = fields[0] size = int(fields[2]) category = fields[3] self.AddPackage(longname, size, category, source) def RegisterUpgradablePackages(self): upl = commands.getoutput('urpmq --auto-select --whatrequires').split() l = len (upl) i = 0 self.upgradable_packages = [] self.upgradable_packages_long = [] while i < l: self.upgradable_packages.append(self.generate_shortname(upl[i])) self.upgradable_packages_long.append(upl[i]) i += 1 def generate_shortname(self, longname): """Generate shortname from a longname. This is a workaround if association failed.""" print("LONGN:", longname) pos1 = longname.rfind("-") if pos1 > 0: pos2 = longname[:pos1].rfind("-") return longname[:pos2] else: return "" def RegisterCategory(self, category_str, package): """Register category 'category' in the category tree.""" category_path = category_str.split('/') current_category = self.category_tree for subcategory_name in category_path: current_category = current_category.GetSubCategory(subcategory_name) current_category.AddPackage(package) def AddPackage(self, longname, size, category, source=None, time=-1): """Add package to the registry.""" if self.package_name_pool.has_key(longname): self.package_name_pool[longname].AddSource(source) return package = Package() package.longname = longname package.shortname = self.generate_shortname(longname) ### Ezt raktam be !!! package.size = size package.category = category if source: package.AddSource(source) package.is_installed = False else: package.is_installed = True package.time = time if len(package.longname) >= 3: if package.longname.lower().find('lib') != -1: package.is_library = True else: package.is_library = False else: package.is_library = False if package.shortname in self.upgradable_packages and package.is_installed: package.is_upgradable = True else: package.is_upgradable = False self.package_name_pool[longname] = package self.all_packages.append(package) def GetPackagesContainingDescription(self, text): """Get the list of every packages that are installable on the system.""" active_sources = self.GetActiveSources() #[source for source in self.all_sources if not source.ignore] containing_longnames = {} for source in active_sources: file = lzma.open(source.hdlist) for line in file: if line[:9] == '@summary@': fields = line.strip().split('@') description = fields[2] elif line[:6] == '@info@': fields = line.strip().split('@') longname = fields[2] if description.lower().find(text) != -1: containing_longnames[longname] = True return containing_longnames FILTER_PACKAGENAME = 0 FILTER_DESCRIPTION = 1 FILTER_FILENAME = 2 def GetPackagesContainingFiles(self, search_text): pass # active_sources = self.GetActiveSources() # active_source_paths = '' # containing_longnames = {} # for source in active_sources: # active_source_paths += escape(source.hdlist) + ' ' # command = 'parsehdlist --fileswinfo ' + active_source_paths + ' | grep ".*:files:.*'+escape(search_text)+'.*"' # file = os.popen(command) # for line in file: # containing_longnames[ line.split(':')[0] ] = True # return containing_longnames def Filter(self, application, library, installed, noninstalled, search_mode, search_text): """Filter packages.""" # reset pacage registry self.packages = [] self.category_tree = Category('root') search_text = search_text.lower() if search_mode == self.FILTER_DESCRIPTION: containing_longnames = self.GetPackagesContainingDescription(search_text) elif search_mode == self.FILTER_FILENAME: containing_longnames = self.GetPackagesContainingFiles(search_text) for source in self.all_sources: source.packages = [] for package in self.all_packages: inst = (package.is_installed and installed) or (not package.is_installed and noninstalled) ptype = (package.is_library and library) or (not package.is_library and application) if search_mode == self.FILTER_PACKAGENAME: search_inc = package.longname.lower().find(search_text)!=-1 elif search_mode == self.FILTER_DESCRIPTION: search_inc = containing_longnames.has_key(package.longname) elif search_mode == self.FILTER_FILENAME: search_inc = containing_longnames.has_key(package.shortname) else: search_inc = True included = inst and ptype and search_inc if included: for source in package.sources: source.AddPackage(package) self.RegisterCategory(package.category, package) self.packages.append(package)
blackPantherOS/packagemanagement
rpmanager/PackagePool.py
Python
apache-2.0
10,079
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.launchpad.webapp.integrationtest; import org.apache.sling.commons.testing.integration.HttpTestBase; import org.apache.sling.servlets.post.SlingPostConstants; /** Test JSP scripting * TODO this class can be generalized to be used for any scripting language, * that would help in testing all scripting engines. */ public class JspScriptingTest extends HttpTestBase { private String testRootUrl; private TestNode rtNode; private TestNode unstructuredNode; @Override protected void setUp() throws Exception { super.setUp(); final String testRootPath = HTTP_BASE_URL + "/" + getClass().getSimpleName() + "/" + System.currentTimeMillis(); testRootUrl = testClient.createNode(testRootPath + SlingPostConstants.DEFAULT_CREATE_SUFFIX, null); rtNode = new TestNode(testRootPath + "/rt", null); unstructuredNode = new TestNode(testRootPath + "/unstructured", null); } @Override protected void tearDown() throws Exception { testClient.delete(testRootUrl); super.tearDown(); } public void testRtNoScript() throws Exception { final String content = getContent(rtNode.nodeUrl + ".txt", CONTENT_TYPE_PLAIN); assertTrue(content.contains("PlainTextRendererServlet")); assertTrue("Content contains " + rtNode.testText + " (" + content + ")", content.contains(rtNode.testText)); } public void testUnstructuredNoScript() throws Exception { final String content = getContent(unstructuredNode.nodeUrl + ".txt", CONTENT_TYPE_PLAIN); assertTrue(content.contains("PlainTextRendererServlet")); assertTrue("Content contains " + unstructuredNode.testText + " (" + content + ")", content.contains(unstructuredNode.testText)); } public void testRtJsp() throws Exception { final String toDelete = uploadTestScript(rtNode.scriptPath, "rendering-test.jsp", "html.jsp"); try { checkContent(rtNode); } finally { if(toDelete != null) { testClient.delete(toDelete); } } } public void testUnstructuredJsp() throws Exception { final String toDelete = uploadTestScript(unstructuredNode.scriptPath, "rendering-test.jsp", "html.jsp"); try { checkContent(unstructuredNode); } finally { if(toDelete != null) { testClient.delete(toDelete); } } } private void checkContent(TestNode tn) throws Exception { final String content = getContent(tn.nodeUrl + ".html", CONTENT_TYPE_HTML); assertTrue("JSP script executed as expected (" + content + ")", content.contains("<h1>JSP rendering result</h1>")); final String [] expected = { "using resource.adaptTo:" + tn.testText, "using currentNode:" + tn.testText, }; for(String exp : expected) { assertTrue("Content contains " + exp + "(" + content + ")", content.contains(exp)); } } }
codders/k2-sling-fork
launchpad/testing/src/test/java/org/apache/sling/launchpad/webapp/integrationtest/JspScriptingTest.java
Java
apache-2.0
3,896
/* * Copyright 2005-2013 shopxx.net. All rights reserved. * Support: http://www.shopxx.net * License: http://www.shopxx.net/license */ package net.groupbuy.service; import net.groupbuy.Page; import net.groupbuy.Pageable; import net.groupbuy.entity.Member; import net.groupbuy.entity.Message; /** * Service - 消息 * * @author SHOP++ Team * @version 3.0 */ public interface MessageService extends BaseService<Message, Long> { /** * 查找消息分页 * * @param member * 会员,null表示管理员 * @param pageable * 分页信息 * @return 消息分页 */ Page<Message> findPage(Member member, Pageable pageable); /** * 查找草稿分页 * * @param sender * 发件人,null表示管理员 * @param pageable * 分页信息 * @return 草稿分页 */ Page<Message> findDraftPage(Member sender, Pageable pageable); /** * 查找消息数量 * * @param member * 会员,null表示管理员 * @param read * 是否已读 * @return 消息数量,不包含草稿 */ Long count(Member member, Boolean read); /** * 删除消息 * * @param id * ID * @param member * 执行人,null表示管理员 */ void delete(Long id, Member member); }
groupbuyteam/groupbuy
src/net/groupbuy/service/MessageService.java
Java
apache-2.0
1,306
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.watterssoft.appsupport.application.ui; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.watterssoft.appsupport.application.domain.Application; import org.watterssoft.appsupport.application.domain.ApplicationDTO; import org.watterssoft.appsupport.application.service.ApplicationService; import org.watterssoft.appsupport.user.service.UserService; /** * @author johnwatters Apr 25, 2014 9:38:58 PM */ @Controller @RequestMapping("/application") public class ApplicationController { private UserService userService; private ApplicationService applicationService; @Autowired public ApplicationController(UserService userService, ApplicationService applicationService) { super(); this.userService = userService; this.applicationService = applicationService; } @RequestMapping("/list") public @ResponseBody List<ApplicationDTO> getUserApplications(HttpServletRequest request) { return applicationService.getAllUserApplicationDTO(request.getRemoteUser()); } @RequestMapping(value = "/addApplication", method = RequestMethod.POST) public @ResponseBody void addApplication(@RequestBody ApplicationDTO applicationDTO, HttpServletRequest request) { Application application = new Application(applicationDTO.getName(), applicationDTO.getVersion(), applicationDTO.getUrl()); application = applicationService.save(application, userService.getUserByUserName(request.getRemoteUser())); applicationDTO.setId(application.getId()); } @RequestMapping(value = "/newApp", method = RequestMethod.GET) public @ResponseBody ApplicationDTO newApplication(HttpServletRequest request) { return new ApplicationDTO(); } @RequestMapping(value = "/newBlankApplication", method = RequestMethod.GET) public String createBlankTicket() { return "application/newApplication"; } @RequestMapping("/layout") public String getTicketPartialPage() { return "application/layout"; } }
jwatters1981/ErrorCapture
src/main/java/org/watterssoft/appsupport/application/ui/ApplicationController.java
Java
apache-2.0
2,921
package fr.sii.ogham.template.thymeleaf.common.configure; import org.slf4j.Logger; import fr.sii.ogham.core.builder.MessagingBuilder; import fr.sii.ogham.core.builder.configurer.DefaultMessagingConfigurer; import fr.sii.ogham.core.builder.configurer.MessagingConfigurer; import fr.sii.ogham.core.builder.configurer.MessagingConfigurerAdapter; import fr.sii.ogham.core.builder.env.EnvironmentBuilder; import fr.sii.ogham.core.builder.resolution.ResourceResolutionBuilder; import fr.sii.ogham.core.message.content.EmailVariant; import fr.sii.ogham.template.thymeleaf.common.buider.AbstractThymeleafMultiContentBuilder; /** * Default configurer for Thymeleaf template engine that is automatically * applied every time a {@link MessagingBuilder} instance is created through * {@link MessagingBuilder#standard()} or {@link MessagingBuilder#minimal()}. * * <p> * The configurer has a priority of 90000 in order to be applied after global * configurer but before any sender implementation. * </p> * * This configurer is applied only if {@code org.thymeleaf.TemplateEngine} is * present in the classpath. If not present, template engine is not registered * at all. * * <p> * This configurer inherits environment configuration (see * {@link EnvironmentBuilder}) * </p> * <p> * It also copies resource resolution configuration of * {@link DefaultMessagingConfigurer} to inherit resource resolution lookups * (see {@link ResourceResolutionBuilder}). * </p> * * <p> * This configurer applies the following configuration: * <ul> * <li>Configures template prefix/suffix paths: * <ul> * <li>Uses the first property that has a value for classpath resolution prefix: * <ol> * <li>"ogham.email.thymeleaf.classpath.path-prefix"</li> * <li>"ogham.email.template.classpath.path-prefix"</li> * <li>"ogham.email.thymeleaf.path-prefix"</li> * <li>"ogham.email.template.path-prefix"</li> * <li>"ogham.template.path-prefix"</li> * </ol> * </li> * <li>Uses the first property that has a value for classpath resolution suffix: * <ol> * <li>"ogham.email.thymeleaf.classpath.path-suffix"</li> * <li>"ogham.email.template.classpath.path-suffix"</li> * <li>"ogham.email.thymeleaf.path-suffix"</li> * <li>"ogham.email.template.path-suffix"</li> * <li>"ogham.template.path-suffix"</li> * </ol> * </li> * <li>Uses the first property that has a value for file resolution prefix: * <ol> * <li>"ogham.email.thymeleaf.file.path-prefix"</li> * <li>"ogham.email.template.file.path-prefix"</li> * <li>"ogham.email.thymeleaf.path-prefix"</li> * <li>"ogham.email.template.path-prefix"</li> * <li>"ogham.template.path-prefix"</li> * </ol> * </li> * <li>Uses the first property that has a value for file resolution suffix: * <ol> * <li>"ogham.email.thymeleaf.file.path-suffix"</li> * <li>"ogham.email.template.file.path-suffix"</li> * <li>"ogham.email.thymeleaf.path-suffix"</li> * <li>"ogham.email.template.path-suffix"</li> * <li>"ogham.template.path-suffix"</li> * </ol> * </li> * </ul> * </li> * <li>Configures email alternative content: * <ul> * <li>Automatically loads HTML template if extension is .html</li> * <li>Automatically loads text template if extension is .txt</li> * </ul> * </li> * <li>Configures template detection: * <ul> * <li>Uses ThymeleafTemplateDetector to detect if templates are * parseable by Thymeleaf</li> * </ul> * </li> * </ul> * * @author Aurélien Baudet * */ public abstract class AbstractDefaultThymeleafEmailConfigurer implements MessagingConfigurer { private final Logger log; private final MessagingConfigurerAdapter delegate; public AbstractDefaultThymeleafEmailConfigurer(Logger log) { this(log, new DefaultMessagingConfigurer()); } public AbstractDefaultThymeleafEmailConfigurer(Logger log, MessagingConfigurerAdapter delegate) { super(); this.log = log; this.delegate = delegate; } @Override public void configure(MessagingBuilder msgBuilder) { if (!canUseThymeleaf()) { log.debug("[{}] skip configuration", this); return; } log.debug("[{}] apply configuration", this); AbstractThymeleafMultiContentBuilder<?, ?, ?> builder = msgBuilder.email().template(getBuilderClass()); // apply default resource resolution configuration if (delegate != null) { delegate.configure(builder); } // @formatter:off builder .classpath() .pathPrefix() .properties("${ogham.email.thymeleaf.classpath.path-prefix}", "${ogham.email.template.classpath.path-prefix}", "${ogham.email.thymeleaf.path-prefix}", "${ogham.email.template.path-prefix}", "${ogham.template.path-prefix}") .and() .pathSuffix() .properties("${ogham.email.thymeleaf.classpath.path-suffix}", "${ogham.email.template.classpath.path-suffix}", "${ogham.email.thymeleaf.path-suffix}", "${ogham.email.template.path-suffix}", "${ogham.template.path-suffix}") .and() .and() .file() .pathPrefix() .properties("${ogham.email.thymeleaf.file.path-prefix}", "${ogham.email.template.file.path-prefix}", "${ogham.email.thymeleaf.path-prefix}", "${ogham.email.template.path-prefix}", "${ogham.template.path-prefix}") .and() .pathSuffix() .properties("${ogham.email.thymeleaf.file.path-suffix}", "${ogham.email.template.file.path-suffix}", "${ogham.email.thymeleaf.path-suffix}", "${ogham.email.template.path-suffix}", "${ogham.template.path-suffix}") .and() .and() .string() .and() .variant(EmailVariant.HTML, "html") .variant(EmailVariant.HTML, "xhtml") .variant(EmailVariant.TEXT, "txt") .cache() .properties("${ogham.email.thymeleaf.cache}", "${ogham.email.template.cache}", "${ogham.template.cache}"); // @formatter:on } protected abstract Class<? extends AbstractThymeleafMultiContentBuilder<?, ?, ?>> getBuilderClass(); protected abstract boolean canUseThymeleaf(); }
groupe-sii/ogham
ogham-template-thymeleaf-common/src/main/java/fr/sii/ogham/template/thymeleaf/common/configure/AbstractDefaultThymeleafEmailConfigurer.java
Java
apache-2.0
5,999
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>后台首页</title> <link href="css/css.css" rel="stylesheet" type="text/css" /> <!--[if IE]><script src="public/jquery/jquery-1.11.1.min.js"></script><![endif]--> <!--[if !IE]><!--><script src="public/jquery/jquery-2.1.1.min.js"></script><!--<![endif]--> <script src="js/tab.js"></script> </head> <body> <div id="main"> <div id="main_top"> </div> <div id="art_body"> <table cellspacing="0" class="add_art"> <tr><th colspan="2"><h3>系统操作提示信息</h3></th></tr> <tr> <td width="240"><img src="image/duihao.png" style="display:block; margin:20px auto" /></td> <td> {if $_GET['re']=='1'} 操作成功! {elseif $_GET['re']=='0'} 操作失败! {/if} <script>setTimeout("Gotonew('?controller=tplmanage&project={$_GET['project']}')",3000); </script> </td> </tr> <tr> <th colspan="2"> 【<a href="?controller=tplmanage&project={$_GET['project']}">返回列表</a>】 </th> </tr> </table> </div> </div> </body> </html>
fengcms/fengcms
admin/template/tplmanage/execution.html
HTML
apache-2.0
1,350
package com.aula.andre.drogaria.domain; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity @SuppressWarnings("serial") public class Cliente extends GenericDomain { @Column(nullable = false) @Temporal(TemporalType.DATE) private Date dataCadastro; @Column(nullable = false) private Boolean liberado; @OneToOne @JoinColumn(nullable = false) private Pessoa pessoa; public Date getDataCadastro() { return dataCadastro; } public void setDataCadastro(Date dataCadastro) { this.dataCadastro = dataCadastro; } public Boolean getLiberado() { return liberado; } public void setLiberado(Boolean liberado) { this.liberado = liberado; } public Pessoa getPessoa() { return pessoa; } public void setPessoa(Pessoa pessoa) { this.pessoa = pessoa; } }
adrlgit/Drogaria
Drogaria/src/main/java/com/aula/andre/drogaria/domain/Cliente.java
Java
apache-2.0
972
/* * Copyright 2016-2020 chronicle.software * * https://chronicle.software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package net.openhft.chronicle.bytes; import net.openhft.chronicle.core.io.ClosedIllegalStateException; import net.openhft.chronicle.core.util.ObjectUtils; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Proxy; import java.nio.BufferOverflowException; import java.nio.BufferUnderflowException; import static net.openhft.chronicle.bytes.internal.ReferenceCountedUtil.throwExceptionIfReleased; @SuppressWarnings({"rawtypes", "unchecked"}) public interface BytesOut<U> extends StreamingDataOutput<Bytes<U>>, ByteStringAppender<Bytes<U>>, BytesPrepender<Bytes<U>>, BytesComment<BytesOut<U>> { /** * Proxy an interface so each message called is written to a file for replay. * * @param tClass primary interface * @param additional any additional interfaces * @return a proxy which implements the primary interface (additional interfaces have to be * cast) * @throws NullPointerException if the provided {@code tClass} is {@code null} * @throws ClosedIllegalStateException if this BytesOut has been previously released */ @NotNull default <T> T bytesMethodWriter(@NotNull Class<T> tClass, Class... additional) throws IllegalArgumentException { throwExceptionIfReleased(this); Class[] interfaces = ObjectUtils.addAll(tClass, additional); //noinspection unchecked return (T) Proxy.newProxyInstance(tClass.getClassLoader(), interfaces, new BinaryBytesMethodWriterInvocationHandler(tClass, MethodEncoderLookup.BY_ANNOTATION, this)); } void writeMarshallableLength16(WriteBytesMarshallable marshallable) throws IllegalArgumentException, BufferOverflowException, IllegalStateException, BufferUnderflowException; /** * Write a limit set of writeObject types. * * @param componentType expected. * @param obj of componentType */ default void writeObject(Class componentType, Object obj) throws IllegalArgumentException, BufferOverflowException, ArithmeticException, IllegalStateException, BufferUnderflowException { if (!componentType.isInstance(obj)) throw new IllegalArgumentException("Cannot serialize " + obj.getClass() + " as an " + componentType); if (obj instanceof BytesMarshallable) { ((BytesMarshallable) obj).writeMarshallable(this); return; } if (obj instanceof Enum) { writeEnum((Enum) obj); return; } if (obj instanceof BytesStore) { BytesStore bs = (BytesStore) obj; writeStopBit(bs.readRemaining()); write(bs); return; } switch (componentType.getName()) { case "java.lang.String": writeUtf8((String) obj); return; case "java.lang.Double": writeDouble((Double) obj); return; case "java.lang.Long": writeLong((Long) obj); return; case "java.lang.Integer": writeInt((Integer) obj); return; default: throw new UnsupportedOperationException("Not supported " + componentType); } } }
OpenHFT/Chronicle-Bytes
src/main/java/net/openhft/chronicle/bytes/BytesOut.java
Java
apache-2.0
3,969
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.adapter.druid; import org.apache.calcite.rel.type.RelDataType; import org.apache.calcite.rex.RexCall; import org.apache.calcite.rex.RexLiteral; import org.apache.calcite.rex.RexNode; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.fun.SqlStdOperatorTable; import javax.annotation.Nullable; /** * Converts Calcite SUBSTRING call to Druid Expression when possible */ public class SubstringOperatorConversion implements DruidSqlOperatorConverter { @Override public SqlOperator calciteOperator() { return SqlStdOperatorTable.SUBSTRING; } @Nullable @Override public String toDruidExpression(RexNode rexNode, RelDataType rowType, DruidQuery query) { final RexCall call = (RexCall) rexNode; final String arg = DruidExpressions.toDruidExpression( call.getOperands().get(0), rowType, query); if (arg == null) { return null; } final String startIndex; final String length; // SQL is 1-indexed, Druid is 0-indexed. if (!call.getOperands().get(1).isA(SqlKind.LITERAL)) { final String arg1 = DruidExpressions.toDruidExpression( call.getOperands().get(1), rowType, query); if (arg1 == null) { // can not infer start index expression bailout. return null; } startIndex = DruidQuery.format("(%s - 1)", arg1); } else { startIndex = DruidExpressions.numberLiteral( RexLiteral.intValue(call.getOperands().get(1)) - 1); } if (call.getOperands().size() > 2) { //case substring from start index with length if (!call.getOperands().get(2).isA(SqlKind.LITERAL)) { // case it is an expression try to parse it length = DruidExpressions.toDruidExpression( call.getOperands().get(2), rowType, query); if (length == null) { return null; } } else { // case length is a constant length = DruidExpressions.numberLiteral(RexLiteral.intValue(call.getOperands().get(2))); } } else { //case substring from index to the end length = DruidExpressions.numberLiteral(-1); } return DruidQuery.format("substring(%s, %s, %s)", arg, startIndex, length); } }
googleinterns/calcite
druid/src/main/java/org/apache/calcite/adapter/druid/SubstringOperatorConversion.java
Java
apache-2.0
3,074
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class org_apache_hadoop_io_compress_zlib_ZlibCompressor_CompressionLevel */ #ifndef _Included_org_apache_hadoop_io_compress_zlib_ZlibCompressor_CompressionLevel #define _Included_org_apache_hadoop_io_compress_zlib_ZlibCompressor_CompressionLevel #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif
leechoongyon/HadoopSourceAnalyze
hadoop-common-project/hadoop-common/target/native/javah/org_apache_hadoop_io_compress_zlib_ZlibCompressor_CompressionLevel.h
C
apache-2.0
419
<?php require_once('kategori_tarif_mp_d_proses.php'); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <!-- CSS --> <link type="text/css" href="../../../../../config/css/style.css" rel="stylesheet"> <link type="text/css" href="../../../../../plugin/css/zebra/default.css" rel="stylesheet"> <!-- JS --> <script type="text/javascript" src="../../../../../plugin/js/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="../../../../../plugin/js/jquery-migrate-1.2.1.min.js"></script> <script type="text/javascript" src="../../../../../plugin/js/jquery.inputmask.custom.js"></script> <script type="text/javascript" src="../../../../../plugin/js/keymaster.js"></script> <script type="text/javascript" src="../../../../../plugin/js/zebra_datepicker.js"></script> <script type="text/javascript" src="../../../../../config/js/main.js"></script> <script type="text/javascript"> $(function() { key('alt+s', function(e) { e.preventDefault(); $('#save').trigger('click'); }); key('alt+r', function(e) { e.preventDefault(); $('#reset').trigger('click'); }); key('esc', function(e) { e.preventDefault(); $('#close').trigger('click'); }); $('#kode_tipe').on('change', function(e) { e.preventDefault(); var key_mp = $('#kode_sk').val() + '-<?php echo $kode_mp; ?>-' + $(this).val(); $('#key_mp').val(key_mp); }); $('#close').on('click', function(e) { e.preventDefault(); return parent.loadData(); }); $(document).on('click', '#save', function(e) { e.preventDefault(); var url = base_master_fa + 'tarif_mp/d/kategori_tarif_mp_d_proses.php', data = $('#form').serialize(); $.post(url, data, function(data) { if (data.error == true) { alert(data.msg); } else { if (data.act == 'Simpan') { alert(data.msg); $('#reset').click(); } else if (data.act == 'Ubah') { alert(data.msg); parent.loadData(); } } }, 'json'); return false; }); }); </script> </head> <body class="popup"> <div id="msg"><?php echo $msg; ?></div> <form name="form" id="form" method="post"> <table class="t-popup wauto"> <tr> <td width="120">KODE</td> <td><input readonly="readonly" type="text" name="key_mp" id="key_mp" size="15" value="<?php echo $key_mp; ?>"></td> </tr> <tr> <td>KATEGORI</td> <td> <select name="kode_tipe" id="kode_tipe"> <option value=""> -- KATEGORI -- </option> <?php $obj = $conn->execute("SELECT KODE_TIPE, NAMA_TIPE FROM KWT_TIPE_MP WHERE KODE_MP = '$kode_mp' ORDER BY NAMA_TIPE ASC"); while( ! $obj->EOF) { $ov = $obj->fields['KODE_TIPE']; $on = $obj->fields['NAMA_TIPE']; echo "<option value='$ov' ".is_selected($ov, $kode_tipe)."> $on ($ov) </option>"; $obj->movenext(); } ?> </select> </td> </tr> <tr> <td>UKURAN</td> <td> <input type="text" name="ukuran_1" id="ukuran_1" size="6" maxlength="10" value="<?php echo $ukuran_1; ?>"> </td> </tr> <tr> <td></td> <td class="td-action"> <input type="submit" id="save" value=" <?php echo $act; ?> (Alt+S) "> <input type="reset" id="reset" value=" Reset (Alt+R) "> <input type="button" id="close" value=" Tutup (Esc) "></td> </td> </tr> </table> <input type="hidden" name="kode_sk" id="kode_sk" value="<?php echo $kode_sk; ?>"> <input type="hidden" name="id" id="id" value="<?php echo $id; ?>"> <input type="hidden" name="act" id="act" value="<?php echo $act; ?>"> </form> </body> </html> <?php close($conn); ?>
waykanza/fasilitas
administrator/master/fasilitas/tarif_mp/d/kategori_tarif_mp_d_popup.php
PHP
apache-2.0
3,435
#!/bin/bash # Copyright 2018 Istio Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. function setup_gcloud_credentials() { if [[ $(command -v gcloud) ]]; then gcloud auth configure-docker -q elif [[ $(command -v docker-credential-gcr) ]]; then docker-credential-gcr configure-docker else echo "No credential helpers found, push to docker may not function properly" fi } function setup_and_export_git_sha() { if [[ -n "${CI:-}" ]]; then if [ -z "${PULL_PULL_SHA:-}" ]; then if [ -z "${PULL_BASE_SHA:-}" ]; then GIT_SHA="$(git rev-parse --verify HEAD)" export GIT_SHA else export GIT_SHA="${PULL_BASE_SHA}" fi else export GIT_SHA="${PULL_PULL_SHA}" fi else # Use the current commit. GIT_SHA="$(git rev-parse --verify HEAD)" export GIT_SHA export ARTIFACTS="${ARTIFACTS:-$(mktemp -d)}" fi GIT_BRANCH="$(git rev-parse --abbrev-ref HEAD)" export GIT_BRANCH setup_gcloud_credentials } # Download and unpack istio release artifacts. function download_untar_istio_release() { local url_path=${1} local tag=${2} local dir=${3:-.} # Download artifacts LINUX_DIST_URL="${url_path}/istio-${tag}-linux.tar.gz" wget -q "${LINUX_DIST_URL}" -P "${dir}" tar -xzf "${dir}/istio-${tag}-linux.tar.gz" -C "${dir}" export ISTIOCTL_BIN="${GOPATH}/src/istio.io/istio/istio-${TAG}/bin/istioctl" } function build_images() { # Build just the images needed for tests for image in pilot proxyv2 app test_policybackend mixer citadel galley sidecar_injector kubectl node-agent-k8s; do DOCKER_BUILD_VARIANTS="${VARIANT:-default}" make docker.${image} done } function kind_load_images() { NAME="${1:-istio-testing}" for i in {1..3}; do # Archived local images and load it into KinD's docker daemon # Kubernetes in KinD can only access local images from its docker daemon. docker images "${HUB}/*:${TAG}" --format '{{.Repository}}:{{.Tag}}' | xargs -n1 kind --loglevel debug --name "${NAME}" load docker-image && break echo "Attempt ${i} to load images failed, retrying in 5s..." sleep 5 done # If a variant is specified, load those images as well. # We should still load non-variant images as well for things like `app` which do not use variants if [[ "${VARIANT:-}" != "" ]]; then for i in {1..3}; do docker images "${HUB}/*:${TAG}-${VARIANT}" --format '{{.Repository}}:{{.Tag}}' | xargs -n1 kind --loglevel debug --name "${NAME}" load docker-image && break echo "Attempt ${i} to load images failed, retrying in 5s..." sleep 5 done fi } # Cleanup e2e resources. function cleanup() { if [[ "${CLEAN_CLUSTERS}" == "True" ]]; then unsetup_clusters fi if [[ "${USE_MASON_RESOURCE}" == "True" ]]; then mason_cleanup cat "${FILE_LOG}" fi } # Set up a GKE cluster for testing. function setup_e2e_cluster() { WD=$(dirname "$0") WD=$(cd "$WD" || exit; pwd) ROOT=$(dirname "$WD") # shellcheck source=prow/mason_lib.sh source "${ROOT}/prow/mason_lib.sh" # shellcheck source=prow/cluster_lib.sh source "${ROOT}/prow/cluster_lib.sh" trap cleanup EXIT if [[ "${USE_MASON_RESOURCE}" == "True" ]]; then INFO_PATH="$(mktemp /tmp/XXXXX.boskos.info)" FILE_LOG="$(mktemp /tmp/XXXXX.boskos.log)" OWNER=${OWNER:-"e2e"} E2E_ARGS+=("--mason_info=${INFO_PATH}") setup_and_export_git_sha get_resource "${RESOURCE_TYPE}" "${OWNER}" "${INFO_PATH}" "${FILE_LOG}" else export GIT_SHA="${GIT_SHA:-$TAG}" fi setup_cluster } function clone_cni() { # Clone the CNI repo so the CNI artifacts can be built. if [[ "$PWD" == "${GOPATH}/src/istio.io/istio" ]]; then TMP_DIR=$PWD cd ../ || return git clone -b "${GIT_BRANCH}" "https://github.com/istio/cni.git" cd "${TMP_DIR}" || return fi } function cleanup_kind_cluster() { NAME="${1}" echo "Test exited with exit code $?." kind export logs --name "${NAME}" "${ARTIFACTS}/kind" --loglevel debug || true if [[ -z "${SKIP_CLEANUP:-}" ]]; then echo "Cleaning up kind cluster" kind delete cluster --name "${NAME}" --loglevel debug || true fi } function setup_kind_cluster() { IMAGE="${1:-}" NAME="${2:-istio-testing}" CONFIG="${3:-}" # Delete any previous e2e KinD cluster echo "Deleting previous KinD cluster with name=${NAME}" if ! (kind delete cluster --name="${NAME}") > /dev/null; then echo "No existing kind cluster with name ${NAME}. Continue..." fi # explicitly disable shellcheck since we actually want $NAME to expand now # shellcheck disable=SC2064 trap "cleanup_kind_cluster ${NAME}" EXIT # If config not explicitly set, then use defaults if [[ -z "${CONFIG}" ]]; then # Different Kubernetes versions need different patches K8S_VERSION=$(cut -d ":" -f 2 <<< "${IMAGE}") if [[ -n "${IMAGE}" && "${K8S_VERSION}" < "v1.13" ]]; then # Kubernetes 1.12 CONFIG=./prow/config/trustworthy-jwt-12.yaml elif [[ -n "${IMAGE}" && "${K8S_VERSION}" < "v1.15" ]]; then # Kubernetes 1.13, 1.14 CONFIG=./prow/config/trustworthy-jwt-13-14.yaml else # Kubernetes 1.15 CONFIG=./prow/config/trustworthy-jwt.yaml fi fi # Create KinD cluster if ! (kind create cluster --name="${NAME}" --config "${CONFIG}" --loglevel debug --retain --image "${IMAGE}" --wait=60s); then echo "Could not setup KinD environment. Something wrong with KinD setup. Exporting logs." exit 1 fi KUBECONFIG="$(kind get kubeconfig-path --name="${NAME}")" export KUBECONFIG kubectl apply -f ./prow/config/metrics } function cni_run_daemon_kind() { echo 'Run the CNI daemon set' ISTIO_CNI_HUB=${ISTIO_CNI_HUB:-gcr.io/istio-testing} ISTIO_CNI_TAG=${ISTIO_CNI_TAG:-latest} # TODO: this should not be pulling from external charts, instead the tests should checkout the CNI repo chartdir=$(mktemp -d) helm init --client-only helm repo add istio.io https://gcsweb.istio.io/gcs/istio-prerelease/daily-build/master-latest-daily/charts/ helm fetch --devel --untar --untardir "${chartdir}" istio.io/istio-cni helm template --values "${chartdir}"/istio-cni/values.yaml --name=istio-cni --namespace=kube-system --set "excludeNamespaces={}" \ --set-string hub="${ISTIO_CNI_HUB}" --set-string tag="${ISTIO_CNI_TAG}" --set-string pullPolicy=IfNotPresent --set logLevel="${CNI_LOGLVL:-debug}" "${chartdir}"/istio-cni > "${chartdir}"/istio-cni_install.yaml kubectl apply -f "${chartdir}"/istio-cni_install.yaml } # setup_cluster_reg is used to set up a cluster registry for multicluster testing function setup_cluster_reg () { MAIN_CONFIG="" for context in "${CLUSTERREG_DIR}"/*; do if [[ -z "${MAIN_CONFIG}" ]]; then MAIN_CONFIG="${context}" fi export KUBECONFIG="${context}" kubectl delete ns istio-system-multi --ignore-not-found kubectl delete clusterrolebinding istio-multi-test --ignore-not-found kubectl create ns istio-system-multi kubectl create sa istio-multi-test -n istio-system-multi kubectl create clusterrolebinding istio-multi-test --clusterrole=cluster-admin --serviceaccount=istio-system-multi:istio-multi-test CLUSTER_NAME=$(kubectl config view --minify=true -o "jsonpath={.clusters[].name}") gen_kubeconf_from_sa istio-multi-test "${context}" done export KUBECONFIG="${MAIN_CONFIG}" } function gen_kubeconf_from_sa () { local service_account=$1 local filename=$2 SERVER=$(kubectl config view --minify=true -o "jsonpath={.clusters[].cluster.server}") SECRET_NAME=$(kubectl get sa "${service_account}" -n istio-system-multi -o jsonpath='{.secrets[].name}') CA_DATA=$(kubectl get secret "${SECRET_NAME}" -n istio-system-multi -o "jsonpath={.data['ca\\.crt']}") TOKEN=$(kubectl get secret "${SECRET_NAME}" -n istio-system-multi -o "jsonpath={.data['token']}" | base64 --decode) cat <<EOF > "${filename}" apiVersion: v1 clusters: - cluster: certificate-authority-data: ${CA_DATA} server: ${SERVER} name: ${CLUSTER_NAME} contexts: - context: cluster: ${CLUSTER_NAME} user: ${CLUSTER_NAME} name: ${CLUSTER_NAME} current-context: ${CLUSTER_NAME} kind: Config preferences: {} users: - name: ${CLUSTER_NAME} user: token: ${TOKEN} EOF }
geeknoid/istio
prow/lib.sh
Shell
apache-2.0
8,956
// // AppDelegate.h // MoMo // // Created by Monster on 15/7/12. // Copyright (c) 2015年 aib. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
MonsterPetter/momo
MoMo/MoMo/AppDelegate.h
C
apache-2.0
267
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import os import pkgutil import threading import xml.etree.ElementTree as ET from abc import abstractmethod from builtins import object, open, str from collections import defaultdict, namedtuple from functools import total_ordering import six from future.utils import PY3 from twitter.common.collections import OrderedSet from pants.backend.jvm.subsystems.jar_dependency_management import (JarDependencyManagement, PinnedJarArtifactSet) from pants.backend.jvm.targets.exportable_jvm_library import ExportableJvmLibrary from pants.backend.jvm.targets.jar_library import JarLibrary from pants.base.generator import Generator, TemplateData from pants.base.revision import Revision from pants.build_graph.target import Target from pants.ivy.bootstrapper import Bootstrapper from pants.java.jar.exclude import Exclude from pants.java.jar.jar_dependency import JarDependency from pants.java.jar.jar_dependency_utils import M2Coordinate, ResolvedJar from pants.java.util import execute_runner from pants.util.collections_abc_backport import OrderedDict from pants.util.dirutil import safe_concurrent_creation, safe_mkdir, safe_open from pants.util.fileutil import atomic_copy, safe_hardlink_or_copy class IvyResolutionStep(object): """Ivy specific class for describing steps of performing resolution.""" # NB(nh): This class is the base class for the ivy resolve and fetch steps. # It also specifies the abstract methods that define the components of resolution steps. def __init__(self, confs, hash_name, pinned_artifacts, soft_excludes, ivy_resolution_cache_dir, ivy_repository_cache_dir, ivy_workdir): """ :param confs: A tuple of string ivy confs to resolve for. :param hash_name: A unique string name for this resolve. :param pinned_artifacts: A tuple of "artifact-alikes" to force the versions of. :param soft_excludes: A flag marking whether to pass excludes to Ivy or to apply them after the fact. :param ivy_repository_cache_dir: The cache directory used by Ivy for repository cache data. :param ivy_resolution_cache_dir: The cache directory used by Ivy for resolution cache data. :param ivy_workdir: A task-specific workdir that all ivy outputs live in. """ self.confs = confs self.hash_name = hash_name self.pinned_artifacts = pinned_artifacts self.soft_excludes = soft_excludes self.ivy_repository_cache_dir = ivy_repository_cache_dir self.ivy_resolution_cache_dir = ivy_resolution_cache_dir self.ivy_workdir = ivy_workdir self.workdir_reports_by_conf = {c: self.resolve_report_path(c) for c in confs} @abstractmethod def required_load_files_exist(self): """The files required to load a previous resolve exist.""" @abstractmethod def required_exec_files_exist(self): """The files to do a resolve exist.""" @abstractmethod def load(self, targets): """Loads the result of a resolve or fetch.""" @abstractmethod def exec_and_load(self, executor, extra_args, targets, jvm_options, workunit_name, workunit_factory): """Runs the resolve or fetch and loads the result, returning it.""" @property def workdir(self): return os.path.join(self.ivy_workdir, self.hash_name) @property def hardlink_classpath_filename(self): return os.path.join(self.workdir, 'classpath') @property def ivy_cache_classpath_filename(self): return '{}.raw'.format(self.hardlink_classpath_filename) @property def frozen_resolve_file(self): return os.path.join(self.workdir, 'resolution.json') @property def hardlink_dir(self): return os.path.join(self.ivy_workdir, 'jars') @abstractmethod def ivy_xml_path(self): """Ivy xml location.""" @abstractmethod def resolve_report_path(self, conf): """Location of the resolve report in the workdir.""" def _construct_and_load_hardlink_map(self): artifact_paths, hardlink_map = IvyUtils.construct_and_load_hardlink_map( self.hardlink_dir, self.ivy_repository_cache_dir, self.ivy_cache_classpath_filename, self.hardlink_classpath_filename) return artifact_paths, hardlink_map def _call_ivy(self, executor, extra_args, ivyxml, jvm_options, hash_name_for_report, workunit_factory, workunit_name): IvyUtils.do_resolve(executor, extra_args, ivyxml, jvm_options, self.workdir_reports_by_conf, self.confs, self.ivy_resolution_cache_dir, self.ivy_cache_classpath_filename, hash_name_for_report, workunit_factory, workunit_name) class IvyFetchStep(IvyResolutionStep): """Resolves ivy artifacts using the coordinates from a previous resolve.""" def required_load_files_exist(self): return (all(os.path.isfile(report) for report in self.workdir_reports_by_conf.values()) and os.path.isfile(self.ivy_cache_classpath_filename) and os.path.isfile(self.frozen_resolve_file)) def resolve_report_path(self, conf): return os.path.join(self.workdir, 'fetch-report-{}.xml'.format(conf)) @property def ivy_xml_path(self): return os.path.join(self.workdir, 'fetch-ivy.xml') def required_exec_files_exist(self): return os.path.isfile(self.frozen_resolve_file) def load(self, targets): try: frozen_resolutions = FrozenResolution.load_from_file(self.frozen_resolve_file, targets) except Exception as e: logger.debug('Failed to load {}: {}'.format(self.frozen_resolve_file, e)) return NO_RESOLVE_RUN_RESULT return self._load_from_fetch(frozen_resolutions) def exec_and_load(self, executor, extra_args, targets, jvm_options, workunit_name, workunit_factory): try: frozen_resolutions = FrozenResolution.load_from_file(self.frozen_resolve_file, targets) except Exception as e: logger.debug('Failed to load {}: {}'.format(self.frozen_resolve_file, e)) return NO_RESOLVE_RUN_RESULT self._do_fetch(executor, extra_args, frozen_resolutions, jvm_options, workunit_name, workunit_factory) result = self._load_from_fetch(frozen_resolutions) if not result.all_linked_artifacts_exist(): raise IvyResolveMappingError( 'Some artifacts were not linked to {} for {}'.format(self.ivy_workdir, result)) return result def _load_from_fetch(self, frozen_resolutions): artifact_paths, hardlink_map = self._construct_and_load_hardlink_map() return IvyFetchResolveResult(artifact_paths, hardlink_map, self.hash_name, self.workdir_reports_by_conf, frozen_resolutions) def _do_fetch(self, executor, extra_args, frozen_resolution, jvm_options, workunit_name, workunit_factory): # It's important for fetches to have a different ivy report from resolves as their # contents differ. hash_name_for_report = '{}-fetch'.format(self.hash_name) ivyxml = self.ivy_xml_path self._prepare_ivy_xml(frozen_resolution, ivyxml, hash_name_for_report) self._call_ivy(executor, extra_args, ivyxml, jvm_options, hash_name_for_report, workunit_factory, workunit_name) def _prepare_ivy_xml(self, frozen_resolution, ivyxml, resolve_hash_name_for_report): # NB(nh): Our ivy.xml ensures that we always get the default configuration, even if it's not # part of the requested confs. default_resolution = frozen_resolution.get('default') if default_resolution is None: raise IvyUtils.IvyError("Couldn't find the frozen resolution for the 'default' ivy conf.") try: jars = default_resolution.jar_dependencies IvyUtils.generate_fetch_ivy(jars, ivyxml, self.confs, resolve_hash_name_for_report) except Exception as e: raise IvyUtils.IvyError('Failed to prepare ivy resolve: {}'.format(e)) class IvyResolveStep(IvyResolutionStep): """Resolves ivy artifacts and produces a cacheable file containing the resulting coordinates.""" def required_load_files_exist(self): return (all(os.path.isfile(report) for report in self.workdir_reports_by_conf.values()) and os.path.isfile(self.ivy_cache_classpath_filename)) def resolve_report_path(self, conf): return os.path.join(self.workdir, 'resolve-report-{}.xml'.format(conf)) @property def ivy_xml_path(self): return os.path.join(self.workdir, 'resolve-ivy.xml') def load(self, targets): artifact_paths, hardlink_map = self._construct_and_load_hardlink_map() return IvyResolveResult(artifact_paths, hardlink_map, self.hash_name, self.workdir_reports_by_conf) def exec_and_load(self, executor, extra_args, targets, jvm_options, workunit_name, workunit_factory): self._do_resolve(executor, extra_args, targets, jvm_options, workunit_name, workunit_factory) result = self.load(targets) if not result.all_linked_artifacts_exist(): raise IvyResolveMappingError( 'Some artifacts were not linked to {} for {}'.format(self.ivy_workdir, result)) frozen_resolutions_by_conf = result.get_frozen_resolutions_by_conf(targets) FrozenResolution.dump_to_file(self.frozen_resolve_file, frozen_resolutions_by_conf) return result def _do_resolve(self, executor, extra_args, targets, jvm_options, workunit_name, workunit_factory): ivyxml = self.ivy_xml_path hash_name = '{}-resolve'.format(self.hash_name) self._prepare_ivy_xml(targets, ivyxml, hash_name) self._call_ivy(executor, extra_args, ivyxml, jvm_options, hash_name, workunit_factory, workunit_name) def _prepare_ivy_xml(self, targets, ivyxml, hash_name): # TODO(John Sirois): merge the code below into IvyUtils or up here; either way, better # diagnostics can be had in `IvyUtils.generate_ivy` if this is done. # See: https://github.com/pantsbuild/pants/issues/2239 jars, global_excludes = IvyUtils.calculate_classpath(targets) # Don't pass global excludes to ivy when using soft excludes. if self.soft_excludes: global_excludes = [] IvyUtils.generate_ivy(targets, jars, global_excludes, ivyxml, self.confs, hash_name, self.pinned_artifacts) class FrozenResolution(object): """Contains the abstracted results of a resolve. With this we can do a simple fetch. """ # TODO(nh): include full dependency graph in here. # So that we can inject it into the build graph if we want to. class MissingTarget(Exception): """Thrown when a loaded resolution has a target spec for a target that doesn't exist.""" def __init__(self): self.target_to_resolved_coordinates = defaultdict(OrderedSet) self.all_resolved_coordinates = OrderedSet() self.coordinate_to_attributes = OrderedDict() @property def jar_dependencies(self): return [ JarDependency(c.org, c.name, c.rev, classifier=c.classifier, ext=c.ext, **self.coordinate_to_attributes.get(c, {})) for c in self.all_resolved_coordinates] def add_resolved_jars(self, target, resolved_jars): coords = [j.coordinate for j in resolved_jars] self.add_resolution_coords(target, coords) # Assuming target is a jar library. for j in target.jar_dependencies: url = j.get_url(relative=True) if url: self.coordinate_to_attributes[j.coordinate] = {'url': url, 'base_path': j.base_path} else: self.coordinate_to_attributes[j.coordinate] = {} def add_resolution_coords(self, target, coords): for c in coords: self.target_to_resolved_coordinates[target].add(c) self.all_resolved_coordinates.add(c) def target_spec_to_coordinate_strings(self): return {t.address.spec: [str(c) for c in coordinates] for t, coordinates in self.target_to_resolved_coordinates.items()} def __repr__(self): return 'FrozenResolution(\n target_to_resolved_coordinates\n {}\n all\n {}'.format( '\n '.join(': '.join([t.address.spec, '\n '.join(str(c) for c in cs)]) for t,cs in self.target_to_resolved_coordinates.items()), '\n '.join(str(c) for c in self.coordinate_to_attributes.keys()) ) def __eq__(self, other): return (type(self) == type(other) and self.all_resolved_coordinates == other.all_resolved_coordinates and self.target_to_resolved_coordinates == other.target_to_resolved_coordinates) def __ne__(self, other): return not self == other @classmethod def load_from_file(cls, filename, targets): if not os.path.exists(filename): return None with open(filename, 'r') as f: # Using OrderedDict here to maintain insertion order of dict entries. from_file = json.load(f, object_pairs_hook=OrderedDict) result = {} target_lookup = {t.address.spec: t for t in targets} for conf, serialized_resolution in from_file.items(): resolution = FrozenResolution() def m2_for(c): return M2Coordinate.from_string(c) for coord, attr_dict in serialized_resolution['coord_to_attrs'].items(): m2 = m2_for(coord) resolution.coordinate_to_attributes[m2] = attr_dict for spec, coord_strs in serialized_resolution['target_to_coords'].items(): t = target_lookup.get(spec, None) if t is None: raise cls.MissingTarget('Cannot find target for address {} in frozen resolution' .format(spec)) resolution.add_resolution_coords(t, [m2_for(c) for c in coord_strs]) result[conf] = resolution return result @classmethod def dump_to_file(cls, filename, resolutions_by_conf): res = {} for conf, resolution in resolutions_by_conf.items(): res[conf] = OrderedDict([ ['target_to_coords',resolution.target_spec_to_coordinate_strings()], ['coord_to_attrs', OrderedDict([str(c), attrs] for c, attrs in resolution.coordinate_to_attributes.items())] ]) with safe_concurrent_creation(filename) as tmp_filename: mode = 'w' if PY3 else 'wb' with open(tmp_filename, mode) as f: json.dump(res, f) class IvyResolveResult(object): """The result of an Ivy resolution. The result data includes the list of resolved artifacts, the relationships between those artifacts and the targets that requested them and the hash name of the resolve. """ def __init__(self, resolved_artifact_paths, hardlink_map, resolve_hash_name, reports_by_conf): self._reports_by_conf = reports_by_conf self.resolved_artifact_paths = resolved_artifact_paths self.resolve_hash_name = resolve_hash_name self._hardlink_map = hardlink_map @property def has_resolved_artifacts(self): """The requested targets have a resolution associated with them.""" return self.resolve_hash_name is not None def all_linked_artifacts_exist(self): """All of the artifact paths for this resolve point to existing files.""" if not self.has_resolved_artifacts: return False for path in self.resolved_artifact_paths: if not os.path.isfile(path): return False else: return True def report_for_conf(self, conf): """Returns the path to the ivy report for the provided conf. Returns None if there is no path. """ return self._reports_by_conf.get(conf) def get_frozen_resolutions_by_conf(self, targets): frozen_resolutions_by_conf = OrderedDict() for conf in self._reports_by_conf: frozen_resolution = FrozenResolution() for target, resolved_jars in self.resolved_jars_for_each_target(conf, targets): frozen_resolution.add_resolved_jars(target, resolved_jars) frozen_resolutions_by_conf[conf] = frozen_resolution return frozen_resolutions_by_conf def resolved_jars_for_each_target(self, conf, targets): """Yields the resolved jars for each passed JarLibrary. If there is no report for the requested conf, yields nothing. :param conf: The ivy conf to load jars for. :param targets: The collection of JarLibrary targets to find resolved jars for. :yield: target, resolved_jars :raises IvyTaskMixin.UnresolvedJarError """ ivy_info = self._ivy_info_for(conf) if not ivy_info: return jar_library_targets = [t for t in targets if isinstance(t, JarLibrary)] ivy_jar_memo = {} for target in jar_library_targets: # Add the artifacts from each dependency module. resolved_jars = self._resolved_jars_with_hardlinks(conf, ivy_info, ivy_jar_memo, self._jar_dependencies_for_target(conf, target), target) yield target, resolved_jars def _jar_dependencies_for_target(self, conf, target): return target.jar_dependencies def _ivy_info_for(self, conf): report_path = self._reports_by_conf.get(conf) return IvyUtils.parse_xml_report(conf, report_path) def _new_resolved_jar_with_hardlink_path(self, conf, target, resolved_jar_without_hardlink): def candidate_cache_paths(): # There is a focus on being lazy here to avoid `os.path.realpath` when we can. yield resolved_jar_without_hardlink.cache_path yield os.path.realpath(resolved_jar_without_hardlink.cache_path) for cache_path in candidate_cache_paths(): pants_path = self._hardlink_map.get(cache_path) if pants_path: break else: raise IvyResolveMappingError( 'Jar {resolved_jar} in {spec} not resolved to the ivy ' 'hardlink map in conf {conf}.' .format(spec=target.address.spec, resolved_jar=resolved_jar_without_hardlink.cache_path, conf=conf)) return ResolvedJar(coordinate=resolved_jar_without_hardlink.coordinate, pants_path=pants_path, cache_path=resolved_jar_without_hardlink.cache_path) def _resolved_jars_with_hardlinks(self, conf, ivy_info, ivy_jar_memo, coordinates, target): raw_resolved_jars = ivy_info.get_resolved_jars_for_coordinates(coordinates, memo=ivy_jar_memo) resolved_jars = [self._new_resolved_jar_with_hardlink_path(conf, target, raw_resolved_jar) for raw_resolved_jar in raw_resolved_jars] return resolved_jars class IvyFetchResolveResult(IvyResolveResult): """A resolve result that uses the frozen resolution to look up dependencies.""" def __init__(self, resolved_artifact_paths, hardlink_map, resolve_hash_name, reports_by_conf, frozen_resolutions): super(IvyFetchResolveResult, self).__init__(resolved_artifact_paths, hardlink_map, resolve_hash_name, reports_by_conf) self._frozen_resolutions = frozen_resolutions def _jar_dependencies_for_target(self, conf, target): return self._frozen_resolutions[conf].target_to_resolved_coordinates.get(target, ()) NO_RESOLVE_RUN_RESULT = IvyResolveResult([], {}, None, {}) IvyModule = namedtuple('IvyModule', ['ref', 'artifact', 'callers']) Dependency = namedtuple('DependencyAttributes', ['org', 'name', 'rev', 'mutable', 'force', 'transitive']) Artifact = namedtuple('Artifact', ['name', 'type_', 'ext', 'url', 'classifier']) logger = logging.getLogger(__name__) class IvyResolveMappingError(Exception): """Raised when there is a failure mapping the ivy resolve results to pants objects.""" @total_ordering class IvyModuleRef(object): """ :API: public """ # latest.integration is ivy magic meaning "just get the latest version" _ANY_REV = 'latest.integration' def __init__(self, org, name, rev, classifier=None, ext=None): self.org = org self.name = name self.rev = rev self.classifier = classifier self.ext = ext or 'jar' self._id = (self.org, self.name, self.rev, self.classifier, self.ext) def __eq__(self, other): return isinstance(other, IvyModuleRef) and self._id == other._id # TODO(#6071): Return NotImplemented if other does not have attributes def __lt__(self, other): # We can't just re-use __repr__ or __str_ because we want to order rev last return ((self.org, self.name, self.classifier or '', self.ext, self.rev) < (other.org, other.name, other.classifier or '', other.ext, other.rev)) def __hash__(self): return hash(self._id) def __str__(self): return 'IvyModuleRef({})'.format(':'.join((x or '') for x in self._id)) def __repr__(self): return ('IvyModuleRef(org={!r}, name={!r}, rev={!r}, classifier={!r}, ext={!r})' .format(*self._id)) @property def caller_key(self): """This returns an identifier for an IvyModuleRef that only retains the caller org and name. Ivy represents dependees as `<caller/>`'s with just org and name and rev information. This method returns a `<caller/>` representation of the current ref. """ return IvyModuleRef(name=self.name, org=self.org, rev=self._ANY_REV) @property def unversioned(self): """This returns an identifier for an IvyModuleRef without version information. It's useful because ivy might return information about a different version of a dependency than the one we request, and we want to ensure that all requesters of any version of that dependency are able to learn about it. """ return IvyModuleRef(name=self.name, org=self.org, rev=self._ANY_REV, classifier=self.classifier, ext=self.ext) class IvyInfo(object): """ :API: public """ def __init__(self, conf): self._conf = conf self.modules_by_ref = {} # Map from ref to referenced module. self.refs_by_unversioned_refs = {} # Map from unversioned ref to the resolved versioned ref # Map from ref of caller to refs of modules required by that caller. self._deps_by_caller = defaultdict(OrderedSet) # Map from _unversioned_ ref to OrderedSet of IvyArtifact instances. self._artifacts_by_ref = defaultdict(OrderedSet) def add_module(self, module): if not module.artifact: # Module was evicted, so do not record information about it return ref_unversioned = module.ref.unversioned if ref_unversioned in self.refs_by_unversioned_refs: raise IvyResolveMappingError('Already defined module {}, as rev {}!' .format(ref_unversioned, module.ref.rev)) if module.ref in self.modules_by_ref: raise IvyResolveMappingError('Already defined module {}, would be overwritten!' .format(module.ref)) self.refs_by_unversioned_refs[ref_unversioned] = module.ref self.modules_by_ref[module.ref] = module for caller in module.callers: self._deps_by_caller[caller.caller_key].add(module.ref) self._artifacts_by_ref[ref_unversioned].add(module.artifact) def _do_traverse_dependency_graph(self, ref, collector, memo, visited): memoized_value = memo.get(ref) if memoized_value: return memoized_value if ref in visited: # Ivy allows for circular dependencies # If we're here, that means we're resolving something that # transitively depends on itself return set() visited.add(ref) acc = collector(ref) # NB(zundel): ivy does not return deps in a consistent order for the same module for # different resolves. Sort them to get consistency and prevent cache invalidation. # See https://github.com/pantsbuild/pants/issues/2607 deps = sorted(self._deps_by_caller.get(ref.caller_key, ())) for dep in deps: acc.update(self._do_traverse_dependency_graph(dep, collector, memo, visited)) memo[ref] = acc return acc def traverse_dependency_graph(self, ref, collector, memo=None): """Traverses module graph, starting with ref, collecting values for each ref into the sets created by the collector function. :param ref an IvyModuleRef to start traversing the ivy dependency graph :param collector a function that takes a ref and returns a new set of values to collect for that ref, which will also be updated with all the dependencies accumulated values :param memo is a dict of ref -> set that memoizes the results of each node in the graph. If provided, allows for retaining cache across calls. :returns the accumulated set for ref """ resolved_ref = self.refs_by_unversioned_refs.get(ref.unversioned) if resolved_ref: ref = resolved_ref if memo is None: memo = dict() visited = set() return self._do_traverse_dependency_graph(ref, collector, memo, visited) def get_resolved_jars_for_coordinates(self, coordinates, memo=None): """Collects jars for the passed coordinates. Because artifacts are only fetched for the "winning" version of a module, the artifacts will not always represent the version originally declared by the library. This method is transitive within the passed coordinates dependencies. :param coordinates collections.Iterable: Collection of coordinates to collect transitive resolved jars for. :param memo: See `traverse_dependency_graph`. :returns: All the artifacts for all of the jars for the provided coordinates, including transitive dependencies. :rtype: list of :class:`pants.java.jar.ResolvedJar` """ def to_resolved_jar(jar_ref, jar_path): return ResolvedJar(coordinate=M2Coordinate(org=jar_ref.org, name=jar_ref.name, rev=jar_ref.rev, classifier=jar_ref.classifier, ext=jar_ref.ext), cache_path=jar_path) resolved_jars = OrderedSet() def create_collection(dep): return OrderedSet([dep]) for jar in coordinates: classifier = jar.classifier if self._conf == 'default' else self._conf jar_module_ref = IvyModuleRef(jar.org, jar.name, jar.rev, classifier, jar.ext) for module_ref in self.traverse_dependency_graph(jar_module_ref, create_collection, memo): for artifact_path in self._artifacts_by_ref[module_ref.unversioned]: resolved_jars.add(to_resolved_jar(module_ref, artifact_path)) return resolved_jars def __repr__(self): return 'IvyInfo(conf={}, refs={})'.format(self._conf, self.modules_by_ref.keys()) class IvyUtils(object): """Useful methods related to interaction with ivy. :API: public """ # Protects ivy executions. _ivy_lock = threading.RLock() # Protect writes to the global map of jar path -> hardlinks to that jar. _hardlink_map_lock = threading.Lock() INTERNAL_ORG_NAME = 'internal' class IvyError(Exception): """Indicates an error preparing an ivy operation.""" class IvyResolveReportError(IvyError): """Indicates that an ivy report cannot be found.""" class IvyResolveConflictingDepsError(IvyError): """Indicates two or more locally declared dependencies conflict.""" class BadRevisionError(IvyError): """Indicates an unparseable version number.""" @staticmethod def _generate_exclude_template(exclude): return TemplateData(org=exclude.org, name=exclude.name) @staticmethod def _generate_override_template(jar): return TemplateData(org=jar.org, module=jar.name, version=jar.rev) @staticmethod def _load_classpath_from_cachepath(path): if not os.path.exists(path): return [] else: with safe_open(path, 'r') as cp: return [_f for _f in (path.strip() for path in cp.read().split(os.pathsep)) if _f] @classmethod def do_resolve(cls, executor, extra_args, ivyxml, jvm_options, workdir_report_paths_by_conf, confs, ivy_resolution_cache_dir, ivy_cache_classpath_filename, resolve_hash_name, workunit_factory, workunit_name): """Execute Ivy with the given ivy.xml and copies all relevant files into the workdir. This method does an Ivy resolve, which may be either a Pants resolve or a Pants fetch depending on whether there is an existing frozen resolution. After it is run, the Ivy reports are copied into the workdir at the paths specified by workdir_report_paths_by_conf along with a file containing a list of all the requested artifacts and their transitive dependencies. :param executor: A JVM executor to use to invoke ivy. :param extra_args: Extra arguments to pass to ivy. :param ivyxml: The input ivy.xml containing the dependencies to resolve. :param jvm_options: A list of jvm option strings to use for the ivy invoke, or None. :param workdir_report_paths_by_conf: A dict mapping confs to report paths in the workdir. :param confs: The confs used in the resolve. :param resolve_hash_name: The hash to use as the module name for finding the ivy report file. :param workunit_factory: A workunit factory for the ivy invoke, or None. :param workunit_name: A workunit name for the ivy invoke, or None. """ ivy = Bootstrapper.default_ivy(bootstrap_workunit_factory=workunit_factory) with safe_concurrent_creation(ivy_cache_classpath_filename) as raw_target_classpath_file_tmp: extra_args = extra_args or [] args = ['-cachepath', raw_target_classpath_file_tmp] + extra_args with cls._ivy_lock: cls._exec_ivy(ivy, confs, ivyxml, args, jvm_options=jvm_options, executor=executor, workunit_name=workunit_name, workunit_factory=workunit_factory) if not os.path.exists(raw_target_classpath_file_tmp): raise cls.IvyError('Ivy failed to create classpath file at {}' .format(raw_target_classpath_file_tmp)) cls._copy_ivy_reports(workdir_report_paths_by_conf, confs, ivy_resolution_cache_dir, resolve_hash_name) logger.debug('Moved ivy classfile file to {dest}' .format(dest=ivy_cache_classpath_filename)) @classmethod def _copy_ivy_reports(cls, workdir_report_paths_by_conf, confs, ivy_resolution_cache_dir, resolve_hash_name): for conf in confs: ivy_cache_report_path = IvyUtils.xml_report_path(ivy_resolution_cache_dir, resolve_hash_name, conf) workdir_report_path = workdir_report_paths_by_conf[conf] try: atomic_copy(ivy_cache_report_path, workdir_report_path) except IOError as e: raise cls.IvyError('Failed to copy report into workdir from {} to {}: {}' .format(ivy_cache_report_path, workdir_report_path, e)) @classmethod def _exec_ivy(cls, ivy, confs, ivyxml, args, jvm_options, executor, workunit_name, workunit_factory): ivy = ivy or Bootstrapper.default_ivy() ivy_args = ['-ivy', ivyxml] ivy_args.append('-confs') ivy_args.extend(confs) ivy_args.extend(args) ivy_jvm_options = list(jvm_options) # Disable cache in File.getCanonicalPath(), makes Ivy work with -symlink option properly on ng. ivy_jvm_options.append('-Dsun.io.useCanonCaches=false') runner = ivy.runner(jvm_options=ivy_jvm_options, args=ivy_args, executor=executor) try: with ivy.resolution_lock: result = execute_runner(runner, workunit_factory=workunit_factory, workunit_name=workunit_name) if result != 0: raise IvyUtils.IvyError('Ivy returned {result}. cmd={cmd}'.format(result=result, cmd=runner.cmd)) except runner.executor.Error as e: raise IvyUtils.IvyError(e) @classmethod def construct_and_load_hardlink_map(cls, hardlink_dir, ivy_repository_cache_dir, ivy_cache_classpath_filename, hardlink_classpath_filename): # Make our actual classpath be hardlinks, so that the paths are uniform across systems. # Note that we must do this even if we read the raw_target_classpath_file from the artifact # cache. If we cache the target_classpath_file we won't know how to create the hardlinks. with IvyUtils._hardlink_map_lock: # A common dir for hardlinks into the ivy2 cache. This ensures that paths to jars # in artifact-cached analysis files are consistent across systems. # Note that we have one global, well-known hardlink dir, again so that paths are # consistent across builds. hardlink_map = cls._hardlink_cachepath(ivy_repository_cache_dir, ivy_cache_classpath_filename, hardlink_dir, hardlink_classpath_filename) classpath = cls._load_classpath_from_cachepath(hardlink_classpath_filename) return classpath, hardlink_map @classmethod def _hardlink_cachepath(cls, ivy_repository_cache_dir, inpath, hardlink_dir, outpath): """hardlinks all paths listed in inpath that are under ivy_repository_cache_dir into hardlink_dir. If there is an existing hardlink for a file under inpath, it is used rather than creating a new hardlink. Preserves all other paths. Writes the resulting paths to outpath. Returns a map of path -> hardlink to that path. """ safe_mkdir(hardlink_dir) # The ivy_repository_cache_dir might itself be a hardlink. In this case, ivy may return paths that # reference the realpath of the .jar file after it is resolved in the cache dir. To handle # this case, add both the hardlink'ed path and the realpath to the jar to the hardlink map. real_ivy_cache_dir = os.path.realpath(ivy_repository_cache_dir) hardlink_map = OrderedDict() inpaths = cls._load_classpath_from_cachepath(inpath) paths = OrderedSet([os.path.realpath(path) for path in inpaths]) for path in paths: if path.startswith(real_ivy_cache_dir): hardlink_map[path] = os.path.join(hardlink_dir, os.path.relpath(path, real_ivy_cache_dir)) else: # This path is outside the cache. We won't hardlink it. hardlink_map[path] = path # Create hardlinks for paths in the ivy cache dir. for path, hardlink in six.iteritems(hardlink_map): if path == hardlink: # Skip paths that aren't going to be hardlinked. continue safe_mkdir(os.path.dirname(hardlink)) safe_hardlink_or_copy(path, hardlink) # (re)create the classpath with all of the paths with safe_open(outpath, 'w') as outfile: outfile.write(':'.join(OrderedSet(hardlink_map.values()))) return dict(hardlink_map) @classmethod def xml_report_path(cls, resolution_cache_dir, resolve_hash_name, conf): """The path to the xml report ivy creates after a retrieve. :API: public :param string cache_dir: The path of the ivy cache dir used for resolves. :param string resolve_hash_name: Hash from the Cache key from the VersionedTargetSet used for resolution. :param string conf: The ivy conf name (e.g. "default"). :returns: The report path. :rtype: string """ return os.path.join(resolution_cache_dir, '{}-{}-{}.xml'.format(IvyUtils.INTERNAL_ORG_NAME, resolve_hash_name, conf)) @classmethod def parse_xml_report(cls, conf, path): """Parse the ivy xml report corresponding to the name passed to ivy. :API: public :param string conf: the ivy conf name (e.g. "default") :param string path: The path to the ivy report file. :returns: The info in the xml report. :rtype: :class:`IvyInfo` :raises: :class:`IvyResolveMappingError` if no report exists. """ if not os.path.exists(path): raise cls.IvyResolveReportError('Missing expected ivy output file {}'.format(path)) logger.debug("Parsing ivy report {}".format(path)) ret = IvyInfo(conf) etree = ET.parse(path) doc = etree.getroot() for module in doc.findall('dependencies/module'): org = module.get('organisation') name = module.get('name') for revision in module.findall('revision'): rev = revision.get('name') callers = [] for caller in revision.findall('caller'): callers.append(IvyModuleRef(caller.get('organisation'), caller.get('name'), caller.get('callerrev'))) for artifact in revision.findall('artifacts/artifact'): classifier = artifact.get('extra-classifier') ext = artifact.get('ext') ivy_module_ref = IvyModuleRef(org=org, name=name, rev=rev, classifier=classifier, ext=ext) artifact_cache_path = artifact.get('location') ivy_module = IvyModule(ivy_module_ref, artifact_cache_path, tuple(callers)) ret.add_module(ivy_module) return ret @classmethod def generate_ivy(cls, targets, jars, excludes, ivyxml, confs, resolve_hash_name=None, pinned_artifacts=None, jar_dep_manager=None): if not resolve_hash_name: resolve_hash_name = Target.maybe_readable_identify(targets) return cls._generate_resolve_ivy(jars, excludes, ivyxml, confs, resolve_hash_name, pinned_artifacts, jar_dep_manager) @classmethod def _generate_resolve_ivy(cls, jars, excludes, ivyxml, confs, resolve_hash_name, pinned_artifacts=None, jar_dep_manager=None): org = IvyUtils.INTERNAL_ORG_NAME name = resolve_hash_name extra_configurations = [conf for conf in confs if conf and conf != 'default'] jars_by_key = OrderedDict() for jar in jars: jars = jars_by_key.setdefault((jar.org, jar.name), []) jars.append(jar) manager = jar_dep_manager or JarDependencyManagement.global_instance() artifact_set = PinnedJarArtifactSet(pinned_artifacts) # Copy, because we're modifying it. for jars in jars_by_key.values(): for i, dep in enumerate(jars): direct_coord = M2Coordinate.create(dep) managed_coord = artifact_set[direct_coord] if direct_coord.rev != managed_coord.rev: # It may be necessary to actually change the version number of the jar we want to resolve # here, because overrides do not apply directly (they are exclusively transitive). This is # actually a good thing, because it gives us more control over what happens. coord = manager.resolve_version_conflict(managed_coord, direct_coord, force=dep.force) jars[i] = dep.copy(rev=coord.rev) elif dep.force: # If this dependency is marked as 'force' and there is no version conflict, use the normal # pants behavior for 'force'. artifact_set.put(direct_coord) dependencies = [cls._generate_jar_template(jars) for jars in jars_by_key.values()] # As it turns out force is not transitive - it only works for dependencies pants knows about # directly (declared in BUILD files - present in generated ivy.xml). The user-level ivy docs # don't make this clear [1], but the source code docs do (see isForce docs) [2]. I was able to # edit the generated ivy.xml and use the override feature [3] though and that does work # transitively as you'd hope. # # [1] http://ant.apache.org/ivy/history/2.3.0/settings/conflict-managers.html # [2] https://svn.apache.org/repos/asf/ant/ivy/core/branches/2.3.0/ # src/java/org/apache/ivy/core/module/descriptor/DependencyDescriptor.java # [3] http://ant.apache.org/ivy/history/2.3.0/ivyfile/override.html overrides = [cls._generate_override_template(_coord) for _coord in artifact_set] excludes = [cls._generate_exclude_template(exclude) for exclude in excludes] template_data = TemplateData( org=org, module=name, extra_configurations=extra_configurations, dependencies=dependencies, excludes=excludes, overrides=overrides) template_relpath = os.path.join('templates', 'ivy_utils', 'ivy.xml.mustache') cls._write_ivy_xml_file(ivyxml, template_data, template_relpath) @classmethod def generate_fetch_ivy(cls, jars, ivyxml, confs, resolve_hash_name): """Generates an ivy xml with all jars marked as intransitive using the all conflict manager.""" org = IvyUtils.INTERNAL_ORG_NAME name = resolve_hash_name extra_configurations = [conf for conf in confs if conf and conf != 'default'] # Use org name _and_ rev so that we can have dependencies with different versions. This will # allow for batching fetching if we want to do that. jars_by_key = OrderedDict() for jar in jars: jars_by_key.setdefault((jar.org, jar.name, jar.rev), []).append(jar) dependencies = [cls._generate_fetch_jar_template(_jars) for _jars in jars_by_key.values()] template_data = TemplateData(org=org, module=name, extra_configurations=extra_configurations, dependencies=dependencies) template_relpath = os.path.join('templates', 'ivy_utils', 'ivy_fetch.xml.mustache') cls._write_ivy_xml_file(ivyxml, template_data, template_relpath) @classmethod def _write_ivy_xml_file(cls, ivyxml, template_data, template_relpath): template_text = pkgutil.get_data(__name__, template_relpath).decode('utf-8') generator = Generator(template_text, lib=template_data) with safe_open(ivyxml, 'w') as output: generator.write(output) @classmethod def calculate_classpath(cls, targets): """Creates a consistent classpath and list of excludes for the passed targets. It also modifies the JarDependency objects' excludes to contain all the jars excluded by provides. :param iterable targets: List of targets to collect JarDependencies and excludes from. :returns: A pair of a list of JarDependencies, and a set of excludes to apply globally. """ jars = OrderedDict() global_excludes = set() provide_excludes = set() targets_processed = set() # Support the ivy force concept when we sanely can for internal dep conflicts. # TODO(John Sirois): Consider supporting / implementing the configured ivy revision picking # strategy generally. def add_jar(jar): # TODO(John Sirois): Maven allows for depending on an artifact at one rev and one of its # attachments (classified artifacts) at another. Ivy does not, allow this, the dependency # can carry only 1 rev and that hosts multiple artifacts for that rev. This conflict # resolution happens at the classifier level, allowing skew in a # multi-artifact/multi-classifier dependency. We only find out about the skew later in # `_generate_jar_template` below which will blow up with a conflict. Move this logic closer # together to get a more clear validate, then emit ivy.xml then resolve flow instead of the # spread-out validations happening here. # See: https://github.com/pantsbuild/pants/issues/2239 coordinate = (jar.org, jar.name, jar.classifier) existing = jars.get(coordinate) jars[coordinate] = jar if not existing else cls._resolve_conflict(existing=existing, proposed=jar) def collect_jars(target): if isinstance(target, JarLibrary): for jar in target.jar_dependencies: add_jar(jar) def collect_excludes(target): target_excludes = target.payload.get_field_value('excludes') if target_excludes: global_excludes.update(target_excludes) def collect_provide_excludes(target): if not (isinstance(target, ExportableJvmLibrary) and target.provides): return logger.debug('Automatically excluding jar {}.{}, which is provided by {}'.format( target.provides.org, target.provides.name, target)) provide_excludes.add(Exclude(org=target.provides.org, name=target.provides.name)) def collect_elements(target): targets_processed.add(target) collect_jars(target) collect_excludes(target) collect_provide_excludes(target) for target in targets: target.walk(collect_elements, predicate=lambda target: target not in targets_processed) # If a source dep is exported (ie, has a provides clause), it should always override # remote/binary versions of itself, ie "round trip" dependencies. # TODO: Move back to applying provides excludes as target-level excludes when they are no # longer global. if provide_excludes: additional_excludes = tuple(provide_excludes) new_jars = OrderedDict() for coordinate, jar in jars.items(): new_jars[coordinate] = jar.copy(excludes=jar.excludes + additional_excludes) jars = new_jars return list(jars.values()), global_excludes @classmethod def _resolve_conflict(cls, existing, proposed): if existing.rev is None: return proposed if proposed.rev is None: return existing if proposed == existing: if proposed.force: return proposed return existing elif existing.force and proposed.force: raise cls.IvyResolveConflictingDepsError('Cannot force {}#{};{} to both rev {} and {}'.format( proposed.org, proposed.name, proposed.classifier or '', existing.rev, proposed.rev )) elif existing.force: logger.debug('Ignoring rev {} for {}#{};{} already forced to {}'.format( proposed.rev, proposed.org, proposed.name, proposed.classifier or '', existing.rev )) return existing elif proposed.force: logger.debug('Forcing {}#{};{} from {} to {}'.format( proposed.org, proposed.name, proposed.classifier or '', existing.rev, proposed.rev )) return proposed else: if Revision.lenient(proposed.rev) > Revision.lenient(existing.rev): logger.debug('Upgrading {}#{};{} from rev {} to {}'.format( proposed.org, proposed.name, proposed.classifier or '', existing.rev, proposed.rev, )) return proposed else: return existing @classmethod def _generate_jar_template(cls, jars): global_dep_attributes = set(Dependency(org=jar.org, name=jar.name, rev=jar.rev, mutable=jar.mutable, force=jar.force, transitive=jar.transitive) for jar in jars) if len(global_dep_attributes) != 1: # TODO: Need to provide information about where these came from - could be # far-flung JarLibrary targets. The jars here were collected from targets via # `calculate_classpath` above so executing this step there instead may make more # sense. conflicting_dependencies = sorted(str(g) for g in global_dep_attributes) raise cls.IvyResolveConflictingDepsError('Found conflicting dependencies:\n\t{}' .format('\n\t'.join(conflicting_dependencies))) jar_attributes = global_dep_attributes.pop() excludes = set() for jar in jars: excludes.update(jar.excludes) any_have_url = False artifacts = OrderedDict() for jar in jars: ext = jar.ext url = jar.get_url() if url: any_have_url = True classifier = jar.classifier artifact = Artifact(name=jar.name, type_=ext or 'jar', ext=ext, url=url, classifier=classifier) artifacts[(ext, url, classifier)] = artifact template = TemplateData( org=jar_attributes.org, module=jar_attributes.name, version=jar_attributes.rev, mutable=jar_attributes.mutable, force=jar_attributes.force, transitive=jar_attributes.transitive, artifacts=list(artifacts.values()), any_have_url=any_have_url, excludes=[cls._generate_exclude_template(exclude) for exclude in excludes]) return template @classmethod def _generate_fetch_jar_template(cls, jars): global_dep_attributes = set(Dependency(org=jar.org, name=jar.name, rev=jar.rev, transitive=False, mutable=jar.mutable, force=True) for jar in jars) if len(global_dep_attributes) != 1: # If we batch fetches and assume conflict manager all, we could ignore these. # Leaving this here for now. conflicting_dependencies = sorted(str(g) for g in global_dep_attributes) raise cls.IvyResolveConflictingDepsError('Found conflicting dependencies:\n\t{}' .format('\n\t'.join(conflicting_dependencies))) jar_attributes = global_dep_attributes.pop() any_have_url = False artifacts = OrderedDict() for jar in jars: ext = jar.ext url = jar.get_url() if url: any_have_url = True classifier = jar.classifier artifact = Artifact(name=jar.name, type_=ext or 'jar', ext=ext, url=url, classifier=classifier) artifacts[(ext, url, classifier)] = artifact template = TemplateData( org=jar_attributes.org, module=jar_attributes.name, version=jar_attributes.rev, mutable=jar_attributes.mutable, artifacts=list(artifacts.values()), any_have_url=any_have_url, excludes=[]) return template
twitter/pants
src/python/pants/backend/jvm/ivy_utils.py
Python
apache-2.0
51,293
CleverTaxes =========== A step forward to Democracy
florent-andre/CleverTaxes
README.md
Markdown
apache-2.0
53
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cassandra.db; import java.io.File; import java.io.IOError; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.util.*; import java.util.concurrent.ExecutionException; import org.apache.commons.lang3.StringUtils; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.apache.cassandra.OrderedJUnit4ClassRunner; import org.apache.cassandra.SchemaLoader; import org.apache.cassandra.UpdateBuilder; import org.apache.cassandra.Util; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.Operator; import org.apache.cassandra.cql3.QueryProcessor; import org.apache.cassandra.cql3.UntypedResultSet; import org.apache.cassandra.db.compaction.CompactionManager; import org.apache.cassandra.db.compaction.OperationType; import org.apache.cassandra.db.compaction.Scrubber; import org.apache.cassandra.db.lifecycle.LifecycleTransaction; import org.apache.cassandra.db.lifecycle.TransactionLog; import org.apache.cassandra.db.marshal.*; import org.apache.cassandra.db.marshal.UUIDType; import org.apache.cassandra.db.partitions.Partition; import org.apache.cassandra.db.partitions.PartitionUpdate; import org.apache.cassandra.dht.ByteOrderedPartitioner; import org.apache.cassandra.dht.IPartitioner; import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.RequestExecutionException; import org.apache.cassandra.exceptions.WriteTimeoutException; import org.apache.cassandra.io.compress.CompressionMetadata; import org.apache.cassandra.io.sstable.*; import org.apache.cassandra.io.sstable.format.SSTableReader; import org.apache.cassandra.io.util.FileUtils; import org.apache.cassandra.schema.KeyspaceParams; import org.apache.cassandra.utils.ByteBufferUtil; import static org.junit.Assert.*; import static org.junit.Assume.assumeTrue; @RunWith(OrderedJUnit4ClassRunner.class) public class ScrubTest { public static final String KEYSPACE = "Keyspace1"; public static final String CF = "Standard1"; public static final String CF2 = "Standard2"; public static final String CF3 = "Standard3"; public static final String COUNTER_CF = "Counter1"; public static final String CF_UUID = "UUIDKeys"; public static final String CF_INDEX1 = "Indexed1"; public static final String CF_INDEX2 = "Indexed2"; public static final String CF_INDEX1_BYTEORDERED = "Indexed1_ordered"; public static final String CF_INDEX2_BYTEORDERED = "Indexed2_ordered"; public static final String COL_INDEX = "birthdate"; public static final String COL_NON_INDEX = "notbirthdate"; public static final Integer COMPRESSION_CHUNK_LENGTH = 4096; @BeforeClass public static void defineSchema() throws ConfigurationException { SchemaLoader.loadSchema(); SchemaLoader.createKeyspace(KEYSPACE, KeyspaceParams.simple(1), SchemaLoader.standardCFMD(KEYSPACE, CF), SchemaLoader.standardCFMD(KEYSPACE, CF2), SchemaLoader.standardCFMD(KEYSPACE, CF3), SchemaLoader.counterCFMD(KEYSPACE, COUNTER_CF) .compression(SchemaLoader.getCompressionParameters(COMPRESSION_CHUNK_LENGTH)), SchemaLoader.standardCFMD(KEYSPACE, CF_UUID, 0, UUIDType.instance), SchemaLoader.keysIndexCFMD(KEYSPACE, CF_INDEX1, true), SchemaLoader.compositeIndexCFMD(KEYSPACE, CF_INDEX2, true), SchemaLoader.keysIndexCFMD(KEYSPACE, CF_INDEX1_BYTEORDERED, true).copy(ByteOrderedPartitioner.instance), SchemaLoader.compositeIndexCFMD(KEYSPACE, CF_INDEX2_BYTEORDERED, true).copy(ByteOrderedPartitioner.instance)); } @Test public void testScrubOneRow() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF); cfs.clearUnsafe(); // insert data and verify we get it back w/ range query fillCF(cfs, 1); assertOrderedAll(cfs, 1); CompactionManager.instance.performScrub(cfs, false, true); // check data is still there assertOrderedAll(cfs, 1); } @Test public void testScrubCorruptedCounterRow() throws IOException, WriteTimeoutException { // When compression is enabled, for testing corrupted chunks we need enough partitions to cover // at least 3 chunks of size COMPRESSION_CHUNK_LENGTH int numPartitions = 1000; CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF); cfs.clearUnsafe(); fillCounterCF(cfs, numPartitions); assertOrderedAll(cfs, numPartitions); assertEquals(1, cfs.getLiveSSTables().size()); SSTableReader sstable = cfs.getLiveSSTables().iterator().next(); //make sure to override at most 1 chunk when compression is enabled overrideWithGarbage(sstable, ByteBufferUtil.bytes("0"), ByteBufferUtil.bytes("1")); // with skipCorrupted == false, the scrub is expected to fail try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB); Scrubber scrubber = new Scrubber(cfs, txn, false, false, true)) { scrubber.scrub(); fail("Expected a CorruptSSTableException to be thrown"); } catch (IOError err) {} // with skipCorrupted == true, the corrupt rows will be skipped Scrubber.ScrubResult scrubResult; try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB); Scrubber scrubber = new Scrubber(cfs, txn, true, false, true)) { scrubResult = scrubber.scrubWithResult(); } assertNotNull(scrubResult); boolean compression = Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false")); if (compression) { assertEquals(0, scrubResult.emptyRows); assertEquals(numPartitions, scrubResult.badRows + scrubResult.goodRows); //because we only corrupted 1 chunk and we chose enough partitions to cover at least 3 chunks assertTrue(scrubResult.goodRows >= scrubResult.badRows * 2); } else { assertEquals(0, scrubResult.emptyRows); assertEquals(1, scrubResult.badRows); assertEquals(numPartitions-1, scrubResult.goodRows); } assertEquals(1, cfs.getLiveSSTables().size()); assertOrderedAll(cfs, scrubResult.goodRows); } @Test public void testScrubCorruptedRowInSmallFile() throws IOException, WriteTimeoutException { // cannot test this with compression assumeTrue(!Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false"))); CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(COUNTER_CF); cfs.clearUnsafe(); fillCounterCF(cfs, 2); assertOrderedAll(cfs, 2); SSTableReader sstable = cfs.getLiveSSTables().iterator().next(); // overwrite one row with garbage overrideWithGarbage(sstable, ByteBufferUtil.bytes("0"), ByteBufferUtil.bytes("1")); // with skipCorrupted == false, the scrub is expected to fail try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB); Scrubber scrubber = new Scrubber(cfs, txn, false, false, true)) { // with skipCorrupted == true, the corrupt row will be skipped scrubber.scrub(); fail("Expected a CorruptSSTableException to be thrown"); } catch (IOError err) {} try (LifecycleTransaction txn = cfs.getTracker().tryModify(Arrays.asList(sstable), OperationType.SCRUB); Scrubber scrubber = new Scrubber(cfs, txn, true, false, true)) { // with skipCorrupted == true, the corrupt row will be skipped scrubber.scrub(); scrubber.close(); } assertEquals(1, cfs.getLiveSSTables().size()); // verify that we can read all of the rows, and there is now one less row assertOrderedAll(cfs, 1); } @Test public void testScrubOneRowWithCorruptedKey() throws IOException, ExecutionException, InterruptedException, ConfigurationException { // cannot test this with compression assumeTrue(!Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false"))); CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF); cfs.clearUnsafe(); // insert data and verify we get it back w/ range query fillCF(cfs, 4); assertOrderedAll(cfs, 4); SSTableReader sstable = cfs.getLiveSSTables().iterator().next(); overrideWithGarbage(sstable, 0, 2); CompactionManager.instance.performScrub(cfs, false, true); // check data is still there assertOrderedAll(cfs, 4); } @Test public void testScrubCorruptedCounterRowNoEarlyOpen() throws IOException, WriteTimeoutException { boolean oldDisabledVal = SSTableRewriter.disableEarlyOpeningForTests; try { SSTableRewriter.disableEarlyOpeningForTests = true; testScrubCorruptedCounterRow(); } finally { SSTableRewriter.disableEarlyOpeningForTests = oldDisabledVal; } } @Test public void testScrubMultiRow() throws ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF); cfs.clearUnsafe(); // insert data and verify we get it back w/ range query fillCF(cfs, 10); assertOrderedAll(cfs, 10); CompactionManager.instance.performScrub(cfs, false, true); // check data is still there assertOrderedAll(cfs, 10); } @Test public void testScrubNoIndex() throws IOException, ExecutionException, InterruptedException, ConfigurationException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(CF); cfs.clearUnsafe(); // insert data and verify we get it back w/ range query fillCF(cfs, 10); assertOrderedAll(cfs, 10); for (SSTableReader sstable : cfs.getLiveSSTables()) new File(sstable.descriptor.filenameFor(Component.PRIMARY_INDEX)).delete(); CompactionManager.instance.performScrub(cfs, false, true, true); // check data is still there assertOrderedAll(cfs, 10); } @Test public void testScrubOutOfOrder() throws Exception { // This test assumes ByteOrderPartitioner to create out-of-order SSTable IPartitioner oldPartitioner = DatabaseDescriptor.getPartitioner(); DatabaseDescriptor.setPartitionerUnsafe(new ByteOrderedPartitioner()); // Create out-of-order SSTable File tempDir = File.createTempFile("ScrubTest.testScrubOutOfOrder", "").getParentFile(); // create ks/cf directory File tempDataDir = new File(tempDir, String.join(File.separator, KEYSPACE, CF3)); tempDataDir.mkdirs(); try { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); String columnFamily = CF3; ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(columnFamily); cfs.clearUnsafe(); List<String> keys = Arrays.asList("t", "a", "b", "z", "c", "y", "d"); String filename = cfs.getSSTablePath(tempDataDir); Descriptor desc = Descriptor.fromFilename(filename); try (SSTableTxnWriter writer = SSTableTxnWriter.create(desc, keys.size(), 0L, 0, SerializationHeader.make(cfs.metadata, Collections.emptyList()))) { for (String k : keys) { PartitionUpdate update = UpdateBuilder.create(cfs.metadata, Util.dk(k)) .newRow("someName").add("val", "someValue") .build(); writer.append(update.unfilteredIterator()); } writer.finish(false); } try { SSTableReader.open(desc, cfs.metadata); fail("SSTR validation should have caught the out-of-order rows"); } catch (IllegalStateException ise) { /* this is expected */ } // open without validation for scrubbing Set<Component> components = new HashSet<>(); if (new File(desc.filenameFor(Component.COMPRESSION_INFO)).exists()) components.add(Component.COMPRESSION_INFO); components.add(Component.DATA); components.add(Component.PRIMARY_INDEX); components.add(Component.FILTER); components.add(Component.STATS); components.add(Component.SUMMARY); components.add(Component.TOC); SSTableReader sstable = SSTableReader.openNoValidation(desc, components, cfs); if (sstable.last.compareTo(sstable.first) < 0) sstable.last = sstable.first; try (LifecycleTransaction txn = LifecycleTransaction.offline(OperationType.SCRUB, sstable); Scrubber scrubber = new Scrubber(cfs, txn, false, true, true)) { scrubber.scrub(); } TransactionLog.waitForDeletions(); cfs.loadNewSSTables(); assertOrderedAll(cfs, 7); } finally { FileUtils.deleteRecursive(tempDataDir); // reset partitioner DatabaseDescriptor.setPartitionerUnsafe(oldPartitioner); } } private void overrideWithGarbage(SSTableReader sstable, ByteBuffer key1, ByteBuffer key2) throws IOException { boolean compression = Boolean.parseBoolean(System.getProperty("cassandra.test.compression", "false")); long startPosition, endPosition; if (compression) { // overwrite with garbage the compression chunks from key1 to key2 CompressionMetadata compData = CompressionMetadata.create(sstable.getFilename()); CompressionMetadata.Chunk chunk1 = compData.chunkFor( sstable.getPosition(PartitionPosition.ForKey.get(key1, sstable.getPartitioner()), SSTableReader.Operator.EQ).position); CompressionMetadata.Chunk chunk2 = compData.chunkFor( sstable.getPosition(PartitionPosition.ForKey.get(key2, sstable.getPartitioner()), SSTableReader.Operator.EQ).position); startPosition = Math.min(chunk1.offset, chunk2.offset); endPosition = Math.max(chunk1.offset + chunk1.length, chunk2.offset + chunk2.length); compData.close(); } else { // overwrite with garbage from key1 to key2 long row0Start = sstable.getPosition(PartitionPosition.ForKey.get(key1, sstable.getPartitioner()), SSTableReader.Operator.EQ).position; long row1Start = sstable.getPosition(PartitionPosition.ForKey.get(key2, sstable.getPartitioner()), SSTableReader.Operator.EQ).position; startPosition = Math.min(row0Start, row1Start); endPosition = Math.max(row0Start, row1Start); } overrideWithGarbage(sstable, startPosition, endPosition); } private void overrideWithGarbage(SSTableReader sstable, long startPosition, long endPosition) throws IOException { RandomAccessFile file = new RandomAccessFile(sstable.getFilename(), "rw"); file.seek(startPosition); file.writeBytes(StringUtils.repeat('z', (int) (endPosition - startPosition))); file.close(); } private static void assertOrderedAll(ColumnFamilyStore cfs, int expectedSize) { assertOrdered(Util.cmd(cfs).build(), expectedSize); } private static void assertOrdered(ReadCommand cmd, int expectedSize) { int size = 0; DecoratedKey prev = null; for (Partition partition : Util.getAllUnfiltered(cmd)) { DecoratedKey current = partition.partitionKey(); assertTrue("key " + current + " does not sort after previous key " + prev, prev == null || prev.compareTo(current) < 0); prev = current; ++size; } assertEquals(expectedSize, size); } protected void fillCF(ColumnFamilyStore cfs, int partitionsPerSSTable) { for (int i = 0; i < partitionsPerSSTable; i++) { PartitionUpdate update = UpdateBuilder.create(cfs.metadata, String.valueOf(i)) .newRow("r1").add("val", "1") .newRow("r1").add("val", "1") .build(); new Mutation(update).applyUnsafe(); } cfs.forceBlockingFlush(); } public static void fillIndexCF(ColumnFamilyStore cfs, boolean composite, long ... values) { assertTrue(values.length % 2 == 0); for (int i = 0; i < values.length; i +=2) { UpdateBuilder builder = UpdateBuilder.create(cfs.metadata, String.valueOf(i)); if (composite) { builder.newRow("c" + i) .add(COL_INDEX, values[i]) .add(COL_NON_INDEX, values[i + 1]); } else { builder.newRow() .add(COL_INDEX, values[i]) .add(COL_NON_INDEX, values[i + 1]); } new Mutation(builder.build()).applyUnsafe(); } cfs.forceBlockingFlush(); } protected void fillCounterCF(ColumnFamilyStore cfs, int partitionsPerSSTable) throws WriteTimeoutException { for (int i = 0; i < partitionsPerSSTable; i++) { PartitionUpdate update = UpdateBuilder.create(cfs.metadata, String.valueOf(i)) .newRow("r1").add("val", 100L) .build(); new CounterMutation(new Mutation(update), ConsistencyLevel.ONE).apply(); } cfs.forceBlockingFlush(); } @Test public void testScrubColumnValidation() throws InterruptedException, RequestExecutionException, ExecutionException { QueryProcessor.process(String.format("CREATE TABLE \"%s\".test_compact_static_columns (a bigint, b timeuuid, c boolean static, d text, PRIMARY KEY (a, b))", KEYSPACE), ConsistencyLevel.ONE); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("test_compact_static_columns"); QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_static_columns (a, b, c, d) VALUES (123, c3db07e8-b602-11e3-bc6b-e0b9a54a6d93, true, 'foobar')", KEYSPACE)); cfs.forceBlockingFlush(); CompactionManager.instance.performScrub(cfs, false, true); QueryProcessor.process("CREATE TABLE \"Keyspace1\".test_scrub_validation (a text primary key, b int)", ConsistencyLevel.ONE); ColumnFamilyStore cfs2 = keyspace.getColumnFamilyStore("test_scrub_validation"); new Mutation(UpdateBuilder.create(cfs2.metadata, "key").newRow().add("b", LongType.instance.decompose(1L)).build()).apply(); cfs2.forceBlockingFlush(); CompactionManager.instance.performScrub(cfs2, false, false); } /** * For CASSANDRA-6892 too, check that for a compact table with one cluster column, we can insert whatever * we want as value for the clustering column, including something that would conflict with a CQL column definition. */ @Test public void testValidationCompactStorage() throws Exception { QueryProcessor.process(String.format("CREATE TABLE \"%s\".test_compact_dynamic_columns (a int, b text, c text, PRIMARY KEY (a, b)) WITH COMPACT STORAGE", KEYSPACE), ConsistencyLevel.ONE); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore("test_compact_dynamic_columns"); QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_dynamic_columns (a, b, c) VALUES (0, 'a', 'foo')", KEYSPACE)); QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_dynamic_columns (a, b, c) VALUES (0, 'b', 'bar')", KEYSPACE)); QueryProcessor.executeInternal(String.format("INSERT INTO \"%s\".test_compact_dynamic_columns (a, b, c) VALUES (0, 'c', 'boo')", KEYSPACE)); cfs.forceBlockingFlush(); CompactionManager.instance.performScrub(cfs, true, true); // Scrub is silent, but it will remove broken records. So reading everything back to make sure nothing to "scrubbed away" UntypedResultSet rs = QueryProcessor.executeInternal(String.format("SELECT * FROM \"%s\".test_compact_dynamic_columns", KEYSPACE)); assertEquals(3, rs.size()); Iterator<UntypedResultSet.Row> iter = rs.iterator(); assertEquals("foo", iter.next().getString("c")); assertEquals("bar", iter.next().getString("c")); assertEquals("boo", iter.next().getString("c")); } @Test /* CASSANDRA-5174 */ public void testScrubKeysIndex_preserveOrder() throws IOException, ExecutionException, InterruptedException { //If the partitioner preserves the order then SecondaryIndex uses BytesType comparator, // otherwise it uses LocalByPartitionerType testScrubIndex(CF_INDEX1_BYTEORDERED, COL_INDEX, false, true); } @Test /* CASSANDRA-5174 */ public void testScrubCompositeIndex_preserveOrder() throws IOException, ExecutionException, InterruptedException { testScrubIndex(CF_INDEX2_BYTEORDERED, COL_INDEX, true, true); } @Test /* CASSANDRA-5174 */ public void testScrubKeysIndex() throws IOException, ExecutionException, InterruptedException { testScrubIndex(CF_INDEX1, COL_INDEX, false, true); } @Test /* CASSANDRA-5174 */ public void testScrubCompositeIndex() throws IOException, ExecutionException, InterruptedException { testScrubIndex(CF_INDEX2, COL_INDEX, true, true); } @Test /* CASSANDRA-5174 */ public void testFailScrubKeysIndex() throws IOException, ExecutionException, InterruptedException { testScrubIndex(CF_INDEX1, COL_INDEX, false, false); } @Test /* CASSANDRA-5174 */ public void testFailScrubCompositeIndex() throws IOException, ExecutionException, InterruptedException { testScrubIndex(CF_INDEX2, COL_INDEX, true, false); } @Test /* CASSANDRA-5174 */ public void testScrubTwice() throws IOException, ExecutionException, InterruptedException { testScrubIndex(CF_INDEX1, COL_INDEX, false, true, true); } private void testScrubIndex(String cfName, String colName, boolean composite, boolean ... scrubs) throws IOException, ExecutionException, InterruptedException { CompactionManager.instance.disableAutoCompaction(); Keyspace keyspace = Keyspace.open(KEYSPACE); ColumnFamilyStore cfs = keyspace.getColumnFamilyStore(cfName); cfs.clearUnsafe(); int numRows = 1000; long[] colValues = new long [numRows * 2]; // each row has two columns for (int i = 0; i < colValues.length; i+=2) { colValues[i] = (i % 4 == 0 ? 1L : 2L); // index column colValues[i+1] = 3L; //other column } fillIndexCF(cfs, composite, colValues); // check index assertOrdered(Util.cmd(cfs).filterOn(colName, Operator.EQ, 1L).build(), numRows / 2); // scrub index Set<ColumnFamilyStore> indexCfss = cfs.indexManager.getIndexesBackedByCfs(); assertTrue(indexCfss.size() == 1); for(ColumnFamilyStore indexCfs : indexCfss) { for (int i = 0; i < scrubs.length; i++) { boolean failure = !scrubs[i]; if (failure) { //make sure the next scrub fails overrideWithGarbage(indexCfs.getLiveSSTables().iterator().next(), ByteBufferUtil.bytes(1L), ByteBufferUtil.bytes(2L)); } CompactionManager.AllSSTableOpStatus result = indexCfs.scrub(false, false, true, true); assertEquals(failure ? CompactionManager.AllSSTableOpStatus.ABORTED : CompactionManager.AllSSTableOpStatus.SUCCESSFUL, result); } } // check index is still working assertOrdered(Util.cmd(cfs).filterOn(colName, Operator.EQ, 1L).build(), numRows / 2); } }
likaiwalkman/cassandra
test/unit/org/apache/cassandra/db/ScrubTest.java
Java
apache-2.0
27,146
// Copyright 2017 The TIE Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Factory for creating a snapshot of a student's code * and performance at a given time. */ tie.factory('SnapshotObjectFactory', [ function() { var Snapshot = function(codePrereqCheckResult, codeEvalResult, feedback) { this._codePrereqCheckResult = codePrereqCheckResult; this._codeEvalResult = codeEvalResult; this._feedback = feedback; this._timestamp = ''; }; // Instance methods. Snapshot.prototype.getCodePrereqCheckResult = function() { return this._codePrereqCheckResult; }; Snapshot.prototype.setCodePrereqCheckResult = function( codePrereqCheckResult) { this._codePrereqCheckResult = codePrereqCheckResult; }; Snapshot.prototype.getCodeEvalResult = function() { return this._codeEvalResult; }; Snapshot.prototype.setCodeEvalResult = function(codeEvalResult) { this._codeEvalResult = codeEvalResult; }; Snapshot.prototype.getFeedback = function() { return this._feedback; }; Snapshot.prototype.setFeedback = function(feedback) { this._feedback = feedback; }; // Static class methods. Snapshot.create = function(codePrereqCheckResult, codeEvalResult, feedback) { return new Snapshot(codePrereqCheckResult, codeEvalResult, feedback); }; return Snapshot; } ]);
BenjaminHolland/tie
client/domain/SnapshotObjectFactory.js
JavaScript
apache-2.0
1,970
/* * Copyright (C) 2015 hops.io. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.hops.security; import com.google.common.collect.Lists; import io.hops.metadata.HdfsStorageFactory; import io.hops.metadata.hdfs.dal.GroupDataAccess; import io.hops.metadata.hdfs.dal.UserDataAccess; import io.hops.metadata.hdfs.entity.Group; import io.hops.metadata.hdfs.entity.User; import io.hops.transaction.handler.HDFSOperationType; import io.hops.transaction.handler.LightWeightRequestHandler; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.DistributedFileSystem; import org.apache.hadoop.hdfs.HdfsConfiguration; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.ipc.RemoteException; import org.junit.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; public class TestUsersGroups { @Test public void testUsersGroupsCache(){ UsersGroupsCache cache = new UsersGroupsCache(10); User currentUser = new User(1, "user0"); List<Group> groups = Lists.newArrayList(); for(int i=1; i< 10; i++){ groups.add(new Group(i, "group"+i)); } //user1 -> {group1, group2} cache.addUserGroups(currentUser, groups.subList(0, 2)); Integer userId = cache.getUserId(currentUser.getName()); assertNotNull(userId); assertEquals((int)userId, currentUser.getId()); for(int i=0; i<2; i++){ Integer groupId = cache.getGroupId(groups.get(i).getName()); assertNotNull(groupId); assertEquals((int)groupId, groups.get(i).getId()); } assertNull(cache.getGroupId(groups.get(2).getName())); List<String> cachedGroups = cache.getGroups(currentUser.getName()); assertNotNull(cachedGroups); assertTrue(cachedGroups.equals(Arrays.asList(groups.get(0).getName(), groups.get(1).getName()))); //remove group by name [group1] cache.removeGroup(groups.get(0).getName()); Integer groupId = cache.getGroupId(groups.get(0).getName()); assertNull(groupId); cachedGroups = cache.getGroups(currentUser.getName()); assertNotNull(cachedGroups); assertTrue(cachedGroups.equals(Arrays.asList(groups.get(1).getName()))); //remove group by id [2] cache.removeGroup(groups.get(1).getId()); String groupName = cache.getGroupName(groups.get(1).getId()); assertNull(groupName); cachedGroups = cache.getGroups(currentUser.getName()); assertNull(cachedGroups); //add group [3] cache.addGroup(groups.get(2)); groupId = cache.getGroupId(groups.get(2).getName()); assertNotNull(groupId); assertEquals((int)groupId, groups.get(2).getId()); cachedGroups = cache.getGroups(currentUser.getName()); assertNull(cachedGroups); // append group to user: user1 -> {group3} cache.appendUserGroups(currentUser.getName(), Arrays.asList(groups.get(2) .getName())); cachedGroups = cache.getGroups(currentUser.getName()); assertNotNull(cachedGroups); assertTrue(cachedGroups.equals(Arrays.asList(groups.get(2).getName()))); UsersGroups.stop(); } @Test public void testCacheEviction(){ final int CACHE_SIZE = 5; UsersGroupsCache cache = new UsersGroupsCache(CACHE_SIZE); List<User> users = Lists.newArrayList(); List<Group> groups = Lists.newArrayList(); List<String> groupNames = Lists.newArrayList(); for(int i=1; i<=CACHE_SIZE; i++){ users.add(new User(i, "user"+ i)); String groupName = "group" + i; groups.add(new Group(i, groupName)); groupNames.add(groupName); } for(int i=0; i<CACHE_SIZE; i++){ cache.addUserGroups(users.get(i), groups.subList(i, (i==CACHE_SIZE - 1 ? i + 1 : i + 2))); } for(int i=0; i<CACHE_SIZE; i++){ List<String> cachedGroups = cache.getGroups(users.get(i).getName()); assertNotNull(cachedGroups); assertTrue(cachedGroups.equals(groupNames.subList(i, (i==CACHE_SIZE - 1 ? i + 1 : i + 2)))); } // add a new user to check eviction User newUser = new User(CACHE_SIZE + 1, "newUser"); cache.addUser(newUser); Integer userId = cache.getUserId(newUser.getName()); assertNotNull(userId); assertEquals((int)userId, newUser.getId()); userId = cache.getUserId(users.get(0).getName()); assertNull(userId); List<String> cachedGroups = cache.getGroups(users.get(0).getName()); assertNull(cachedGroups); // group1 should be removed since it is associated with only user1 Integer groupId = cache.getGroupId(groups.get(0).getName()); assertNull("Cache eviction should remove " + groups.get(0) .getName(), groupId); // group2 shouldn't be removed since it is associated with user1 and user2 groupId = cache.getGroupId(groups.get(1).getName()); assertNotNull("Cache eviction shouldn't remove " + groups.get(1) .getName(), groupId); //add 2 new group Group newGroup1 = new Group(CACHE_SIZE+1, "newgroup1"); Group newGroup2 = new Group(CACHE_SIZE+2, "newgroup2"); cache.addGroup(newGroup1); groupId = cache.getGroupId(newGroup1.getName()); assertNotNull(groupId); assertEquals((int) groupId, newGroup1.getId()); cache.addGroup(newGroup2); groupId = cache.getGroupId(newGroup2.getName()); assertNotNull(groupId); assertEquals((int) groupId, newGroup2.getId()); // group2 should be removed groupId = cache.getGroupId(groups.get(1).getName()); assertNull("Cache eviction should remove " + groups.get(1) .getName(), groupId); //user2 associated with group2 should be removed userId = cache.getUserId(users.get(1).getName()); assertNull("Cache eviction should remove all users associated with " + "a removed group ", userId); // group3 shouldn't be removed since it is associated with user2 and user3 groupId = cache.getGroupId(groups.get(2).getName()); assertNotNull("Cache eviction shouldn't remove " + groups.get(2) .getName(), groupId); //user3 shouldn't be removed userId = cache.getUserId(users.get(2).getName()); assertNotNull("Cache eviction shouldn't remove " + users.get(2).getName() +" since it wasn't associated with " + groups.get(1).getName(), userId); cachedGroups = cache.getGroups(users.get(2).getName()); assertNotNull(cachedGroups); assertEquals(cachedGroups, Arrays.asList(groups.get(2).getName(), groups .get(3).getName())); //add another group Group newGroup3 = new Group(CACHE_SIZE+3, "newgroup3"); cache.addGroup(newGroup3); groupId = cache.getGroupId(newGroup1.getName()); assertNotNull(groupId); assertEquals((int) groupId, newGroup1.getId()); //group3 should be removed groupId = cache.getGroupId(groups.get(2).getName()); assertNull("Cache eviction should remove " + groups.get(2) .getName(), groupId); //user3 should be removed userId = cache.getUserId(users.get(2).getName()); assertNull("Cache eviction should remove all users associated with " + "a removed group ", userId); } @Test public void testUsersGroupsNotConfigurad() throws IOException { UsersGroups.addUserToGroups("user", new String[]{"group1", "group2"}); assertEquals(UsersGroups.getGroupID("group1"), 0); assertEquals(UsersGroups.getUserID("user"), 0); UsersGroups.stop(); } @Test public void testAddUsers() throws IOException { Configuration conf = new Configuration(); conf.setInt(CommonConfigurationKeys.HOPS_GROUPS_UPDATER_ROUND, 10); HdfsStorageFactory.resetDALInitialized(); HdfsStorageFactory.setConfiguration(conf); HdfsStorageFactory.formatStorage(); UsersGroups.addUserToGroupsTx("user", new String[]{"group1", "group2"}); int userId = UsersGroups.getUserID("user"); assertNotSame(0, userId); assertEquals(UsersGroups.getUser(userId), "user"); int groupId = UsersGroups.getGroupID("group1"); assertNotSame(0, groupId); assertEquals(UsersGroups.getGroup(groupId), "group1"); assertEquals(UsersGroups.getGroups("user"), Arrays.asList("group1", "group2")); removeUser(userId); userId = UsersGroups.getUserID("user"); assertNotSame(0, userId); //Wait for the group updater to kick in try { Thread.sleep(10500); } catch (InterruptedException e) { e.printStackTrace(); } userId = UsersGroups.getUserID("user"); assertEquals(0, userId); assertNull(UsersGroups.getGroups("user")); UsersGroups.addUserToGroupsTx("user", new String[]{"group1", "group2"}); userId = UsersGroups.getUserID("user"); assertNotSame(0, userId); assertEquals(Arrays.asList("group1", "group2"), UsersGroups.getGroups("user")); removeUser(userId); UsersGroups.addUserToGroupsTx("user", new String[]{"group3"}); int newUserId = UsersGroups.getUserID("user"); assertNotSame(0, userId); //Auto incremented Ids assertTrue(newUserId > userId); UsersGroups.addUserToGroupsTx("user", new String[]{"group1", "group2"}); assertEquals(Arrays.asList("group3", "group1", "group2"), UsersGroups.getGroups("user")); UsersGroups.stop(); } @Test public void testGroupMappingsRefresh() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1) .build(); cluster.waitActive(); cluster.getNameNode().getRpcServer().refreshUserToGroupsMappings(); UsersGroups.addUserToGroupsTx("user", new String[]{"group1", "group2"}); int userId = UsersGroups.getUserID("user"); assertNotSame(0, userId); assertEquals(UsersGroups.getUser(userId), "user"); int groupId = UsersGroups.getGroupID("group1"); assertNotSame(0, groupId); assertEquals(UsersGroups.getGroup(groupId), "group1"); assertEquals(UsersGroups.getGroups("user"), Arrays.asList("group1", "group2")); removeUser(userId); userId = UsersGroups.getUserID("user"); assertNotSame(0, userId); cluster.getNameNode().getRpcServer().refreshUserToGroupsMappings(); userId = UsersGroups.getUserID("user"); assertEquals(0, userId); assertNull(UsersGroups.getGroups("user")); UsersGroups.addUserToGroupsTx("user", new String[]{"group1", "group2"}); userId = UsersGroups.getUserID("user"); assertNotSame(0, userId); assertEquals(Arrays.asList("group1", "group2"), UsersGroups.getGroups("user")); removeUser(userId); UsersGroups.addUserToGroupsTx("user", new String[]{"group3"}); int newUserId = UsersGroups.getUserID("user"); assertNotSame(0, userId); //Auto incremented Ids assertTrue(newUserId > userId); UsersGroups.addUserToGroupsTx("user", new String[]{"group1", "group2"}); assertEquals(Arrays.asList("group3", "group1", "group2"), UsersGroups.getGroups("user")); cluster.shutdown(); } @Test public void setOwnerMultipleTimes() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1) .build(); cluster.waitActive(); DistributedFileSystem dfs = cluster.getFileSystem(); Path base = new Path("/projects/project1"); dfs.mkdirs(base); Path child = new Path(base, "dataset"); dfs.mkdirs(child); dfs.setOwner(base, "testUser", "testGroup"); removeGroup(UsersGroups.getGroupID("testGroup")); dfs.flushCacheGroup("testGroup"); dfs.setOwner(base, "testUser", "testGroup"); cluster.shutdown(); } private void removeUser(final int userId) throws IOException { new LightWeightRequestHandler( HDFSOperationType.TEST) { @Override public Object performTask() throws IOException { UserDataAccess da = (UserDataAccess) HdfsStorageFactory.getDataAccess(UserDataAccess .class); da.removeUser(userId); return null; } }.handle(); } private void removeGroup(final int groupId) throws IOException { new LightWeightRequestHandler( HDFSOperationType.TEST) { @Override public Object performTask() throws IOException { GroupDataAccess da = (GroupDataAccess) HdfsStorageFactory.getDataAccess (GroupDataAccess.class); da.removeGroup(groupId); return null; } }.handle(); } }
gigaroby/hops
hadoop-hdfs-project/hadoop-hdfs/src/test/java/io/hops/security/TestUsersGroups.java
Java
apache-2.0
13,258
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Fri Nov 14 18:25:53 PST 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>org.apache.hadoop.hbase.mapreduce (HBase 0.98.8-hadoop2 API)</title> <meta name="date" content="2014-11-14"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.hadoop.hbase.mapreduce (HBase 0.98.8-hadoop2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/hadoop/hbase/mapred/package-summary.html">Prev Package</a></li> <li><a href="../../../../../org/apache/hadoop/hbase/master/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/hadoop/hbase/mapreduce/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.apache.hadoop.hbase.mapreduce</h1> <div class="docSummary"> <div class="block">Provides HBase <a href="http://wiki.apache.org/hadoop/HadoopMapReduce">MapReduce</a> Input/OutputFormats, a table indexing MapReduce job, and utility</div> </div> <p>See:&nbsp;<a href="#package_description">Description</a></p> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Interface Summary table, listing interfaces, and an explanation"> <caption><span>Interface Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Interface</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/VisibilityExpressionResolver.html" title="interface in org.apache.hadoop.hbase.mapreduce">VisibilityExpressionResolver</a></td> <td class="colLast"> <div class="block">Interface to convert visibility expressions into Tags for storing along with Cells in HFiles.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/CellCounter.html" title="class in org.apache.hadoop.hbase.mapreduce">CellCounter</a></td> <td class="colLast"> <div class="block">A job with a a map and reduce phase to count cells in a table.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/CellCreator.html" title="class in org.apache.hadoop.hbase.mapreduce">CellCreator</a></td> <td class="colLast"> <div class="block">Facade to create Cells for HFileOutputFormat.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/CopyTable.html" title="class in org.apache.hadoop.hbase.mapreduce">CopyTable</a></td> <td class="colLast"> <div class="block">Tool used to copy a table to another one which can be on a different setup.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/Driver.html" title="class in org.apache.hadoop.hbase.mapreduce">Driver</a></td> <td class="colLast"> <div class="block">Driver for hbase mapreduce jobs.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/Export.html" title="class in org.apache.hadoop.hbase.mapreduce">Export</a></td> <td class="colLast"> <div class="block">Export an HBase table.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/GroupingTableMapper.html" title="class in org.apache.hadoop.hbase.mapreduce">GroupingTableMapper</a></td> <td class="colLast"> <div class="block">Extract grouping columns from input record.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/HFileOutputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">HFileOutputFormat</a></td> <td class="colLast">Deprecated <div class="block"><i>use <a href="../../../../../org/apache/hadoop/hbase/mapreduce/HFileOutputFormat2.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>HFileOutputFormat2</code></a> instead.</i></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/HFileOutputFormat2.html" title="class in org.apache.hadoop.hbase.mapreduce">HFileOutputFormat2</a></td> <td class="colLast"> <div class="block">Writes HFiles.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/HLogInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">HLogInputFormat</a></td> <td class="colLast"> <div class="block">Simple <code>InputFormat</code> for <code>HLog</code> files.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/HRegionPartitioner.html" title="class in org.apache.hadoop.hbase.mapreduce">HRegionPartitioner</a>&lt;KEY,VALUE&gt;</td> <td class="colLast"> <div class="block">This is used to partition the output keys into groups of keys.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/IdentityTableMapper.html" title="class in org.apache.hadoop.hbase.mapreduce">IdentityTableMapper</a></td> <td class="colLast"> <div class="block">Pass the given key and record as-is to the reduce phase.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/IdentityTableReducer.html" title="class in org.apache.hadoop.hbase.mapreduce">IdentityTableReducer</a></td> <td class="colLast"> <div class="block">Convenience class that simply writes all values (which must be <a href="../../../../../org/apache/hadoop/hbase/client/Put.html" title="class in org.apache.hadoop.hbase.client"><code>Put</code></a> or <a href="../../../../../org/apache/hadoop/hbase/client/Delete.html" title="class in org.apache.hadoop.hbase.client"><code>Delete</code></a> instances) passed to it out to the configured HBase table.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/Import.html" title="class in org.apache.hadoop.hbase.mapreduce">Import</a></td> <td class="colLast"> <div class="block">Import data written by <a href="../../../../../org/apache/hadoop/hbase/mapreduce/Export.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>Export</code></a>.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/ImportTsv.html" title="class in org.apache.hadoop.hbase.mapreduce">ImportTsv</a></td> <td class="colLast"> <div class="block">Tool to import data from a TSV file.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/KeyValueSortReducer.html" title="class in org.apache.hadoop.hbase.mapreduce">KeyValueSortReducer</a></td> <td class="colLast"> <div class="block">Emits sorted KeyValues.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/LoadIncrementalHFiles.html" title="class in org.apache.hadoop.hbase.mapreduce">LoadIncrementalHFiles</a></td> <td class="colLast"> <div class="block">Tool to load the output of HFileOutputFormat into an existing table.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">MultiTableInputFormat</a></td> <td class="colLast"> <div class="block">Convert HBase tabular data from multiple scanners into a format that is consumable by Map/Reduce.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableInputFormatBase.html" title="class in org.apache.hadoop.hbase.mapreduce">MultiTableInputFormatBase</a></td> <td class="colLast"> <div class="block">A base for <a href="../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>MultiTableInputFormat</code></a>s.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableOutputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">MultiTableOutputFormat</a></td> <td class="colLast"> <div class="block"> Hadoop output format that writes to one or more HBase tables.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/PutCombiner.html" title="class in org.apache.hadoop.hbase.mapreduce">PutCombiner</a>&lt;K&gt;</td> <td class="colLast"> <div class="block">Combine Puts.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/PutSortReducer.html" title="class in org.apache.hadoop.hbase.mapreduce">PutSortReducer</a></td> <td class="colLast"> <div class="block">Emits sorted Puts.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/RowCounter.html" title="class in org.apache.hadoop.hbase.mapreduce">RowCounter</a></td> <td class="colLast"> <div class="block">A job with a just a map phase to count rows.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/SimpleTotalOrderPartitioner.html" title="class in org.apache.hadoop.hbase.mapreduce">SimpleTotalOrderPartitioner</a>&lt;VALUE&gt;</td> <td class="colLast"> <div class="block">A partitioner that takes start and end keys and uses bigdecimal to figure which reduce a key belongs to.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">TableInputFormat</a></td> <td class="colLast"> <div class="block">Convert HBase tabular data into a format that is consumable by Map/Reduce.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableInputFormatBase.html" title="class in org.apache.hadoop.hbase.mapreduce">TableInputFormatBase</a></td> <td class="colLast"> <div class="block">A base for <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableInputFormat</code></a>s.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableMapper.html" title="class in org.apache.hadoop.hbase.mapreduce">TableMapper</a>&lt;KEYOUT,VALUEOUT&gt;</td> <td class="colLast"> <div class="block">Extends the base <code>Mapper</code> class to add the required input key and value classes.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableMapReduceUtil.html" title="class in org.apache.hadoop.hbase.mapreduce">TableMapReduceUtil</a></td> <td class="colLast"> <div class="block">Utility for <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableMapper.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableMapper</code></a> and <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableReducer.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableReducer</code></a></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableOutputCommitter.html" title="class in org.apache.hadoop.hbase.mapreduce">TableOutputCommitter</a></td> <td class="colLast"> <div class="block">Small committer class that does not do anything.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableOutputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">TableOutputFormat</a>&lt;KEY&gt;</td> <td class="colLast"> <div class="block">Convert Map/Reduce output and write it to an HBase table.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableRecordReader.html" title="class in org.apache.hadoop.hbase.mapreduce">TableRecordReader</a></td> <td class="colLast"> <div class="block">Iterate over an HBase table data, return (ImmutableBytesWritable, Result) pairs.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableRecordReaderImpl.html" title="class in org.apache.hadoop.hbase.mapreduce">TableRecordReaderImpl</a></td> <td class="colLast"> <div class="block">Iterate over an HBase table data, return (ImmutableBytesWritable, Result) pairs.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableReducer.html" title="class in org.apache.hadoop.hbase.mapreduce">TableReducer</a>&lt;KEYIN,VALUEIN,KEYOUT&gt;</td> <td class="colLast"> <div class="block">Extends the basic <code>Reducer</code> class to add the required key and value input/output classes.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableSnapshotInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce">TableSnapshotInputFormat</a></td> <td class="colLast"> <div class="block">TableSnapshotInputFormat allows a MapReduce job to run over a table snapshot.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableSplit.html" title="class in org.apache.hadoop.hbase.mapreduce">TableSplit</a></td> <td class="colLast"> <div class="block">A table split corresponds to a key range (low, high) and an optional scanner.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TextSortReducer.html" title="class in org.apache.hadoop.hbase.mapreduce">TextSortReducer</a></td> <td class="colLast"> <div class="block">Emits Sorted KeyValues.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TsvImporterMapper.html" title="class in org.apache.hadoop.hbase.mapreduce">TsvImporterMapper</a></td> <td class="colLast"> <div class="block">Write table content out to files in hdfs.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/TsvImporterTextMapper.html" title="class in org.apache.hadoop.hbase.mapreduce">TsvImporterTextMapper</a></td> <td class="colLast"> <div class="block">Write table content out to map output files.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/hadoop/hbase/mapreduce/WALPlayer.html" title="class in org.apache.hadoop.hbase.mapreduce">WALPlayer</a></td> <td class="colLast"> <div class="block">A tool to replay WAL files as a M/R job.</div> </td> </tr> </tbody> </table> </li> </ul> <a name="package_description"> <!-- --> </a> <h2 title="Package org.apache.hadoop.hbase.mapreduce Description">Package org.apache.hadoop.hbase.mapreduce Description</h2> <div class="block">Provides HBase <a href="http://wiki.apache.org/hadoop/HadoopMapReduce">MapReduce</a> Input/OutputFormats, a table indexing MapReduce job, and utility <h2>Table of Contents</h2> <ul> <li><a href="#classpath">HBase, MapReduce and the CLASSPATH</a></li> <li><a href="#driver">Bundled HBase MapReduce Jobs</a></li> <li><a href="#sink">HBase as MapReduce job data source and sink</a></li> <li><a href="#bulk">Bulk Import writing HFiles directly</a></li> <li><a href="#examples">Example Code</a></li> </ul> <h2><a name="classpath">HBase, MapReduce and the CLASSPATH</a></h2> <p>MapReduce jobs deployed to a MapReduce cluster do not by default have access to the HBase configuration under <code>$HBASE_CONF_DIR</code> nor to HBase classes. You could add <code>hbase-site.xml</code> to <code>$HADOOP_HOME/conf</code> and add HBase jars to the <code>$HADOOP_HOME/lib</code> and copy these changes across your cluster (or edit conf/hadoop-env.sh and add them to the <code>HADOOP_CLASSPATH</code> variable) but this will pollute your hadoop install with HBase references; its also obnoxious requiring restart of the hadoop cluster before it'll notice your HBase additions.</p> <p>As of 0.90.x, HBase will just add its dependency jars to the job configuration; the dependencies just need to be available on the local <code>CLASSPATH</code>. For example, to run the bundled HBase <a href="../../../../../org/apache/hadoop/hbase/mapreduce/RowCounter.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>RowCounter</code></a> mapreduce job against a table named <code>usertable</code>, type: <blockquote><pre> $ HADOOP_CLASSPATH=`${HBASE_HOME}/bin/hbase classpath` ${HADOOP_HOME}/bin/hadoop jar ${HBASE_HOME}/hbase-0.90.0.jar rowcounter usertable </pre></blockquote> Expand <code>$HBASE_HOME</code> and <code>$HADOOP_HOME</code> in the above appropriately to suit your local environment. The content of <code>HADOOP_CLASSPATH</code> is set to the HBase <code>CLASSPATH</code> via backticking the command <code>${HBASE_HOME}/bin/hbase classpath</code>. <p>When the above runs, internally, the HBase jar finds its zookeeper and <a href="http://code.google.com/p/guava-libraries/">guava</a>, etc., dependencies on the passed </code>HADOOP_CLASSPATH</code> and adds the found jars to the mapreduce job configuration. See the source at <code>TableMapReduceUtil#addDependencyJars(org.apache.hadoop.mapreduce.Job)</code> for how this is done. </p> <p>The above may not work if you are running your HBase from its build directory; i.e. you've done <code>$ mvn test install</code> at <code>${HBASE_HOME}</code> and you are now trying to use this build in your mapreduce job. If you get <blockquote><pre>java.lang.RuntimeException: java.lang.ClassNotFoundException: org.apache.hadoop.hbase.mapreduce.RowCounter$RowCounterMapper ... </pre></blockquote> exception thrown, try doing the following: <blockquote><pre> $ HADOOP_CLASSPATH=${HBASE_HOME}/target/hbase-0.90.0-SNAPSHOT.jar:`${HBASE_HOME}/bin/hbase classpath` ${HADOOP_HOME}/bin/hadoop jar ${HBASE_HOME}/target/hbase-0.90.0-SNAPSHOT.jar rowcounter usertable </pre></blockquote> Notice how we preface the backtick invocation setting <code>HADOOP_CLASSPATH</code> with reference to the built HBase jar over in the <code>target</code> directory. </p> <h2><a name="driver">Bundled HBase MapReduce Jobs</a></h2> <p>The HBase jar also serves as a Driver for some bundled mapreduce jobs. To learn about the bundled mapreduce jobs run: <blockquote><pre> $ ${HADOOP_HOME}/bin/hadoop jar ${HBASE_HOME}/hbase-0.90.0-SNAPSHOT.jar An example program must be given as the first argument. Valid program names are: copytable: Export a table from local cluster to peer cluster completebulkload: Complete a bulk data load. export: Write table data to HDFS. import: Import data written by Export. importtsv: Import data in TSV format. rowcounter: Count rows in HBase table </pre></blockquote> <h2><a name="sink">HBase as MapReduce job data source and sink</a></h2> <p>HBase can be used as a data source, <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableInputFormat</code></a>, and data sink, <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableOutputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableOutputFormat</code></a> or <a href="../../../../../org/apache/hadoop/hbase/mapreduce/MultiTableOutputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>MultiTableOutputFormat</code></a>, for MapReduce jobs. Writing MapReduce jobs that read or write HBase, you'll probably want to subclass <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableMapper.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableMapper</code></a> and/or <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableReducer.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableReducer</code></a>. See the do-nothing pass-through classes <a href="../../../../../org/apache/hadoop/hbase/mapreduce/IdentityTableMapper.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>IdentityTableMapper</code></a> and <a href="../../../../../org/apache/hadoop/hbase/mapreduce/IdentityTableReducer.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>IdentityTableReducer</code></a> for basic usage. For a more involved example, see <a href="../../../../../org/apache/hadoop/hbase/mapreduce/RowCounter.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>RowCounter</code></a> or review the <code>org.apache.hadoop.hbase.mapreduce.TestTableMapReduce</code> unit test. </p> <p>Running mapreduce jobs that have HBase as source or sink, you'll need to specify source/sink table and column names in your configuration.</p> <p>Reading from HBase, the TableInputFormat asks HBase for the list of regions and makes a map-per-region or <code>mapred.map.tasks maps</code>, whichever is smaller (If your job only has two maps, up mapred.map.tasks to a number &gt; number of regions). Maps will run on the adjacent TaskTracker if you are running a TaskTracer and RegionServer per node. Writing, it may make sense to avoid the reduce step and write yourself back into HBase from inside your map. You'd do this when your job does not need the sort and collation that mapreduce does on the map emitted data; on insert, HBase 'sorts' so there is no point double-sorting (and shuffling data around your mapreduce cluster) unless you need to. If you do not need the reduce, you might just have your map emit counts of records processed just so the framework's report at the end of your job has meaning or set the number of reduces to zero and use TableOutputFormat. See example code below. If running the reduce step makes sense in your case, its usually better to have lots of reducers so load is spread across the HBase cluster.</p> <p>There is also a new HBase partitioner that will run as many reducers as currently existing regions. The <a href="../../../../../org/apache/hadoop/hbase/mapreduce/HRegionPartitioner.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>HRegionPartitioner</code></a> is suitable when your table is large and your upload is not such that it will greatly alter the number of existing regions when done; otherwise use the default partitioner. </p> <h2><a name="bulk">Bulk import writing HFiles directly</a></h2> <p>If importing into a new table, its possible to by-pass the HBase API and write your content directly to the filesystem properly formatted as HBase data files (HFiles). Your import will run faster, perhaps an order of magnitude faster if not more. For more on how this mechanism works, see <a href="http://hbase.apache.org/bulk-loads.html">Bulk Loads</code> documentation. </p> <h2><a name="examples">Example Code</a></h2> <h3>Sample Row Counter</h3> <p>See <a href="../../../../../org/apache/hadoop/hbase/mapreduce/RowCounter.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>RowCounter</code></a>. This job uses <a href="../../../../../org/apache/hadoop/hbase/mapreduce/TableInputFormat.html" title="class in org.apache.hadoop.hbase.mapreduce"><code>TableInputFormat</code></a> and does a count of all rows in specified table. You should be able to run it by doing: <code>% ./bin/hadoop jar hbase-X.X.X.jar</code>. This will invoke the hbase MapReduce Driver class. Select 'rowcounter' from the choice of jobs offered. This will emit rowcouner 'usage'. Specify tablename, column to count and output directory. You may need to add the hbase conf directory to <code>$HADOOP_HOME/conf/hadoop-env.sh#HADOOP_CLASSPATH</code> so the rowcounter gets pointed at the right hbase cluster (or, build a new jar with an appropriate hbase-site.xml built into your job jar). </p></div> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/hadoop/hbase/mapred/package-summary.html">Prev Package</a></li> <li><a href="../../../../../org/apache/hadoop/hbase/master/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/hadoop/hbase/mapreduce/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2014 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All rights reserved.</small></p> </body> </html>
devansh2015/hbase-0.98.8
docs/apidocs/org/apache/hadoop/hbase/mapreduce/package-summary.html
HTML
apache-2.0
28,107
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="fr"> <head> <!-- Generated by javadoc (1.8.0_91) on Wed Jun 29 23:15:35 CEST 2016 --> <title>ProductEditor</title> <meta name="date" content="2016-06-29"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ProductEditor"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ProductEditor.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/imie/component/form/OrderEditor.ChangeHandler.html" title="interface in com.imie.component.form"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/imie/component/form/ProductEditor.ChangeHandler.html" title="interface in com.imie.component.form"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/imie/component/form/ProductEditor.html" target="_top">Frames</a></li> <li><a href="ProductEditor.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields.inherited.from.class.com.vaadin.ui.AbstractOrderedLayout">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">com.imie.component.form</div> <h2 title="Class ProductEditor" class="title">Class ProductEditor</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.vaadin.server.AbstractClientConnector</li> <li> <ul class="inheritance"> <li>com.vaadin.ui.AbstractComponent</li> <li> <ul class="inheritance"> <li>com.vaadin.ui.AbstractComponentContainer</li> <li> <ul class="inheritance"> <li>com.vaadin.ui.AbstractLayout</li> <li> <ul class="inheritance"> <li>com.vaadin.ui.AbstractOrderedLayout</li> <li> <ul class="inheritance"> <li>com.vaadin.ui.VerticalLayout</li> <li> <ul class="inheritance"> <li>com.imie.component.form.ProductEditor</li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>com.vaadin.event.LayoutEvents.LayoutClickNotifier, com.vaadin.event.MethodEventSource, com.vaadin.server.ClientConnector, com.vaadin.server.Sizeable, com.vaadin.shared.Connector, com.vaadin.ui.Component, com.vaadin.ui.ComponentContainer, com.vaadin.ui.HasComponents, com.vaadin.ui.HasComponents.ComponentAttachDetachNotifier, com.vaadin.ui.Layout, com.vaadin.ui.Layout.AlignmentHandler, com.vaadin.ui.Layout.MarginHandler, com.vaadin.ui.Layout.SpacingHandler, java.io.Serializable, java.lang.Iterable&lt;com.vaadin.ui.Component&gt;</dd> </dl> <hr> <br> <pre>@SpringComponent @UIScope public class <span class="typeNameLabel">ProductEditor</span> extends com.vaadin.ui.VerticalLayout</pre> <div class="block"><b>Product Form Editor Class</b></div> <dl> <dt><span class="simpleTagLabel">Version:</span></dt> <dd>1.0</dd> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>kevin boussard</dd> <dt><span class="seeLabel">See Also:</span></dt> <dd><a href="../../../../serialized-form.html#com.imie.component.form.ProductEditor">Serialized Form</a></dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested.class.summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Nested Class Summary table, listing nested classes, and an explanation"> <caption><span>Nested Classes</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static interface&nbsp;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/imie/component/form/ProductEditor.ChangeHandler.html" title="interface in com.imie.component.form">ProductEditor.ChangeHandler</a></span></code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.com.vaadin.ui.Layout"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;com.vaadin.ui.Layout</h3> <code>com.vaadin.ui.Layout.AlignmentHandler, com.vaadin.ui.Layout.MarginHandler, com.vaadin.ui.Layout.SpacingHandler</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.com.vaadin.ui.HasComponents"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;com.vaadin.ui.HasComponents</h3> <code>com.vaadin.ui.HasComponents.ComponentAttachDetachNotifier, com.vaadin.ui.HasComponents.ComponentAttachEvent, com.vaadin.ui.HasComponents.ComponentAttachListener, com.vaadin.ui.HasComponents.ComponentDetachEvent, com.vaadin.ui.HasComponents.ComponentDetachListener</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.com.vaadin.ui.Component"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;com.vaadin.ui.Component</h3> <code>com.vaadin.ui.Component.ErrorEvent, com.vaadin.ui.Component.Event, com.vaadin.ui.Component.Focusable, com.vaadin.ui.Component.Listener</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.com.vaadin.server.ClientConnector"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;com.vaadin.server.ClientConnector</h3> <code>com.vaadin.server.ClientConnector.AttachEvent, com.vaadin.server.ClientConnector.AttachListener, com.vaadin.server.ClientConnector.ConnectorErrorEvent, com.vaadin.server.ClientConnector.DetachEvent, com.vaadin.server.ClientConnector.DetachListener</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested.classes.inherited.from.class.com.vaadin.server.Sizeable"> <!-- --> </a> <h3>Nested classes/interfaces inherited from interface&nbsp;com.vaadin.server.Sizeable</h3> <code>com.vaadin.server.Sizeable.Unit</code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields.inherited.from.class.com.vaadin.ui.AbstractOrderedLayout"> <!-- --> </a> <h3>Fields inherited from class&nbsp;com.vaadin.ui.AbstractOrderedLayout</h3> <code>ALIGNMENT_DEFAULT, components</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="fields.inherited.from.class.com.vaadin.ui.AbstractComponent"> <!-- --> </a> <h3>Fields inherited from class&nbsp;com.vaadin.ui.AbstractComponent</h3> <code>DESIGN_ATTR_PLAIN_TEXT</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="fields.inherited.from.class.com.vaadin.server.Sizeable"> <!-- --> </a> <h3>Fields inherited from interface&nbsp;com.vaadin.server.Sizeable</h3> <code>SIZE_UNDEFINED, UNITS_CM, UNITS_EM, UNITS_EX, UNITS_INCH, UNITS_MM, UNITS_PERCENTAGE, UNITS_PICAS, UNITS_PIXELS, UNITS_POINTS</code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../com/imie/component/form/ProductEditor.html#ProductEditor-com.imie.component.repository.ProductRepository-">ProductEditor</a></span>(<a href="../../../../com/imie/component/repository/ProductRepository.html" title="interface in com.imie.component.repository">ProductRepository</a>&nbsp;repository)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/imie/component/form/ProductEditor.html#editProduct-com.imie.component.entity.Product-">editProduct</a></span>(<a href="../../../../com/imie/component/entity/Product.html" title="class in com.imie.component.entity">Product</a>&nbsp;p)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../com/imie/component/form/ProductEditor.html#setChangeHandler-com.imie.component.form.ProductEditor.ChangeHandler-">setChangeHandler</a></span>(<a href="../../../../com/imie/component/form/ProductEditor.ChangeHandler.html" title="interface in com.imie.component.form">ProductEditor.ChangeHandler</a>&nbsp;h)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.ui.AbstractOrderedLayout"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.vaadin.ui.AbstractOrderedLayout</h3> <code>addComponent, addComponent, addComponentAsFirst, addLayoutClickListener, addListener, getComponent, getComponentAlignment, getComponentCount, getComponentIndex, getCustomAttributes, getDefaultComponentAlignment, getExpandRatio, getMargin, getState, getState, isSpacing, iterator, readDesign, removeComponent, removeLayoutClickListener, removeListener, replaceComponent, setComponentAlignment, setDefaultComponentAlignment, setExpandRatio, setMargin, setMargin, setSpacing, writeDesign</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.ui.AbstractComponentContainer"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.vaadin.ui.AbstractComponentContainer</h3> <code>addComponentAttachListener, addComponentDetachListener, addComponents, addListener, addListener, fireComponentAttachEvent, fireComponentDetachEvent, getComponentIterator, moveComponentsFrom, removeAllComponents, removeComponentAttachListener, removeComponentDetachListener, removeListener, removeListener, setHeight, setWidth</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.ui.AbstractComponent"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.vaadin.ui.AbstractComponent</h3> <code>addListener, addShortcutListener, addStyleName, attach, beforeClientResponse, detach, findAncestor, fireComponentErrorEvent, fireComponentEvent, focus, getActionManager, getCaption, getComponentError, getData, getDebugId, getDescription, getErrorMessage, getHeight, getHeightUnits, getIcon, getId, getLocale, getParent, getPrimaryStyleName, getStyleName, getWidth, getWidthUnits, isCaptionAsHtml, isConnectorEnabled, isEnabled, isImmediate, isOrHasAncestor, isReadOnly, isVisible, removeListener, removeShortcutListener, removeStyleName, setCaption, setCaptionAsHtml, setComponentError, setData, setDebugId, setDescription, setEnabled, setHeight, setHeightUndefined, setIcon, setId, setImmediate, setLocale, setParent, setPrimaryStyleName, setReadOnly, setSizeFull, setSizeUndefined, setStyleName, setVisible, setWidth, setWidthUndefined</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.server.AbstractClientConnector"> <!-- --> </a> <h3>Methods inherited from class&nbsp;com.vaadin.server.AbstractClientConnector</h3> <code>addAttachListener, addDetachListener, addExtension, addListener, addListener, addListener, addMethodInvocationToQueue, createState, encodeState, equals, fireEvent, getAllChildrenIterable, getConnectorId, getErrorHandler, getExtensions, getListeners, getResource, getRpcManager, getRpcProxy, getSession, getStateType, getUI, handleConnectorRequest, hashCode, hasListeners, isAttached, isThis, markAsDirty, markAsDirtyRecursive, registerRpc, registerRpc, removeAttachListener, removeDetachListener, removeExtension, removeListener, removeListener, removeListener, removeListener, requestRepaint, requestRepaintAll, retrievePendingRpcCalls, setErrorHandler, setResource</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, finalize, getClass, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.ui.ComponentContainer"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.vaadin.ui.ComponentContainer</h3> <code>addComponents, addListener, addListener, getComponentIterator, moveComponentsFrom, removeAllComponents, removeListener, removeListener</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.ui.Component"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.vaadin.ui.Component</h3> <code>addListener, addStyleName, attach, getCaption, getDescription, getIcon, getId, getLocale, getParent, getPrimaryStyleName, getStyleName, getUI, isEnabled, isReadOnly, isVisible, removeListener, removeStyleName, setCaption, setEnabled, setIcon, setId, setParent, setPrimaryStyleName, setReadOnly, setStyleName, setVisible</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.server.ClientConnector"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.vaadin.server.ClientConnector</h3> <code>addAttachListener, addDetachListener, beforeClientResponse, detach, encodeState, getErrorHandler, getExtensions, getRpcManager, getStateType, handleConnectorRequest, isAttached, isConnectorEnabled, markAsDirty, markAsDirtyRecursive, removeAttachListener, removeDetachListener, removeExtension, requestRepaint, requestRepaintAll, retrievePendingRpcCalls, setErrorHandler</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.shared.Connector"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.vaadin.shared.Connector</h3> <code>getConnectorId</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.server.Sizeable"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.vaadin.server.Sizeable</h3> <code>getHeight, getHeightUnits, getWidth, getWidthUnits, setHeight, setHeight, setHeightUndefined, setSizeFull, setSizeUndefined, setWidth, setWidth, setWidthUndefined</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Iterable"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;java.lang.Iterable</h3> <code>forEach, spliterator</code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.com.vaadin.ui.HasComponents.ComponentAttachDetachNotifier"> <!-- --> </a> <h3>Methods inherited from interface&nbsp;com.vaadin.ui.HasComponents.ComponentAttachDetachNotifier</h3> <code>addComponentAttachListener, addComponentDetachListener, removeComponentAttachListener, removeComponentDetachListener</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ProductEditor-com.imie.component.repository.ProductRepository-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ProductEditor</h4> <pre>@Autowired public&nbsp;ProductEditor(<a href="../../../../com/imie/component/repository/ProductRepository.html" title="interface in com.imie.component.repository">ProductRepository</a>&nbsp;repository)</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="editProduct-com.imie.component.entity.Product-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>editProduct</h4> <pre>public final&nbsp;void&nbsp;editProduct(<a href="../../../../com/imie/component/entity/Product.html" title="class in com.imie.component.entity">Product</a>&nbsp;p)</pre> </li> </ul> <a name="setChangeHandler-com.imie.component.form.ProductEditor.ChangeHandler-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setChangeHandler</h4> <pre>public&nbsp;void&nbsp;setChangeHandler(<a href="../../../../com/imie/component/form/ProductEditor.ChangeHandler.html" title="interface in com.imie.component.form">ProductEditor.ChangeHandler</a>&nbsp;h)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/ProductEditor.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/imie/component/form/OrderEditor.ChangeHandler.html" title="interface in com.imie.component.form"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../com/imie/component/form/ProductEditor.ChangeHandler.html" title="interface in com.imie.component.form"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/imie/component/form/ProductEditor.html" target="_top">Frames</a></li> <li><a href="ProductEditor.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested.class.summary">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields.inherited.from.class.com.vaadin.ui.AbstractOrderedLayout">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
kevinboussard/IMIE-COMPONENT
Javadoc/com/imie/component/form/ProductEditor.html
HTML
apache-2.0
22,597
package com.tianxing.pattern.Bridge; /** * Created by tianxing on 2017/3/8. * 功能层次 最上层 */ public class Display { private DisplayImpl impl; public Display(DisplayImpl impl){ this.impl = impl; } public void open(){ impl.rawOpen(); } public void print(){ impl.rawPrint(); } public void close(){ impl.rawClose(); } public final void display(){ open(); print(); close(); } }
sngths/gradle-demo
src/main/java/com/tianxing/pattern/Bridge/Display.java
Java
apache-2.0
495
# Copyright 2013: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg OPTS = {"benchmark": [ # prepoll delay, timeout, poll interval # "start": (0, 300, 1) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "start", default=float(0), help="Time to sleep after %s before polling" " for status" % "start"), cfg.FloatOpt("nova_server_%s_timeout" % "start", default=float(300), help="Server %s timeout" % "start"), cfg.FloatOpt("nova_server_%s_poll_interval" % "start", default=float(1), help="Server %s poll interval" % "start"), # "stop": (0, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "stop", default=float(0), help="Time to sleep after %s before polling" " for status" % "stop"), cfg.FloatOpt("nova_server_%s_timeout" % "stop", default=float(300), help="Server %s timeout" % "stop"), cfg.FloatOpt("nova_server_%s_poll_interval" % "stop", default=float(2), help="Server %s poll interval" % "stop"), # "boot": (1, 300, 1) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "boot", default=float(1), help="Time to sleep after %s before polling" " for status" % "boot"), cfg.FloatOpt("nova_server_%s_timeout" % "boot", default=float(300), help="Server %s timeout" % "boot"), cfg.FloatOpt("nova_server_%s_poll_interval" % "boot", default=float(2), help="Server %s poll interval" % "boot"), # "delete": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "delete", default=float(2), help="Time to sleep after %s before polling" " for status" % "delete"), cfg.FloatOpt("nova_server_%s_timeout" % "delete", default=float(300), help="Server %s timeout" % "delete"), cfg.FloatOpt("nova_server_%s_poll_interval" % "delete", default=float(2), help="Server %s poll interval" % "delete"), # "reboot": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "reboot", default=float(2), help="Time to sleep after %s before polling" " for status" % "reboot"), cfg.FloatOpt("nova_server_%s_timeout" % "reboot", default=float(300), help="Server %s timeout" % "reboot"), cfg.FloatOpt("nova_server_%s_poll_interval" % "reboot", default=float(2), help="Server %s poll interval" % "reboot"), # "rebuild": (1, 300, 1) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "rebuild", default=float(1), help="Time to sleep after %s before polling" " for status" % "rebuild"), cfg.FloatOpt("nova_server_%s_timeout" % "rebuild", default=float(300), help="Server %s timeout" % "rebuild"), cfg.FloatOpt("nova_server_%s_poll_interval" % "rebuild", default=float(1), help="Server %s poll interval" % "rebuild"), # "rescue": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "rescue", default=float(2), help="Time to sleep after %s before polling" " for status" % "rescue"), cfg.FloatOpt("nova_server_%s_timeout" % "rescue", default=float(300), help="Server %s timeout" % "rescue"), cfg.FloatOpt("nova_server_%s_poll_interval" % "rescue", default=float(2), help="Server %s poll interval" % "rescue"), # "unrescue": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "unrescue", default=float(2), help="Time to sleep after %s before polling" " for status" % "unrescue"), cfg.FloatOpt("nova_server_%s_timeout" % "unrescue", default=float(300), help="Server %s timeout" % "unrescue"), cfg.FloatOpt("nova_server_%s_poll_interval" % "unrescue", default=float(2), help="Server %s poll interval" % "unrescue"), # "suspend": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "suspend", default=float(2), help="Time to sleep after %s before polling" " for status" % "suspend"), cfg.FloatOpt("nova_server_%s_timeout" % "suspend", default=float(300), help="Server %s timeout" % "suspend"), cfg.FloatOpt("nova_server_%s_poll_interval" % "suspend", default=float(2), help="Server %s poll interval" % "suspend"), # "resume": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resume", default=float(2), help="Time to sleep after %s before polling" " for status" % "resume"), cfg.FloatOpt("nova_server_%s_timeout" % "resume", default=float(300), help="Server %s timeout" % "resume"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resume", default=float(2), help="Server %s poll interval" % "resume"), # "pause": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "pause", default=float(2), help="Time to sleep after %s before polling" " for status" % "pause"), cfg.FloatOpt("nova_server_%s_timeout" % "pause", default=float(300), help="Server %s timeout" % "pause"), cfg.FloatOpt("nova_server_%s_poll_interval" % "pause", default=float(2), help="Server %s poll interval" % "pause"), # "unpause": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "unpause", default=float(2), help="Time to sleep after %s before polling" " for status" % "unpause"), cfg.FloatOpt("nova_server_%s_timeout" % "unpause", default=float(300), help="Server %s timeout" % "unpause"), cfg.FloatOpt("nova_server_%s_poll_interval" % "unpause", default=float(2), help="Server %s poll interval" % "unpause"), # "shelve": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "shelve", default=float(2), help="Time to sleep after %s before polling" " for status" % "shelve"), cfg.FloatOpt("nova_server_%s_timeout" % "shelve", default=float(300), help="Server %s timeout" % "shelve"), cfg.FloatOpt("nova_server_%s_poll_interval" % "shelve", default=float(2), help="Server %s poll interval" % "shelve"), # "unshelve": (2, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "unshelve", default=float(2), help="Time to sleep after %s before polling" " for status" % "unshelve"), cfg.FloatOpt("nova_server_%s_timeout" % "unshelve", default=float(300), help="Server %s timeout" % "unshelve"), cfg.FloatOpt("nova_server_%s_poll_interval" % "unshelve", default=float(2), help="Server %s poll interval" % "unshelve"), # "image_create": (0, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "image_create", default=float(0), help="Time to sleep after %s before polling" " for status" % "image_create"), cfg.FloatOpt("nova_server_%s_timeout" % "image_create", default=float(300), help="Server %s timeout" % "image_create"), cfg.FloatOpt("nova_server_%s_poll_interval" % "image_create", default=float(2), help="Server %s poll interval" % "image_create"), # "image_delete": (0, 300, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "image_delete", default=float(0), help="Time to sleep after %s before polling" " for status" % "image_delete"), cfg.FloatOpt("nova_server_%s_timeout" % "image_delete", default=float(300), help="Server %s timeout" % "image_delete"), cfg.FloatOpt("nova_server_%s_poll_interval" % "image_delete", default=float(2), help="Server %s poll interval" % "image_delete"), # "resize": (2, 400, 5) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resize", default=float(2), help="Time to sleep after %s before polling" " for status" % "resize"), cfg.FloatOpt("nova_server_%s_timeout" % "resize", default=float(400), help="Server %s timeout" % "resize"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resize", default=float(5), help="Server %s poll interval" % "resize"), # "resize_confirm": (0, 200, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resize_confirm", default=float(0), help="Time to sleep after %s before polling" " for status" % "resize_confirm"), cfg.FloatOpt("nova_server_%s_timeout" % "resize_confirm", default=float(200), help="Server %s timeout" % "resize_confirm"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resize_confirm", default=float(2), help="Server %s poll interval" % "resize_confirm"), # "resize_revert": (0, 200, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "resize_revert", default=float(0), help="Time to sleep after %s before polling" " for status" % "resize_revert"), cfg.FloatOpt("nova_server_%s_timeout" % "resize_revert", default=float(200), help="Server %s timeout" % "resize_revert"), cfg.FloatOpt("nova_server_%s_poll_interval" % "resize_revert", default=float(2), help="Server %s poll interval" % "resize_revert"), # "live_migrate": (1, 400, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "live_migrate", default=float(1), help="Time to sleep after %s before polling" " for status" % "live_migrate"), cfg.FloatOpt("nova_server_%s_timeout" % "live_migrate", default=float(400), help="Server %s timeout" % "live_migrate"), cfg.FloatOpt("nova_server_%s_poll_interval" % "live_migrate", default=float(2), help="Server %s poll interval" % "live_migrate"), # "migrate": (1, 400, 2) cfg.FloatOpt("nova_server_%s_prepoll_delay" % "migrate", default=float(1), help="Time to sleep after %s before polling" " for status" % "migrate"), cfg.FloatOpt("nova_server_%s_timeout" % "migrate", default=float(400), help="Server %s timeout" % "migrate"), cfg.FloatOpt("nova_server_%s_poll_interval" % "migrate", default=float(2), help="Server %s poll interval" % "migrate"), # "detach": cfg.FloatOpt("nova_detach_volume_timeout", default=float(200), help="Nova volume detach timeout"), cfg.FloatOpt("nova_detach_volume_poll_interval", default=float(2), help="Nova volume detach poll interval") ]}
yeming233/rally
rally/plugins/openstack/cfg/nova.py
Python
apache-2.0
12,529
# -*- coding: utf-8 -*- ''' Created on Mar 12, 2012 @author: moloch Copyright 2012 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' import re from uuid import uuid4 from datetime import datetime from sqlalchemy import Column from sqlalchemy.types import DateTime, Integer, String from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.declarative import declarative_base generate_uuid = lambda: str(uuid4()) class _DatabaseObject(object): ''' All game objects inherit from this object ''' @declared_attr def __tablename__(self): ''' Converts name from camel case to snake case ''' name = self.__name__ return ( name[0].lower() + re.sub(r'([A-Z])', lambda letter: "_" + letter.group(0).lower(), name[1:] ) ) id = Column(Integer, unique=True, primary_key=True) # lint:ok uuid = Column(String(36), unique=True, default=generate_uuid) created = Column(DateTime, default=datetime.now) # Create an instance called "BaseObject" DatabaseObject = declarative_base(cls=_DatabaseObject)
lunarca/fngrpt
models/BaseModels.py
Python
apache-2.0
1,637
# Planchonella vitiensis Gillespie SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Sapotaceae/Planchonella/Planchonella vitiensis/README.md
Markdown
apache-2.0
190
# Copyright 2016 Cisco Systems, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging import logging.handlers log = logging.getLogger('imc') console = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') console.setFormatter(formatter) def enable_file_logging(filename="imcsdk.log"): file_handler = logging.handlers.RotatingFileHandler( filename, maxBytes=10*1024*1024, backupCount=5) log.addHandler(file_handler) def set_log_level(level=logging.DEBUG): """ Allows setting log level Args: level: logging level - import logging and pass enums from it(INFO/DEBUG/ERROR/etc..) Returns: None Example: from imcsdk import set_log_level import logging set_log_level(logging.INFO) """ log.setLevel(level) console.setLevel(level) set_log_level(logging.DEBUG) log.addHandler(console) if os.path.exists('/tmp/imcsdk_debug'): enable_file_logging() __author__ = 'Cisco Systems' __email__ = 'ucs-python@cisco.com' __version__ = '0.9.3.1'
ragupta-git/ImcSdk
imcsdk/__init__.py
Python
apache-2.0
1,616
# Erophila simplex Winge SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
mdoering/backbone
life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Draba/Draba verna/ Syn. Erophila simplex/README.md
Markdown
apache-2.0
179
object Main extends App { println("Hello!") }
andremccarv/rgraph
src/main/scala/Main.scala
Scala
apache-2.0
50
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.scope; import javax.annotation.Nonnull; /** * A listener interfaces that is invoked before a scope is destroyed. If an * object implementing this interface is added into a scope, this destruction * method is automatically called! * * @author Philip Helger */ public interface IScopeDestructionAware { /** * Called before the owning scope is destroyed. You may perform some last * actions before the scope is really destroyed. This method is called after * the <code>IScope.preDestroy()</code> callback is invoked and before the * scope is set as being "in destruction". * * @param aScopeToBeDestroyed * The scope that will be destroyed. Never <code>null</code>. * @throws Exception * in case of an error */ default void onBeforeScopeDestruction (@Nonnull final IScope aScopeToBeDestroyed) throws Exception {} /** * Called when the owning scope is destroyed. You may perform some cleanup * work in here. This is method is called when the scope is already "in * destruction". * * @param aScopeInDestruction * The scope in destruction. Never <code>null</code>. * @throws Exception * in case of an error */ default void onScopeDestruction (@Nonnull final IScope aScopeInDestruction) throws Exception {} }
phax/ph-commons
ph-scopes/src/main/java/com/helger/scope/IScopeDestructionAware.java
Java
apache-2.0
1,983
/** * Package: MAG - VistA Imaging WARNING: Per VHA Directive 2004-038, this routine should not be modified. Date Created: May 11, 2010 Site Name: Washington OI Field Office, Silver Spring, MD Developer: vhaiswwerfej Description: ;; +--------------------------------------------------------------------+ ;; Property of the US Government. ;; No permission to copy or redistribute this software is given. ;; Use of unreleased versions of this software requires the user ;; to execute a written test agreement with the VistA Imaging ;; Development Office of the Department of Veterans Affairs, ;; telephone (301) 734-0100. ;; ;; The Food and Drug Administration classifies this software as ;; a Class II medical device. As such, it may not be changed ;; in any way. Modifications to this software may result in an ;; adulterated medical device under 21CFR820, the use of which ;; is considered to be a violation of US Federal Statutes. ;; +--------------------------------------------------------------------+ */ package gov.va.med.imaging.federation.storage; import java.io.IOException; import java.io.InputStream; import gov.va.med.imaging.exchange.storage.ByteBufferBackedInputStream; /** * Extends ByteBufferBackedInputStream and returns false for isCloseInputStreamWhenReadComplete() so the input * stream is not closed when the read is complete. This is necessary because the input stream is the zip stream * and there may be more files in the zip stream to read. This should only be used when the input stream is a * zip stream * * @author vhaiswwerfej * */ public class FederationZipByteBufferBackedInputStream extends ByteBufferBackedInputStream { public FederationZipByteBufferBackedInputStream(InputStream inputStream, int size, boolean readIntoBuffer, String providedChecksum) throws IOException { super(inputStream, size, readIntoBuffer, providedChecksum); } @Override protected boolean isCloseInputStreamWhenReadComplete() { return false; } }
VHAINNOVATIONS/Telepathology
Source/Java/FederationDataSourceProvider/main/src/java/gov/va/med/imaging/federation/storage/FederationZipByteBufferBackedInputStream.java
Java
apache-2.0
2,124
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_27) on Tue Mar 26 08:27:27 EDT 2013 --> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <TITLE> org.apache.solr.util.xslt Class Hierarchy (Solr 4.2.1 API) </TITLE> <META NAME="date" CONTENT="2013-03-26"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.solr.util.xslt Class Hierarchy (Solr 4.2.1 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/solr/util/stats/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/solr/util/xslt/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package org.apache.solr.util.xslt </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL> <LI TYPE="circle">org.apache.solr.util.xslt.<A HREF="../../../../../org/apache/solr/util/xslt/TransformerProvider.html" title="class in org.apache.solr.util.xslt"><B>TransformerProvider</B></A></UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../../org/apache/solr/util/stats/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/solr/util/xslt/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> <i>Copyright &copy; 2000-2013 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </BODY> </HTML>
jacquehettel/hugo_solr
docs/solr-core/org/apache/solr/util/xslt/package-tree.html
HTML
apache-2.0
6,723
// package store provides typed, centralized access to the event-sourced workflow and invocation models package store import ( "errors" "fmt" "github.com/fission/fission-workflows/pkg/fes" "github.com/fission/fission-workflows/pkg/types" "github.com/fission/fission-workflows/pkg/util/labels" "github.com/fission/fission-workflows/pkg/util/pubsub" ) type Workflows struct { fes.CacheReader // Currently needed for pubsub publisher interface, should be exposed here } func NewWorkflowsStore(workflows fes.CacheReader) *Workflows { return &Workflows{ workflows, } } // GetWorkflow returns an event-sourced workflow. // If an error occurred the error is returned, if no workflow was found both return values are nil. func (s *Workflows) GetWorkflow(workflowID string) (*types.Workflow, error) { key := fes.Aggregate{Type: types.TypeWorkflow, Id: workflowID} entity, err := s.GetAggregate(key) if err != nil { return nil, err } if entity == nil { return nil, nil } wf, ok := entity.(*types.Workflow) if !ok { panic(fmt.Sprintf("aggregate type mismatch for key %s (expected: %T, got %T)", key.Format(), &types.Workflow{}, wf)) } return wf, nil } // GetWorkflowNotifications returns a subscription to the updates of the workflow cache. // Returns nil if the cache does not support pubsub. // // Future: Currently this assumes the presence of a pubsub.Publisher interface in the cache. // In the future we can fallback to pull-based mechanisms func (s *Workflows) GetWorkflowUpdates() *WorkflowSubscription { selector := labels.In(fes.PubSubLabelAggregateType, types.TypeWorkflow) workflowPub, ok := s.CacheReader.(pubsub.Publisher) if !ok { return nil } sub := &WorkflowSubscription{ Subscription: workflowPub.Subscribe(pubsub.SubscriptionOptions{ Buffer: fes.DefaultNotificationBuffer, LabelMatcher: selector, }), } sub.closeFn = func() error { return workflowPub.Unsubscribe(sub.Subscription) } return sub } type Invocations struct { fes.CacheReader } func NewInvocationStore(invocations fes.CacheReader) *Invocations { return &Invocations{ invocations, } } // GetInvocation returns an event-sourced invocation. // If an error occurred the error is returned, if no invocation was found both return values are nil. func (s *Invocations) GetInvocation(invocationID string) (*types.WorkflowInvocation, error) { key := fes.Aggregate{Type: types.TypeInvocation, Id: invocationID} entity, err := s.GetAggregate(key) if err != nil { return nil, err } if entity == nil { return nil, nil } wfi, ok := entity.(*types.WorkflowInvocation) if !ok { panic(fmt.Sprintf("aggregate type mismatch for key %s (expected: %T, got %T - %v)", key.Format(), &types.WorkflowInvocation{}, wfi, wfi)) } return wfi, nil } // GetInvocationSubscription returns a subscription to the updates of the invocation cache. // Returns nil if the cache does not support pubsub. // // Future: Currently this assumes the presence of a pubsub.Publisher interface in the cache. // In the future we can fallback to pull-based mechanisms func (s *Invocations) GetInvocationUpdates() *InvocationSubscription { selector := labels.In(fes.PubSubLabelAggregateType, types.TypeInvocation, types.TypeTaskRun) invocationPub, ok := s.CacheReader.(pubsub.Publisher) if !ok { return nil } sub := &InvocationSubscription{ Subscription: invocationPub.Subscribe(pubsub.SubscriptionOptions{ Buffer: fes.DefaultNotificationBuffer, LabelMatcher: selector, }), } sub.closeFn = func() error { return invocationPub.Unsubscribe(sub.Subscription) } return sub } type WorkflowSubscription struct { *pubsub.Subscription closeFn func() error } func (sub *WorkflowSubscription) ToNotification(msg pubsub.Msg) (*fes.Notification, error) { update, ok := msg.(*fes.Notification) if !ok { return nil, errors.New("received message is not a notification") } return update, nil } func (sub *WorkflowSubscription) Close() error { if sub.closeFn == nil { return nil } return sub.closeFn() } type InvocationSubscription struct { *pubsub.Subscription closeFn func() error } func (sub *InvocationSubscription) ToNotification(msg pubsub.Msg) (*fes.Notification, error) { update, ok := msg.(*fes.Notification) if !ok { return nil, errors.New("received message is not a notification") } return update, nil } func (sub *InvocationSubscription) Close() error { if sub.closeFn == nil { return nil } return sub.closeFn() } func ParseNotificationToWorkflow(update *fes.Notification) (*types.Workflow, error) { entity, ok := update.Updated.(*types.Workflow) if !ok { return nil, errors.New("received message does not include workflow invocation as payload") } return entity, nil } func ParseNotificationToInvocation(update *fes.Notification) (*types.WorkflowInvocation, error) { entity, ok := update.Updated.(*types.WorkflowInvocation) if !ok { return nil, errors.New("received message does not include workflow invocation as payload") } return entity, nil }
fission/fission-workflows
pkg/api/store/store.go
GO
apache-2.0
5,038
package com.taobao.ustore.repo.hbase; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class RowCoderSample3 extends AbstractRowCoder { public RowCoderSample3(TablePhysicalSchema schema){ super(schema); } @Override public Map<String, Object> decodeRowKey(byte[] rowKey) { String rowKeyStr[] = new String(rowKey).split("\4"); String host; String type; String url; Date gmt_create = null; host = rowKeyStr[0]; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { gmt_create = sdf.parse(rowKeyStr[1]); } catch (ParseException e) { } type = rowKeyStr[2]; url = rowKeyStr[3]; Map<String, Object> rowKeyColumnValues = new HashMap(); rowKeyColumnValues.put("HOST", host); rowKeyColumnValues.put("URL", url); rowKeyColumnValues.put("TYPE", type); rowKeyColumnValues.put("GMT_CREATE", gmt_create); return rowKeyColumnValues; } @Override public byte[] encodeRowKey(Map<String, Object> rowKeyColumnValues) { StringBuilder rowKeyStr = new StringBuilder(); String host = (String) rowKeyColumnValues.get("HOST"); Date gmt_create = (Date) rowKeyColumnValues.get("GMT_CREATE"); String type = (String) rowKeyColumnValues.get("TYPE"); String url = (String) rowKeyColumnValues.get("URL"); if (host != null) rowKeyStr.append(host); else rowKeyStr.append('\0'); rowKeyStr.append((char) 4); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String gmt_create_str = sdf.format(gmt_create); if (gmt_create != null) rowKeyStr.append(gmt_create_str); else rowKeyStr.append('\0'); rowKeyStr.append((char) 4); if (type != null) rowKeyStr.append(type); else rowKeyStr.append('\0'); rowKeyStr.append((char) 4); if (url != null) rowKeyStr.append(url); else rowKeyStr.append('\0'); return rowKeyStr.toString().getBytes(); } }
xloye/tddl5
tddl-repo-hbase/src/main/java/com/taobao/ustore/repo/hbase/RowCoderSample3.java
Java
apache-2.0
2,181
/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> extern "C" { #include "media/aeron_udp_channel_transport.h" #include "media/aeron_udp_channel_transport_loss.h" #include "protocol/aeron_udp_protocol.h" #if !defined(HAVE_STRUCT_MMSGHDR) struct mmsghdr { struct msghdr msg_hdr; unsigned int msg_len; }; #endif } #define TEMP_URL_LEN (128) class UdpChannelTransportLossTest : public testing::Test { public: UdpChannelTransportLossTest() = default; }; typedef struct delegate_recv_state_stct { int messages_received; int bytes_received; } delegate_recv_state_t; void aeron_udp_channel_interceptor_loss_incoming_delegate( void *interceptor_state, aeron_udp_channel_incoming_interceptor_t *delegate, aeron_udp_channel_transport_t *transport, void *receiver_clientd, void *endpoint_clientd, void *destination_clientd, uint8_t *buffer, size_t length, struct sockaddr_storage *addr) { auto *state = (delegate_recv_state_t *)interceptor_state; state->messages_received++; state->bytes_received += (int)length; } TEST_F(UdpChannelTransportLossTest, shouldDiscardAllPacketsWithRateOfOne) { uint16_t msg_type = AERON_HDR_TYPE_DATA; aeron_udp_channel_incoming_interceptor_t delegate; delegate_recv_state_t delegate_recv_state = { 0, 0 }; aeron_udp_channel_interceptor_loss_params_t params; uint8_t data_0[1024]; uint8_t data_1[1024]; aeron_frame_header_t *frame_header; frame_header = (aeron_frame_header_t *)(data_0); frame_header->type = msg_type; frame_header = (aeron_frame_header_t *)(data_1); frame_header->type = msg_type; params.rate = 1.0; params.recv_msg_type_mask = 1U << msg_type; params.seed = 0; delegate.incoming_func = aeron_udp_channel_interceptor_loss_incoming_delegate; delegate.interceptor_state = &delegate_recv_state; aeron_udp_channel_interceptor_loss_configure(&params); aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data_0, 1024, nullptr); aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data_1, 1024, nullptr); EXPECT_EQ(delegate_recv_state.messages_received, 0); } TEST_F(UdpChannelTransportLossTest, shouldNotDiscardAllPacketsWithRateOfOneWithDifferentMessageType) { uint16_t loss_msg_type = AERON_HDR_TYPE_DATA; uint16_t data_msg_type = AERON_HDR_TYPE_SETUP; aeron_udp_channel_incoming_interceptor_t delegate; delegate_recv_state_t delegate_recv_state = { 0, 0 }; aeron_udp_channel_interceptor_loss_params_t params; uint8_t data_0[1024]; uint8_t data_1[1024]; aeron_frame_header_t *frame_header; frame_header = (aeron_frame_header_t *)(data_0); frame_header->type = data_msg_type; frame_header = (aeron_frame_header_t *)(data_1); frame_header->type = data_msg_type; params.rate = 1.0; params.recv_msg_type_mask = 1U << loss_msg_type; params.seed = 0; delegate.incoming_func = aeron_udp_channel_interceptor_loss_incoming_delegate; delegate.interceptor_state = &delegate_recv_state; aeron_udp_channel_interceptor_loss_configure(&params); aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data_0, 1024, nullptr); aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data_1, 1024, nullptr); EXPECT_EQ(delegate_recv_state.messages_received, 2); } TEST_F(UdpChannelTransportLossTest, shouldNotDiscardAllPacketsWithRateOfZero) { uint16_t loss_msg_type = AERON_HDR_TYPE_DATA; aeron_udp_channel_incoming_interceptor_t delegate; delegate_recv_state_t delegate_recv_state = { 0, 0 }; aeron_udp_channel_interceptor_loss_params_t params; uint8_t data_0[1024]; uint8_t data_1[1024]; aeron_frame_header_t *frame_header; frame_header = (aeron_frame_header_t *)(data_0); frame_header->type = loss_msg_type; frame_header = (aeron_frame_header_t *)(data_1); frame_header->type = loss_msg_type; params.rate = 0.0; params.recv_msg_type_mask = 1U << loss_msg_type; params.seed = 0; delegate.incoming_func = aeron_udp_channel_interceptor_loss_incoming_delegate; delegate.interceptor_state = &delegate_recv_state; aeron_udp_channel_interceptor_loss_configure(&params); aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data_0, 1024, nullptr); aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data_1, 1024, nullptr); EXPECT_EQ(delegate_recv_state.messages_received, 2); } TEST_F(UdpChannelTransportLossTest, shouldDiscardRoughlyHalfTheMessages) { uint16_t msg_type = AERON_HDR_TYPE_DATA; aeron_udp_channel_incoming_interceptor_t delegate; delegate_recv_state_t delegate_recv_state = { 0, 0 }; aeron_udp_channel_interceptor_loss_params_t params; aeron_frame_header_t *frame_header; const size_t vlen = 10; uint8_t data[vlen * 1024]; params.rate = 0.5; params.recv_msg_type_mask = 1U << msg_type; params.seed = 23764; delegate.incoming_func = aeron_udp_channel_interceptor_loss_incoming_delegate; delegate.interceptor_state = &delegate_recv_state; aeron_udp_channel_interceptor_loss_configure(&params); for (size_t i = 0; i < vlen; i++) { frame_header = (aeron_frame_header_t *)(data + (i * 1024)); frame_header->type = msg_type; aeron_udp_channel_interceptor_loss_incoming( nullptr, &delegate, nullptr, nullptr, nullptr, nullptr, data + (i * 1024), 1024, nullptr); } EXPECT_LT(delegate_recv_state.messages_received, static_cast<int>(vlen)); EXPECT_GT(delegate_recv_state.messages_received, 0); EXPECT_LT(delegate_recv_state.bytes_received, static_cast<int64_t>(vlen * 1024)); EXPECT_GT(delegate_recv_state.bytes_received, 0); EXPECT_EQ(delegate_recv_state.messages_received, 6); } TEST_F(UdpChannelTransportLossTest, shouldParseAllParams) { char uri[TEMP_URL_LEN]; aeron_udp_channel_interceptor_loss_params_t params; strncpy(uri, "rate=0.20|seed=10|recv-msg-mask=0xF", TEMP_URL_LEN); int i = aeron_udp_channel_interceptor_loss_parse_params(uri, &params); EXPECT_EQ(i, 0); EXPECT_EQ(params.rate, 0.2); EXPECT_EQ(params.seed, 10ull); EXPECT_EQ(params.recv_msg_type_mask, 0xFul); } TEST_F(UdpChannelTransportLossTest, shouldFailOnInvalidRate) { char uri[TEMP_URL_LEN]; aeron_udp_channel_interceptor_loss_params_t params; strncpy(uri, "rate=abc", TEMP_URL_LEN); int i = aeron_udp_channel_interceptor_loss_parse_params(uri, &params); EXPECT_EQ(i, -1); } TEST_F(UdpChannelTransportLossTest, shouldFailOnInvalidSeed) { char uri[TEMP_URL_LEN]; aeron_udp_channel_interceptor_loss_params_t params; strncpy(uri, "seed=abc", TEMP_URL_LEN); int i = aeron_udp_channel_interceptor_loss_parse_params(uri, &params); EXPECT_EQ(i, -1); } TEST_F(UdpChannelTransportLossTest, shouldFailOnInvalidRecvMsgMask) { char uri[TEMP_URL_LEN]; aeron_udp_channel_interceptor_loss_params_t params; strncpy(uri, "recv-msg-mask=zzz", TEMP_URL_LEN); int i = aeron_udp_channel_interceptor_loss_parse_params(uri, &params); EXPECT_EQ(i, -1); }
real-logic/Aeron
aeron-driver/src/test/c/media/aeron_udp_channel_transport_loss_test.cpp
C++
apache-2.0
8,010
/****************************************************************************** * Copyright 2011 Kitware Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef __ButtonLineEdit_H #define __ButtonLineEdit_H #include <QWidget> #include <QLineEdit> #include <QPushButton> #include "MidasResourceDescTable.h" class MidasItemTreeItem; class ButtonEditUI; class ButtonLineEdit : public QWidget { Q_OBJECT public: ButtonLineEdit(MidasItemTreeItem* item, MIDASFields field, ButtonEditUI* handler, QWidget* parent = 0, std::string text = "Add"); ~ButtonLineEdit(); QString getData(); void setData(const QString& value); public slots: void appendText(const QString& text); protected: QLineEdit* m_TextEdit; QPushButton* m_AddButton; MIDASFields m_Field; MidasItemTreeItem* m_Item; }; #endif
cpatrick/MidasClient
Libs/Widgets/GUI/ButtonLineEdit.h
C
apache-2.0
1,434
#ifndef GETOPT_H #define GETOPT_H /* include files needed by this include file */ /* macros defined by this include file */ #define no_argument 0 #define REQUIRED_ARG 1 #define OPTIONAL_ARG 2 /* types defined by this include file */ /* GETOPT_LONG_OPTION_T: The type of long option */ typedef struct GETOPT_LONG_OPTION_T { char *name; /* the name of the long option */ int has_arg; /* one of the above macros */ int *flag; /* determines if getopt_long() returns a * value for a long option; if it is * non-NULL, 0 is returned as a function * value and the value of val is stored in * the area pointed to by flag. Otherwise, * val is returned. */ int val; /* determines the value to return if flag is * NULL. */ } GETOPT_LONG_OPTION_T; typedef GETOPT_LONG_OPTION_T option; #ifdef __cplusplus extern "C" { #endif /* externally-defined variables */ extern char *optarg; extern int optind; extern int opterr; extern int optopt; /* function prototypes */ int getopt (int argc, char **argv, char *optstring); int getopt_long (int argc, char **argv, char *shortopts, GETOPT_LONG_OPTION_T * longopts, int *longind); int getopt_long_only (int argc, char **argv, char *shortopts, GETOPT_LONG_OPTION_T * longopts, int *longind); #ifdef __cplusplus }; #endif #endif /* GETOPT_H */ /* END OF FILE getopt.h */
berkus/ninja
src/getopt.h
C
apache-2.0
1,661
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select # Configure the baseURL baseUrl = "https://www.expedia.es" # Create a webDriver instance and maximize window driver = webdriver.Firefox() driver.maximize_window() # Navigage to URL and put a 10 seconds implicit wait driver.get(baseUrl) driver.implicitly_wait(10) # Find and click on element "Flights" # Find departure textbox and type "Barcelona" # Find departure textbox and type "Madrid" # Find departure time and type "23/11/2017" # Close Calendar # Find the "Find" button and click on # Quit driver
twiindan/selenium_lessons
04_Selenium/exercices/expedia.py
Python
apache-2.0
654
# # Cookbook Name:: opscode-ci-piab # Recipe:: base # # Copyright 2009, Opscode, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # include_recipe "erlang_binary" include_recipe "runit" execute "add_opscode_gemrepo" do not_if "gem sources --list | grep gems.opscode.com" command "gem sources --add http://gems.opscode.com" end # update rubygems if < 1.3.6 bash "upgrade to rubygems 1.3.6" do user "root" cwd "/tmp" not_if { (Gem::Version.new(Gem::VERSION) <=> Gem::Version.new("1.3.6")) >= 0 } code <<-EOH wget http://rubyforge.org/frs/download.php/69365/rubygems-1.3.6.tgz tar xvf rubygems-1.3.6.tgz cd rubygems-1.3.6 ruby setup.rb --no-format-executable EOH end group "opscode" do gid 5049 end user "opscode" do comment "Opscode User" shell "/bin/sh" uid 5049 gid 5049 end directory "/home/opscode" do mode 0755 owner "opscode" group "opscode" end directory "/home/opscode/.ssh" do mode 0700 owner "opscode" group "opscode" end include_recipe "opscode-github" directory "/etc/opscode" do mode 0770 owner "root" group "opscode" end cookbook_file "/etc/opscode/webui_pub.pem" do source "webui_pub.pem" owner "opscode" group "opscode" mode "0600" end # Prepare the audit directory directory "/var/spool/opscode" do owner "opscode" group "opscode" mode "0770" end directory "/var/spool/opscode/audit" do owner "opscode" group "opscode" mode "0770" end package "libxml2" package "libxml2-dev" package "libsqlite3-dev" package "libxslt1-dev" package "libxml-simple-ruby" # These GEM's are used for chef-server and others, but not needed for # other packages like opscode-chef or opscode-account, as they use # bundler. gems = { # TODO: tim, 2011/3/28: mixlib-authorization still requires rspec 1.3.0 'rspec' => ['2.5.0', '1.3.0'], 'gemcutter' => '0.6.1', 'jeweler' => '1.4.0', 'cucumber' => '0.8.5', 'ci_reporter' => '1.6.4', 'bunny' => '0.6.0', 'moneta' => '0.6.0', 'uuidtools' => '2.1.1', 'merb-slices' => '1.1.3', 'merb-assets' => '1.1.3', 'merb-helpers' => '1.1.3', 'merb-haml' => '1.1.3', 'merb-param-protection' => '1.1.3', 'treetop' => '1.4.9', 'unicorn' => '2.0.1', 'fog' => '0.2.30', 'dep_selector' => nil, # opscode-authz cukes 'couchrest' => '0.23', # mixlib-authorization spec 'uuid' => '2.3.1', 'yajl-ruby' => '0.7.8', } gem_dir = Dir['/srv/localgems/gems/*'] gems.each do |name,versions| Array(versions).flatten.each do |version| have_version = if version gem_dir.find{|d|d=~/\/#{name}-#{version}/} else gem_dir.find{|d|d=~/\/#{name}-/} end unless have_version script "install_localgems_#{name}" do interpreter "bash" user "root" code <<-EOH export GEM_HOME=/srv/localgems export GEM_PATH=/srv/localgems export PATH="/srv/localgems/bin:$PATH" gem install #{name} #{version.nil? ? '' : "--version #{version}"} EOH end end end end # Specs are run directly against these. Also, chef-server needs # them. We will install into /srv/#{gemname}, as well as # /srv/localgems opscode_gems = [ "mixlib-log", "mixlib-cli", "mixlib-config", "mixlib-authentication", "mixlib-authorization", "mixlib-localization", "ohai", "couchrest", "aws-s3" ] opscode_gems.each do |name| ["/srv/#{name}", "/srv/#{name}/shared", "/srv/#{name}/shared/cached-copy"].each do |dirname| directory dirname do owner "root" group "root" mode "0775" end end deploy_revision "gem-#{name}-src" do revision (node[:environment]["#{name}-revision"] || node[:environment]['default-revision']) repository 'git@github.com:' + (node[:environment]["#{name}-remote"] || node[:environment]['default-remote']) + "/#{name}.git" remote (node[:environment]["#{name}-remote"] || node[:environment]['default-remote']) symlink_before_migrate Hash.new deploy_to "/srv/#{name}" user "root" group "root" migrate false before_symlink do bash "install_#{name}_local" do user "root" cwd "#{release_path}" code <<-EOH export GEM_HOME=/srv/localgems export GEM_PATH=/srv/localgems export PATH=/srv/localgems/bin:$PATH rake repackage || rake build gem install pkg/*.gem EOH end end end end
chef/opscode-test
continuous-integration/environments/opscode-ci/cookbooks/opscode-base/recipes/default.rb
Ruby
apache-2.0
4,952