code
stringlengths 10
749k
| repo_name
stringlengths 5
108
| path
stringlengths 7
333
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 10
749k
|
---|---|---|---|---|---|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jtex.plot;
/**
*
* @author hios
*/
public interface ScatterCanvas {
public ScatterOptions getScatterOptions();
public void setScatterOptions(ScatterOptions options);
}
|
luttero/Maud
|
src/com/jtex/plot/ScatterCanvas.java
|
Java
|
bsd-3-clause
| 380 |
/**
* CArtAgO - DEIS, University of Bologna
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package cartago;
/**
* Unique identifier of an operation (instance)
* executed by an artifact
*
* @author aricci
*
*/
public class OpId implements java.io.Serializable {
private int id;
private ArtifactId aid;
private AgentId agentId;
private String opName;
OpId(ArtifactId aid, String opName, int id, AgentId ctxId){
this.id = id;
this.aid = aid;
this.agentId = ctxId;
this.opName = opName;
}
/**
* Get the numeric identifier of the operation id
*
* @return
*/
public int getId(){
return id;
}
/**
* Get the operation name.
*
* @return
*/
public String getOpName(){
return opName;
}
/**
* Get the id of the artifact where the operation has been executed
*
* @return
*/
public ArtifactId getArtifactId(){
return aid;
}
/**
* Get the identifier of the agent performer of the operation
*
* @return
*/
public AgentId getAgentBodyId(){
return agentId;
}
AgentId getContextId(){
return agentId;
}
public boolean equals(Object obj){
return aid.equals(((OpId)obj).aid) && ((OpId)obj).id==id;
}
public String toString(){
return "opId("+id+","+opName+","+aid+","+agentId+")";
}
}
|
lsa-pucrs/jason-ros-releases
|
cartago-2.0.1/src/main/cartago/OpId.java
|
Java
|
bsd-3-clause
| 2,026 |
package team.gif;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.DigitalIOButton;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import team.gif.commands.*;
public class OI {
public static final Joystick leftStick = new Joystick(1);
public static final rightStick = new Joystick(2);
public static final auxStick = new Joystick(3);
private final Button leftTrigger = new JoystickButton(leftStick, 1);
private final Button right2 = new JoystickButton(rightStick, 2);
private final Button right3 = new JoystickButton(rightStick, 3);
private final Button right6 = new JoystickButton(rightStick, 6);
private final Button right7 = new JoystickButton(rightStick, 7);
public static final Button auxTrigger = new JoystickButton(rightStick, 1);
public OI() {
leftTrigger.whileHeld(new ShifterHigh());
right2.whileHeld(new CollectorReceive());
right2.whenPressed(new EarsOpen());
right3.whileHeld(new CollectorPass());
right3.whenPressed(new EarsOpen());
right3.whenReleased(new CollectorStandby());
right3.whenReleased(new EarsClosed());
right6.whileHeld(new BumperUp());
right7.whileHeld(new CollectorRaise());
}
}
|
Team2338/Fumper
|
src/team/gif/OI.java
|
Java
|
bsd-3-clause
| 1,352 |
/*
* Copyright Ekagra and SemanticBits, LLC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/clinical-connector/LICENSE.txt for details.
*/
package gov.nih.nci.cdmsconnector.c3d.service.globus.resource;
import gov.nih.nci.cdmsconnector.c3d.common.C3DGridServiceConstants;
import gov.nih.nci.cdmsconnector.c3d.stubs.C3DGridServiceResourceProperties;
import org.apache.axis.components.uuid.UUIDGen;
import org.apache.axis.components.uuid.UUIDGenFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.globus.wsrf.InvalidResourceKeyException;
import org.globus.wsrf.PersistenceCallback;
import org.globus.wsrf.Resource;
import org.globus.wsrf.ResourceException;
import org.globus.wsrf.ResourceKey;
import org.globus.wsrf.ResourceContext;
import gov.nih.nci.cagrid.introduce.servicetools.SingletonResourceHomeImpl;
import org.globus.wsrf.jndi.Initializable;
/**
* DO NOT EDIT: This class is autogenerated!
*
* This class implements the resource home for the resource type represented
* by this service.
*
* @created by Introduce Toolkit version 1.2
*
*/
public class C3DGridServiceResourceHome extends SingletonResourceHomeImpl implements Initializable {
static final Log logger = LogFactory.getLog(C3DGridServiceResourceHome.class);
private static final UUIDGen UUIDGEN = UUIDGenFactory.getUUIDGen();
public Resource createSingleton() {
logger.info("Creating a single resource.");
try {
C3DGridServiceResourceProperties props = new C3DGridServiceResourceProperties();
C3DGridServiceResource resource = new C3DGridServiceResource();
if (resource instanceof PersistenceCallback) {
//try to load the resource if it was persisted
try{
((PersistenceCallback) resource).load(null);
} catch (InvalidResourceKeyException ex){
//persisted singleton resource was not found so we will just create a new one
resource.initialize(props, C3DGridServiceConstants.RESOURCE_PROPERTY_SET, UUIDGEN.nextUUID());
}
} else {
resource.initialize(props, C3DGridServiceConstants.RESOURCE_PROPERTY_SET, UUIDGEN.nextUUID());
}
return resource;
} catch (Exception e) {
logger.error("Exception when creating the resource",e);
return null;
}
}
public Resource find(ResourceKey key) throws ResourceException {
C3DGridServiceResource resource = (C3DGridServiceResource) super.find(key);
return resource;
}
/**
* Initialze the singleton resource, when the home is initialized.
*/
public void initialize() throws Exception {
logger.info("Attempting to initialize resource.");
Resource resource = find(null);
if (resource == null) {
logger.error("Unable to initialize resource!");
} else {
logger.info("Successfully initialized resource.");
}
}
/**
* Get the resouce that is being addressed in this current context
*/
public C3DGridServiceResource getAddressedResource() throws Exception {
C3DGridServiceResource thisResource;
thisResource = (C3DGridServiceResource) ResourceContext.getResourceContext().getResource();
return thisResource;
}
}
|
NCIP/clinical-connector
|
software/C3DGridService/src/gov/nih/nci/cdmsconnector/c3d/service/globus/resource/C3DGridServiceResourceHome.java
|
Java
|
bsd-3-clause
| 3,275 |
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
*******************************************************************************/
package org.caleydo.view.relationshipexplorer.ui.collection;
import java.util.HashSet;
import java.util.Set;
import org.caleydo.core.data.datadomain.ATableBasedDataDomain;
import org.caleydo.core.data.perspective.table.TablePerspective;
import org.caleydo.core.data.perspective.variable.Perspective;
import org.caleydo.core.data.virtualarray.VirtualArray;
import org.caleydo.core.id.IDCategory;
import org.caleydo.core.id.IDType;
import org.caleydo.view.relationshipexplorer.ui.ConTourElement;
import org.caleydo.view.relationshipexplorer.ui.collection.idprovider.IElementIDProvider;
import org.caleydo.view.relationshipexplorer.ui.column.factory.ColumnFactories;
import org.caleydo.view.relationshipexplorer.ui.column.factory.IColumnFactory;
import org.caleydo.view.relationshipexplorer.ui.detail.parcoords.ParallelCoordinatesDetailViewFactory;
import com.google.common.collect.Sets;
/**
* @author Christian
*
*/
public class TabularDataCollection extends AEntityCollection {
protected final ATableBasedDataDomain dataDomain;
protected final IDCategory itemIDCategory;
protected final TablePerspective tablePerspective;
protected final IDType itemIDType;
protected final VirtualArray va;
protected final Perspective dimensionPerspective;
protected final IDType mappingIDType;
public TabularDataCollection(TablePerspective tablePerspective, IDCategory itemIDCategory,
IElementIDProvider elementIDProvider, ConTourElement relationshipExplorer) {
super(relationshipExplorer);
dataDomain = tablePerspective.getDataDomain();
this.itemIDCategory = itemIDCategory;
this.tablePerspective = tablePerspective;
this.mappingIDType = dataDomain.getDatasetDescriptionIDType(itemIDCategory);
if (dataDomain.getDimensionIDCategory() == itemIDCategory) {
va = tablePerspective.getDimensionPerspective().getVirtualArray();
itemIDType = tablePerspective.getDimensionPerspective().getIdType();
dimensionPerspective = tablePerspective.getRecordPerspective();
} else {
va = tablePerspective.getRecordPerspective().getVirtualArray();
itemIDType = tablePerspective.getRecordPerspective().getIdType();
dimensionPerspective = tablePerspective.getDimensionPerspective();
}
if (elementIDProvider == null)
elementIDProvider = getDefaultElementIDProvider(va);
allElementIDs.addAll(elementIDProvider.getElementIDs());
filteredElementIDs.addAll(allElementIDs);
setLabel(dataDomain.getLabel());
detailViewFactory = new ParallelCoordinatesDetailViewFactory();
}
@Override
public IDType getBroadcastingIDType() {
return itemIDType;
}
@Override
protected Set<Object> getBroadcastIDsFromElementID(Object elementID) {
return Sets.newHashSet(elementID);
}
@Override
protected Set<Object> getElementIDsFromBroadcastID(Object broadcastingID) {
return Sets.newHashSet(broadcastingID);
}
@Override
protected IColumnFactory getDefaultColumnFactory() {
return ColumnFactories.createDefaultTabularDataColumnFactory();
}
/**
* @return the dataDomain, see {@link #dataDomain}
*/
public ATableBasedDataDomain getDataDomain() {
return dataDomain;
}
/**
* @return the perspective, see {@link #dimensionPerspective}
*/
public Perspective getDimensionPerspective() {
return dimensionPerspective;
}
/**
* @return the itemIDCategory, see {@link #itemIDCategory}
*/
public IDCategory getItemIDCategory() {
return itemIDCategory;
}
/**
* @return the itemIDType, see {@link #itemIDType}
*/
public IDType getItemIDType() {
return itemIDType;
}
@Override
public IDType getMappingIDType() {
return mappingIDType;
}
/**
* @return the tablePerspective, see {@link #tablePerspective}
*/
public TablePerspective getTablePerspective() {
return tablePerspective;
}
/**
* @return the va, see {@link #va}
*/
public VirtualArray getVa() {
return va;
}
public static IElementIDProvider getDefaultElementIDProvider(final VirtualArray va) {
return new IElementIDProvider() {
@Override
public Set<Object> getElementIDs() {
return new HashSet<Object>(va.getIDs());
}
};
}
@Override
public String getText(Object elementID) {
return elementID.toString();
}
}
|
Caleydo/org.caleydo.view.contour
|
src/main/java/org/caleydo/view/relationshipexplorer/ui/collection/TabularDataCollection.java
|
Java
|
bsd-3-clause
| 4,540 |
/*
* TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
* Copyright (c) 2008, Nationwide Health Information Network (NHIN) Connect. All rights reserved.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* - Neither the name of the NHIN Connect Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* END OF TERMS AND CONDITIONS
*/
package gov.hhs.fha.nhinc.common.dda;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for GetDetailDataForUserRequestType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="GetDetailDataForUserRequestType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="userId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="dataSource" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="itemId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GetDetailDataForUserRequestType", propOrder = {
"userId",
"dataSource",
"itemId"
})
public class GetDetailDataForUserRequestType {
@XmlElement(required = true)
protected String userId;
@XmlElement(required = true)
protected String dataSource;
@XmlElement(required = true)
protected String itemId;
/**
* Gets the value of the userId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUserId() {
return userId;
}
/**
* Sets the value of the userId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUserId(String value) {
this.userId = value;
}
/**
* Gets the value of the dataSource property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDataSource() {
return dataSource;
}
/**
* Sets the value of the dataSource property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDataSource(String value) {
this.dataSource = value;
}
/**
* Gets the value of the itemId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getItemId() {
return itemId;
}
/**
* Sets the value of the itemId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setItemId(String value) {
this.itemId = value;
}
}
|
TATRC/KMR2
|
Services/Common/XDSCommonLib/src/main/java/gov/hhs/fha/nhinc/common/dda/GetDetailDataForUserRequestType.java
|
Java
|
bsd-3-clause
| 4,397 |
/**
* Copyright (c) 2015 See AUTHORS file
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the mini2Dx nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.mini2Dx.core.di.exception;
/**
* A base class for bean exceptions
*/
public class BeanException extends Exception {
private static final long serialVersionUID = 4487528732406582847L;
public BeanException(String message) {
super(message);
}
}
|
hyperverse/mini2Dx
|
core/src/main/java/org/mini2Dx/core/di/exception/BeanException.java
|
Java
|
bsd-3-clause
| 1,761 |
/* CoAP on Moterunner Demonstration
* Copyright (c) 2013-2014, SAP AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the SAP AG nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SAP BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Contributors:
* Matthias Thoma
* Martin Zabel
* Theofilos Kakantousis
*
* The following things need to be added before any public release:
* 3. Consider to add TTL / Resend stuff (see hellosensor.java)
* 4. Have a look at rules for message id and consider to move it either here or to some generic class
*/
package com.sap.coap;
import com.ibm.saguaro.system.*;
import com.ibm.iris.*;
import com.ibm.saguaro.mrv6.*;
//##if LOGGING
import com.ibm.saguaro.logger.*;
//##endif
public class Message {
public byte[] header = new byte[4];
public byte[] token = null;
public byte[] payload = null;
public int payloadLength = 0;
public byte[] options;
public int optionArraySize = 0;
public int roundCounter = 0;
@Immutable public static final byte CON = 0x00;
@Immutable public static final byte NON = 0x01;
@Immutable public static final byte ACK = 0x02;
@Immutable public static final byte RST = 0x03;
@Immutable public static final byte EMPTY = 0x00;
@Immutable public static final byte GET = 0x01;
@Immutable public static final byte POST = 0x02;
@Immutable public static final byte PUT = 0x03;
@Immutable public static final byte DELETE = 0x04;
public final void setPayload(byte[] mypayload){
this.payload = mypayload;
this.payloadLength = mypayload.length;
}
public Message() {
header[0] = 0x40; // set the version number
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="type"> something </param>
/// <param name="tokenLen"> token legnth </param>
/// <param name="code"> CoAP message code </param>
/// <param name="msgid"> CoAP message id </param>
public Message(byte type, byte tokenLen, byte code, int msgid) {
setMessageHeader(type, tokenLen, code, msgid);
}
public final void setMessageHeader(byte type, byte tokenLen, byte code, int msgid) {
header[0] = (byte) ((0x40 | (type << 4)) | tokenLen);
header[1] = code;
Util.set16be(header,2,msgid);
}
public static byte createResponseCode(final byte cl, final byte cc) {
return (byte) ((cl << 5) | cc);
}
public final byte getVersion() {
return (byte) ((header[0] >>> 6) & 0x03);
}
public final byte getType() {
return (byte) ((header[0] & 0x30) >> 4);
}
public final void setType(final byte type) {
byte tl = (byte) (header [0] & 0x0F);
header[0] = (byte) ((0x40 | (type << 4)) | tl); // set the version number
}
public final byte getTokenLength() {
return (byte) (header[0] & 0x0F);
}
public final byte getCode() {
return header[1];
}
public final int getMessageId() {
return Util.get16be(header,2);
}
public final void clearOptions() {
options=null;
optionArraySize=0;
}
public final void clearPayload() {
payloadLength = 0;
payload = null;
}
public final byte[] getPayload() {
return this.payload;
}
public final int getPayloadSize() {
return this.payloadLength;
}
public byte[] getURIfromOptionArray() {
int partNo = 0;
int bufferOffset = 0;
int offset = getOffsetOfOptionWithId(11, partNo);
if (offset<0)
return null;
int bufferSize = 0;
// Calculate buffer size
int firstOffset = offset;
while (offset>=0) {
if (partNo>0)
bufferSize++;
int valueSize = getValueSizeOfOptionWithOffset(offset);
bufferSize += valueSize;
partNo++;
offset = getOffsetOfOptionWithId(11, partNo);
}
byte[] buffer = new byte[bufferSize];
partNo=0;
offset = getOffsetOfOptionWithId(11, partNo);
int valueSize = getValueSizeOfOptionWithOffset(offset);
byte[] data = getValueOfOptionWithOffset(offset);
while (data != null) {
if (partNo>0) {
buffer[bufferOffset]='/';
bufferOffset++;
}
partNo++;
Util.copyData(data, 0, buffer, bufferOffset, valueSize);
bufferOffset += valueSize;
offset = getOffsetOfOptionWithId(11, partNo);
data = null;
if (offset>=0) {
valueSize = getValueSizeOfOptionWithOffset(offset);
data = getValueOfOptionWithOffset(offset);
}
}
return buffer;
}
public boolean hasOption(int id) {
return (getOffsetOfOptionWithId(id,0) != -1);
}
public void insertOption(int id, byte[] value, int valueSize) {
//1. find position
// an ascending order of the options has to be kept
// find start offsets of the 'enclosing' options left and right of the one to insert
// special case: inserting at the beginning: offsetRightOption = 0
// special case: inserting at the end: offsetRightOption = optionArraySize (i.e. points behind the array)
int offsetRightOption = 0;
int idRightOption = 0;
int idLeftOption = 0;
while(offsetRightOption < optionArraySize) { //if the loop is not left by a break, the option has to be inserted at the end
idRightOption = idOfOptionWithOffset(options, offsetRightOption, idRightOption);
if(idRightOption > id) { //insertion point found
break;
}
idLeftOption = idRightOption;
offsetRightOption = findOffsetOfNextOption(options, offsetRightOption);
}
//2. calculate value length field size for this option
int optionExtendedLengthFieldSize = getExtendedOptionFieldSizeFor(valueSize);
//3. calculate delta value for this option.
// depends on the previous id (being 0 when no previous option exists)
int delta = id - idLeftOption;
//4. calculate delta field size for this option
int optionExtendedDeltaFieldSize = getExtendedOptionFieldSizeFor(delta);
//5. recalculate the delta field size for the next option
// the delta value for the next option decreases due to the insertion
// this may result in less bytes being used for the size field
int deltaFieldSizeRightOption = 0;
int deltaFieldSizeRightOptionNew = 0;
int deltaRightOptionNew = 0;
int extendedDeltaFieldSizeDifferenceRightOption = 0;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaFieldSizeRightOption = optionExtendedDeltaFieldSize(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = idRightOption - id;
deltaFieldSizeRightOptionNew = getExtendedOptionFieldSizeFor(deltaRightOptionNew);
//determine the size difference between the new and the old field
extendedDeltaFieldSizeDifferenceRightOption = deltaFieldSizeRightOption - deltaFieldSizeRightOptionNew;
}
//7. calculate total size of new option array
int optionArraySizeNew = optionArraySize
+ 1
+ optionExtendedLengthFieldSize
+ optionExtendedDeltaFieldSize
+ valueSize
- extendedDeltaFieldSizeDifferenceRightOption;
//8. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//9. copy options until insertion point to new array
if(offsetRightOption>0) {
Util.copyData(options, 0, optionsNew, 0, offsetRightOption);
}
int currentOffset = offsetRightOption; //next position to read from the old options where no additional option is present. points now to the header byte of the next option
int offsetFirstByte = offsetRightOption; //points to the header byte of the option to insert
int currentOffsetNew = offsetFirstByte+1; //next position to write in the new array (after the header byte of the option to insert)
//10. write delta
if(optionExtendedDeltaFieldSize == 1) {
optionsNew[offsetFirstByte] += 13 << 4;
optionsNew[currentOffsetNew] = (byte)(delta-13);
}
else if(optionExtendedDeltaFieldSize == 2) {
optionsNew[offsetFirstByte] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew, delta-269);
}
else { //optionExtendedDeltaFieldSize == 0
optionsNew[offsetFirstByte] += delta << 4;
}
currentOffsetNew += optionExtendedDeltaFieldSize;
//11. write value length
if(optionExtendedLengthFieldSize == 1) {
optionsNew[offsetFirstByte] += 13;
optionsNew[currentOffsetNew] = (byte)(valueSize-13);
}
else if(optionExtendedLengthFieldSize == 2) {
optionsNew[offsetFirstByte] += 14;
Util.set16(optionsNew, currentOffsetNew, valueSize-269);
}
else { //optionExtendedLengthFieldSize == 0
optionsNew[offsetFirstByte] += valueSize;
}
currentOffsetNew += optionExtendedLengthFieldSize;
//12. copy value
if(valueSize>0) {
Util.copyData(value, 0, optionsNew, currentOffsetNew, valueSize);
}
currentOffsetNew += valueSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//13. write header of next option with adjusted delta
//length stays constant, delta is erased
optionsNew[currentOffsetNew] = (byte) (options[currentOffset] & 0x0F);
//write recalculated delta to the next option
if(deltaFieldSizeRightOptionNew == 1) {
optionsNew[currentOffsetNew] += 13 << 4;
optionsNew[currentOffsetNew+1] = (byte) (deltaRightOptionNew-13);
}
else if(deltaFieldSizeRightOptionNew == 2){
optionsNew[currentOffsetNew] += 14 << 4;
Util.set16(optionsNew, currentOffsetNew+1, deltaRightOptionNew-269);
}
else { //deltaFieldSizeRightOptionNew == 0
optionsNew[currentOffsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
currentOffsetNew += 1+deltaFieldSizeRightOptionNew;
//jump behind the next option's extended delta field in the old array
currentOffset += 1+deltaFieldSizeRightOption;
//14. copy rest of array (= next option's extended value length field, next option's value, all subsequent options)
int restLength = optionArraySize - currentOffset;
Util.copyData(options, currentOffset, optionsNew, currentOffsetNew, restLength);
}
//15. replace old options by new
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public int getOffsetOfOptionWithId(int wantedOptionId, int matchNumber) {
int currentOptionOffset = 0;
int currentDelta = 0;
while(currentOptionOffset < optionArraySize) {
int currentOptionId = idOfOptionWithOffset(options, currentOptionOffset, currentDelta);
if(currentOptionId == wantedOptionId) { //first of the options has been found. iterate them until the right match number is found
for(int i = 0; i<matchNumber; i++) {
currentOptionOffset = findOffsetOfNextOption(options, currentOptionOffset);
if(currentOptionOffset == optionArraySize || (options[currentOptionOffset] & 0xF0) != 0x00) {
return -1; //array length has been exceeded or the delta is not 0, i.e. an option with an higher id was found
}
}
return currentOptionOffset;
}
if(currentOptionId > wantedOptionId) {
return -1;
}
currentDelta = currentOptionId;
currentOptionOffset = findOffsetOfNextOption(options, currentOptionOffset);
}
return -1;
}
public byte[] getValueOfOptionWithOffset(int offset) {
int valueSize = getValueSizeOfOptionWithOffset(options, offset);
int headerSize = headerSizeOfOptionWithOffset(options, offset);
offset += headerSize;
byte[] value = new byte[valueSize];
if(valueSize>0) {
Util.copyData(options, offset, value, 0, valueSize);
}
return value;
}
public int getValueSizeOfOptionWithOffset(int offset) {
return getValueSizeOfOptionWithOffset(options, offset);
}
public void removeOptionWithOffset(int offset) {
//1. get delta of this option
int delta = idOfOptionWithOffset(options, offset, 0); //this method with 0 as previous delta gives just the delta of this option
//2. get length of the block to remove
int optionSize = headerSizeOfOptionWithOffset(options, offset)
+ getValueSizeOfOptionWithOffset(options, offset);
//3. recalculate next option's new delta value
int offsetRightOption = offset + optionSize; //same as findOffsetOfNextOption(options, offset);
int deltaRightOption;
int deltaFieldSizeRightOption = 0;
int deltaRightOptionNew = 0;
int deltaFieldSizeRightOptionNew = 0;
int deltaFieldSizeDifferenceRightOption = 0;
if(offsetRightOption != optionArraySize) {
//get the old field size for the next option
deltaRightOption = idOfOptionWithOffset(options, offsetRightOption, 0); //this method with 0 as previous delta gives just the delta of this option
deltaFieldSizeRightOption = optionExtendedDeltaFieldSize(options, offsetRightOption);
//recalculate delta field size for next option
deltaRightOptionNew = delta + deltaRightOption;
deltaFieldSizeRightOptionNew = getExtendedOptionFieldSizeFor(deltaRightOptionNew);
//determine the size difference between the new and the old field
deltaFieldSizeDifferenceRightOption = deltaFieldSizeRightOptionNew - deltaFieldSizeRightOption;
}
//6. calculate new array size
int optionArraySizeNew = optionArraySize
- optionSize
+ deltaFieldSizeDifferenceRightOption;
//7. allocate mem for new option array
byte[] optionsNew = new byte[optionArraySizeNew];
//8. copy old option array to the start of the option to remove
if (offset>0)
Util.copyData(options, 0, optionsNew, 0, offset);
int offsetNew = offset;
offset += optionSize;
//only if a next option exists
if(offsetRightOption != optionArraySize) {
//9. write new delta for next option
//length stays constant, delta is erased
optionsNew[offsetNew] = (byte) (options[offset] & 0x0F);
//write recalculated delta to the next option
if(deltaFieldSizeRightOptionNew == 1) {
optionsNew[offsetNew] += 13 << 4;
optionsNew[offsetNew+1] = (byte) (deltaRightOptionNew-13);
}
else if(deltaFieldSizeRightOptionNew == 2){
optionsNew[offsetNew] += 14 << 4;
Util.set16(optionsNew, offsetNew+1, deltaRightOptionNew-269);
}
else { //deltaFieldSizeRightOptionNew == 0
optionsNew[offsetNew] += deltaRightOptionNew << 4;
}
//jump behind the next option's extended delta field delta in the new array
offsetNew += 1+deltaFieldSizeRightOptionNew;
//jump behind the next option's extended delta field in the old array
offset += 1+deltaFieldSizeRightOption;
//10. copy rest of the array
int restLength = optionArraySizeNew - offsetNew;
Util.copyData(options, offset, optionsNew, offsetNew, restLength);
}
options = optionsNew;
optionArraySize = optionArraySizeNew;
}
public void removeOptionWithId(int id, int matchNumber) {
int offset = getOffsetOfOptionWithId(id, matchNumber);
removeOptionWithOffset(offset);
}
public byte[] valueOfOptionWithId(int id, int no) {
int partNo = 0;
int offset = getOffsetOfOptionWithId(id, no);
if (offset>=0) {
int valueSize = getValueSizeOfOptionWithOffset(offset);
byte[] data = getValueOfOptionWithOffset(offset);
return data;
}
return null;
}
public int findOffsetOfNextOption(int offset) {
return findOffsetOfNextOption(this.options, offset);
}
public int idOfOptionWithOffset(int offset, int currentDelta) {
return idOfOptionWithOffset(this.options, offset, currentDelta);
}
public void encodeTo(byte[] buffer, int offset) {
int iOffset = 0;
Util.copyData(header, 0, buffer, offset, 4);
iOffset+=4;
byte tokenLength = this.getTokenLength();
if (tokenLength > 0) {
Util.copyData(token,0, buffer, offset+iOffset, tokenLength);
iOffset += tokenLength;
}
if (optionArraySize>0) {
Util.copyData(options, 0, buffer, offset+iOffset, optionArraySize);
iOffset += optionArraySize;
}
if (this.payloadLength!=0) {
buffer[offset+iOffset] = (byte) 0xFF;
iOffset++;
Util.copyData(this.payload,0, buffer, offset+iOffset, this.payloadLength);
}
}
//
// Return:
// 0: OK
// -1: Protocol error
// -2: Currently unsupported feature
public byte decode(byte[] inBuffer, int offset, int len) {
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: ENTER DECODE"));
Logger.flush(Mote.INFO);
//##endif
int inOffset = offset;
int endLen = offset+len;
payloadLength = 0;
Util.copyData(inBuffer, offset, header, 0, 4);
inOffset += 4;
// Read token
byte tokenLength = getTokenLength();
if(tokenLength > 8) {
return -1;
}
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: token len"));
Logger.appendInt(tokenLength);
Logger.flush(Mote.INFO);
//##endif
if (tokenLength>0) {
token = new byte[tokenLength];
Util.copyData(inBuffer, inOffset, token, 0, tokenLength);
}
inOffset += tokenLength;
// Check if end of Message
if (inOffset >= endLen) // Zero length Message, zero options
return 0;
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: start reading options "));
Logger.flush(Mote.INFO);
//##endif
// Check if payload marker or options
int optionOffset = inOffset;
inOffset = jumpOverOptions(inBuffer, inOffset, endLen);
if(inOffset == -1) {
return -1;
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: new offset"));
Logger.appendInt(inOffset);
Logger.appendString(csr.s2b("CoAPDecode :: endlen"));
Logger.appendInt(endLen);
Logger.flush(Mote.INFO);
//##endif
optionArraySize = inOffset - optionOffset; //may be 0 if no options are given
options = new byte[optionArraySize];
if(optionArraySize > 0) {
Util.copyData(inBuffer, optionOffset, options, 0, optionArraySize);
}
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: end reading options "));
Logger.flush(Mote.INFO);
//##endif
if (inOffset == endLen) { // Zero length Message
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: no payload "));
Logger.flush(Mote.INFO);
//##endif
return 0;
}
if (inBuffer[inOffset] == (byte) 0xFF) {
inOffset++;
if(inOffset == endLen) { //protocol error: there is no payload though the marker indicates
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
// Payload
payloadLength = endLen-inOffset;
payload = new byte[payloadLength];
Util.copyData(inBuffer, inOffset, payload, 0, payloadLength);
}
else {
inOffset++;
if(inOffset < endLen) { //protocol error: there is payload though there is no marker
//##if LOGGING
Logger.appendString(csr.s2b("CoAPDecode :: protocol error "));
Logger.flush(Mote.INFO);
//##endif
return -1;
}
}
return 0;
}
public final int getMessageLength() {
int len=4+getTokenLength();
if (this.payloadLength!=0)
len += 1+payloadLength;
len += optionArraySize;
return len;
}
public final Packet prepareResponseForSourcePacket(int inDstPort, byte[] inDstAddr, byte[] inSrcAddr, int srcPort) {
int dstport = inDstPort;
int lenp = getMessageLength();
Packet tempPacket = Mac.getPacket();
tempPacket.release();
Address.copyAddress(inDstAddr, 0, tempPacket.dstaddr, 0);
Address.copyAddress(inSrcAddr, 0, tempPacket.srcaddr, 0);
tempPacket.create(dstport, srcPort, lenp);
encodeTo(tempPacket.payloadBuf, tempPacket.payloadOff);
return tempPacket;
}
private static int jumpOverOptions(byte[] inBuffer, int offset, int len) {
int nextOptionOffset = offset;
while(nextOptionOffset < len && inBuffer[nextOptionOffset] != (byte) 0xFF) {
// checking for protocol violation -- one of the nibbles is F but it's not the payload marker
// check belongs only here since the first time parsing of a received message happens here
if( (inBuffer[offset] & 0x0F) == 0x0F || (inBuffer[offset] & 0xF0) == 0xF0 ) {
return -1;
}
nextOptionOffset = findOffsetOfNextOption(inBuffer, nextOptionOffset);
}
return nextOptionOffset;
}
private static int findOffsetOfNextOption(byte[] inBuffer, int offset) {
int headerSize = headerSizeOfOptionWithOffset(inBuffer, offset);
int valueSize = getValueSizeOfOptionWithOffset(inBuffer, offset);
int currentOptionSize = headerSize + valueSize;
return offset + currentOptionSize;
}
private static int headerSizeOfOptionWithOffset(byte[] inBuffer, int offset) {
int size = 1;
size += optionExtendedDeltaFieldSize(inBuffer, offset);
size += optionExtendedLengthFieldSize(inBuffer, offset);
return size;
}
private static int optionExtendedDeltaFieldSize(byte[] inBuffer, int offset) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return 0;
if(optionDelta == 13)
return 1;
return 2; //optionDelta == 14
}
private static int optionExtendedLengthFieldSize(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return 0;
if(optionLength == 13)
return 1;
return 2; //optionLength == 14
}
private static int getValueSizeOfOptionWithOffset(byte[] inBuffer, int offset) {
byte optionLength = (byte) (inBuffer[offset] & 0x0F);
if(optionLength < 13)
return optionLength;
else {
offset += 1 + optionExtendedDeltaFieldSize(inBuffer, offset);
if(optionLength == 13) {
return inBuffer[offset] + 13;
}
return Util.get16(inBuffer, offset) + 269; //optionLength == 14
}
}
private static int idOfOptionWithOffset(byte[] inBuffer, int offset, int currentDelta) {
byte optionDelta = (byte) (((inBuffer[offset] & 0xF0) >> 4));
if(optionDelta < 13)
return currentDelta + optionDelta;
else {
offset += 1;
if(optionDelta == 13) {
return currentDelta + inBuffer[offset] + 13;
}
return currentDelta + Util.get16(inBuffer, offset) + 269; //optionDelta == 14
}
}
private static int getExtendedOptionFieldSizeFor(int input) {
if(input<13)
return 0;
else if(input >= 13 && input < 269)
return 1;
return 2; //input >= 269
}
}
|
MR-CoAP/CoAP
|
src/com/sap/coap/Message.java
|
Java
|
bsd-3-clause
| 26,430 |
/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file. */
package it.inaf.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class DateFormatter {
public static String formatType1(String date)
{
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType2(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
public static String formatType3(String date)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
java.util.Date tmpDate = null;
try {
tmpDate = format.parse(date);
} catch(ParseException e) {
e.printStackTrace();
}
SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
return postFormater.format(tmpDate);
}
}
|
mediainaf/AppINAFAndroid
|
app/src/main/java/it/inaf/android/DateFormatter.java
|
Java
|
bsd-3-clause
| 1,724 |
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2619.SirLancebot2016.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
import org.usfirst.frc2619.SirLancebot2016.subsystems.*;
/**
*
*/
public class CrossRockWallCG extends CommandGroup {
double distanceFromStart = 4.2;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
public CrossRockWallCG() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=PARAMETERS
// Add Commands here:
// e.g. addSequential(new Command1());
// addSequential(new Command2());
// these will run in order.
// To run multiple commands at the same time,
// use addParallel()
// e.g. addParallel(new Command1());
// addSequential(new Command2());
// Command1 and Command2 will run in parallel.
// A command group will require all of the subsystems that each member
// would require.
// e.g. if Command1 requires chassis, and Command2 requires arm,
// a CommandGroup containing them would require both the chassis and the
// arm.
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=COMMAND_DECLARATIONS
addSequential(new DriveXfeet(distanceFromStart));
addSequential(new DriveUntilFlat(1));
}
}
|
The-Charge/SirLancebot2016
|
src/org/usfirst/frc2619/SirLancebot2016/commands/CrossRockWallCG.java
|
Java
|
bsd-3-clause
| 1,844 |
/*******************************************************************************
* Copyright (c) 2009-2012, University of Manchester
*
* Licensed under the New BSD License.
* Please see LICENSE file that is distributed with the source code
******************************************************************************/
package uk.ac.manchester.cs.owl.semspreadsheets.model;
/**
* Author: Matthew Horridge<br>
* The University of Manchester<br>
* Information Management Group<br>
* Date: 08-Nov-2009
*/
public interface NamedRange {
String getName();
Range getRange();
}
|
Tokebluff/RightField
|
src/main/java/uk/ac/manchester/cs/owl/semspreadsheets/model/NamedRange.java
|
Java
|
bsd-3-clause
| 595 |
/*L
* Copyright SAIC, SAIC-Frederick.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caadapter/LICENSE.txt for details.
*/
package gov.nih.nci.caadapter.sdtm.util;
/**
* This class represents a entity
*
* @author OWNER: Harsha Jayanna
* @author LAST UPDATE $Author: phadkes $
* @version Since caAdapter v4.0 revision
* $Revision: 1.4 $
* $Date: 2008-06-09 19:53:51 $
*/
public class Entity {
private String schema = null;
private String entityName = null;
/**
* Creates a new instance of Entity
*/
public Entity(String schema, String entityName) {
this.setSchema(schema);
this.setEntityName(entityName);
}
public String toString() {
return getEntityName();
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getEntityName() {
return entityName;
}
public void setEntityName(String entityName) {
this.entityName = entityName;
}
}
/**
* Change History
* $Log: not supported by cvs2svn $
* Revision 1.3 2008/06/06 18:55:19 phadkes
* Changes for License Text
*
* Revision 1.2 2007/08/16 19:04:58 jayannah
* Reformatted and added the Comments and the log tags for all the files
*
*/
|
NCIP/caadapter
|
software/caadapter/src/java/gov/nih/nci/caadapter/sdtm/util/Entity.java
|
Java
|
bsd-3-clause
| 1,371 |
/**
* Copyright 5AM Solutions Inc, ESAC, ScenPro & SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/caintegrator/LICENSE.txt for details.
*/
package gov.nih.nci.caintegrator.web.action.study.management;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import gov.nih.nci.caintegrator.application.study.LogEntry;
import gov.nih.nci.caintegrator.application.study.StudyConfiguration;
import gov.nih.nci.caintegrator.application.study.StudyManagementServiceStub;
import gov.nih.nci.caintegrator.web.action.AbstractSessionBasedTest;
import gov.nih.nci.caintegrator.web.action.study.management.EditStudyLogAction;
import java.util.Date;
import org.junit.Before;
import org.junit.Test;
import com.opensymphony.xwork2.Action;
/**
*
*/
public class EditStudyLogActionTest extends AbstractSessionBasedTest {
private EditStudyLogAction action = new EditStudyLogAction();
private StudyManagementServiceStub studyManagementService;
private LogEntry logEntry1;
private LogEntry logEntry2;
@Override
@Before
public void setUp() throws Exception {
super.setUp();
action.setStudyConfiguration(new StudyConfiguration());
action = new EditStudyLogAction();
studyManagementService = new StudyManagementServiceStub();
action.setStudyManagementService(studyManagementService);
action.setWorkspaceService(workspaceService);
logEntry1 = new LogEntry();
logEntry1.setTrimSystemLogMessage("message");
logEntry1.setLogDate(new Date());
logEntry1.setTrimDescription("desc");
try {
Thread.sleep(20l);
} catch (InterruptedException e) {
}
logEntry2 = new LogEntry();
logEntry2.setSystemLogMessage("message2");
logEntry2.setLogDate(new Date());
logEntry2.setDescription("desc");
action.getStudyConfiguration().getLogEntries().add(logEntry1);
action.getStudyConfiguration().getLogEntries().add(logEntry2);
}
@Test
public void testPrepare() throws InterruptedException {
action.prepare();
// Verify the most recent ones are sorted first.
assertEquals(logEntry2, action.getDisplayableLogEntries().get(0).getLogEntry());
assertEquals(logEntry1, action.getDisplayableLogEntries().get(1).getLogEntry());
assertTrue(studyManagementService.getRefreshedStudyEntityCalled);
}
@Test
public void testSave() {
action.prepare();
// logEntry2 is first
action.getDisplayableLogEntries().get(0).setDescription("new");
action.getDisplayableLogEntries().get(0).setUpdateDescription(true);
// logEntry1 will have a new description, but the checkbox will be false.
action.getDisplayableLogEntries().get(1).setDescription("new");
action.getDisplayableLogEntries().get(1).setUpdateDescription(false);
assertEquals(Action.SUCCESS, action.save());
assertEquals("new", logEntry2.getDescription());
assertEquals("desc", logEntry1.getDescription());
assertTrue(studyManagementService.saveCalled);
}
@Test
public void testAcceptableParameterName() {
assertTrue(action.acceptableParameterName(null));
assertTrue(action.acceptableParameterName("ABC"));
assertFalse(action.acceptableParameterName("123"));
assertFalse(action.acceptableParameterName("d-123-e"));
}
}
|
NCIP/caintegrator
|
caintegrator-war/test/src/gov/nih/nci/caintegrator/web/action/study/management/EditStudyLogActionTest.java
|
Java
|
bsd-3-clause
| 3,632 |
/*
* Copyright (c) 2008, Keith Woodward
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of Keith Woodward nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package straightedge.geom.vision;
import straightedge.geom.*;
public class CollinearOverlap{
public KPolygon polygon;
public int pointIndex;
public int nextPointIndex;
public KPolygon polygon2;
public int point2Index;
public CollinearOverlap(KPolygon polygon, int pointIndex, int nextPointIndex, KPolygon polygon2, int point2Index){
this.polygon = polygon;
this.pointIndex = pointIndex;
this.nextPointIndex = nextPointIndex;
this.polygon2 = polygon2;
this.point2Index = point2Index;
}
public KPolygon getPolygon() {
return polygon;
}
public int getPointIndex() {
return pointIndex;
}
public int getNextPointIndex() {
return nextPointIndex;
}
public KPolygon getPolygon2() {
return polygon2;
}
public int getPoint2Index() {
return point2Index;
}
}
|
rpax/straightedge
|
src/main/java/straightedge/geom/vision/CollinearOverlap.java
|
Java
|
bsd-3-clause
| 2,372 |
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc157.ProtoBot2017;
import org.usfirst.frc157.ProtoBot2017.AnalogSelectSwitch;
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import com.ctre.CANTalon;
import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.RobotDrive;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=IMPORTS
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
/**
* The RobotMap is a mapping from the ports sensors and actuators are wired into
* to a variable name. This provides flexibility changing wiring, makes checking
* the wiring easier and significantly reduces the number of magic numbers
* floating around.
*/
public class RobotMap {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static CANTalon driveFL_Motor;
public static CANTalon driveFR_Motor;
public static CANTalon driveRL_Motor;
public static CANTalon driveRR_Motor;
public static RobotDrive driveMechDrive;
public static CANTalon gearMotorLeft;
public static CANTalon gearMotorRight;
public static CANTalon collectMotor;
public static CANTalon helixMotorRight;
public static CANTalon helixMotorLeft;
public static CANTalon shootMotor;
public static CANTalon climbMotor;
public static Relay leftGateRelay;
public static Relay rightGateRelay;
public final static int OnboardModeSelectSwitchAnalogInID = 3;
public static AnalogSelectSwitch modeSelect;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
public static void init() {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
modeSelect = new AnalogSelectSwitch(0); // Analog Port 0
driveFL_Motor = new CANTalon(5); // CAN ID 5
LiveWindow.addActuator("Drive", "FL_Motor", driveFL_Motor);
driveFR_Motor = new CANTalon(4); // CAN ID 4
LiveWindow.addActuator("Drive", "FR_Motor", driveFR_Motor);
driveRL_Motor = new CANTalon(7); // CAN ID 7
LiveWindow.addActuator("Drive", "RL_Motor", driveRL_Motor);
driveRR_Motor = new CANTalon(6) ; // CAN ID 6
LiveWindow.addActuator("Drive", "RR_Motor", driveRR_Motor);
driveMechDrive = new RobotDrive(driveFL_Motor, driveRL_Motor,
driveFR_Motor, driveRR_Motor);
driveMechDrive.setSafetyEnabled(true);
driveMechDrive.setExpiration(0.5);
driveMechDrive.setSensitivity(0.5);
driveMechDrive.setMaxOutput(1.0);
gearMotorRight = new CANTalon(14); // CAN ID 14
LiveWindow.addActuator("Gear", "gearMotor", gearMotorRight);
gearMotorLeft = new CANTalon(12);
LiveWindow.addActuator("Gear", "gearMotor", gearMotorLeft);
collectMotor = new CANTalon(13); // CAN ID 13
LiveWindow.addActuator("Collect", "collectMotor", collectMotor);
helixMotorRight = new CANTalon(9); // CAN ID 9
helixMotorLeft = new CANTalon(8); // CAN ID 8
shootMotor = new CANTalon(11); // CAN ID 11
climbMotor = new CANTalon(10); // CAN ID 10
rightGateRelay = new Relay(0); // Relay Port 0
leftGateRelay = new Relay(1); // Relay Port 1
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
}
}
|
Aztechs157/ProtoBot2017
|
src/org/usfirst/frc157/ProtoBot2017/RobotMap.java
|
Java
|
bsd-3-clause
| 3,913 |
package edu.ucdenver.ccp.datasource.fileparsers.snomed;
import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecord;
/*
* #%L
* Colorado Computational Pharmacology's common module
* %%
* Copyright (C) 2012 - 2015 Regents of the University of Colorado
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import lombok.Getter;
/**
* @author Center for Computational Pharmacology, UC Denver; ccpsupport@ucdenver.edu
*
*/
@Getter
public class SnomedRf2DescriptionFileRecord extends SingleLineFileRecord {
public enum DescriptionType {
FULLY_SPECIFIED_NAME("900000000000003001"),
SYNONYM("900000000000013009");
private final String typeId;
private DescriptionType(String typeId) {
this.typeId = typeId;
}
public String typeId() {
return typeId;
}
public static DescriptionType getType(String typeId) {
for (DescriptionType type : values()) {
if (type.typeId().equals(typeId)) {
return type;
}
}
throw new IllegalArgumentException("Invalid SnoMed description type id: " + typeId);
}
}
/*
* id effectiveTime active moduleId conceptId languageCode typeId term caseSignificanceId
*/
private final String descriptionId;
private final String effectiveTime;
private final boolean active;
private final String moduleId;
private final String conceptId;
private final String languageCode;
private final DescriptionType type;
private final String term;
private final String caseSignificanceId;
/**
* @param byteOffset
* @param lineNumber
* @param definitionId
* @param effectiveTime
* @param active
* @param moduleId
* @param conceptId
* @param languageCode
* @param typeId
* @param term
* @param caseSignificanceId
*/
public SnomedRf2DescriptionFileRecord(String descriptionId, String effectiveTime, boolean active, String moduleId,
String conceptId, String languageCode, DescriptionType type, String term, String caseSignificanceId,
long byteOffset, long lineNumber) {
super(byteOffset, lineNumber);
this.descriptionId = descriptionId;
this.effectiveTime = effectiveTime;
this.active = active;
this.moduleId = moduleId;
this.conceptId = conceptId;
this.languageCode = languageCode;
this.type = type;
this.term = term;
this.caseSignificanceId = caseSignificanceId;
}
}
|
UCDenver-ccp/datasource
|
datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/snomed/SnomedRf2DescriptionFileRecord.java
|
Java
|
bsd-3-clause
| 3,805 |
package com.mattunderscore.trees.base;
import static org.junit.Assert.*;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import com.mattunderscore.iterators.SingletonIterator;
import com.mattunderscore.trees.mutable.MutableNode;
import com.mattunderscore.trees.tree.Node;
/**
* Unit tests for {@link MutableChildIterator}.
*
* @author Matt Champion on 29/08/2015
*/
public final class MutableChildIteratorTest {
@Mock
private MutableNode<String> parent;
@Mock
private MutableNode<String> child;
private Iterator<? extends MutableNode<String>> iterator;
@Before
public void setUp() {
initMocks(this);
iterator = new SingletonIterator<>(child);
}
@Test
public void hasNext() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
assertTrue(mutableIterator.hasNext());
mutableIterator.next();
assertFalse(mutableIterator.hasNext());
}
@Test(expected = NoSuchElementException.class)
public void next() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
final MutableNode<String> node = mutableIterator.next();
assertSame(child, node);
mutableIterator.next();
}
@Test
public void remove() {
final MutableChildIterator<String, MutableNode<String>> mutableIterator = new MutableChildIterator<>(parent, iterator);
mutableIterator.next();
mutableIterator.remove();
verify(parent).removeChild(child);
}
}
|
mattunderscorechampion/tree-root
|
trees-basic-nodes/src/test/java/com/mattunderscore/trees/base/MutableChildIteratorTest.java
|
Java
|
bsd-3-clause
| 1,823 |
package com.spm.store;
import java.io.Serializable;
import java.util.List;
import android.content.Context;
/**
*
* @author Agustin Sgarlata
* @param <T>
*/
public class DbProvider<T extends Serializable> extends Db4oHelper {
public Class<T> persistentClass;
public DbProvider(Class<T> persistentClass, Context ctx) {
super(ctx);
this.persistentClass = persistentClass;
}
public void store(T obj) {
db().store(obj);
db().commit();
}
public void delete(T obj) {
db().delete(obj);
db().commit();
}
public List<T> findAll() {
return db().query(persistentClass);
}
public List<T> get(T obj) {
return db().queryByExample(obj);
}
}
|
mural/spm
|
SPM/src/main/java/com/spm/store/DbProvider.java
|
Java
|
bsd-3-clause
| 670 |
/**
* This code is free software; you can redistribute it and/or modify it under
* the terms of the new BSD License.
*
* Copyright (c) 2008-2011, Sebastian Staudt
*/
package com.github.koraktor.steamcondenser.steam.community;
import static com.github.koraktor.steamcondenser.steam.community.XMLUtil.loadXml;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.github.koraktor.steamcondenser.steam.community.portal2.Portal2Stats;
/**
* @author Guto Maia
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DocumentBuilderFactory.class, DocumentBuilder.class })
public class Portal2StatsTest extends StatsTestCase<Portal2Stats>{
public Portal2StatsTest() {
super("gutomaia", "portal2");
}
@Test
public void getPortal2Stats() throws Exception {
assertEquals("Portal 2", stats.getGameName());
assertEquals("Portal2", stats.getGameFriendlyName());
assertEquals(620, stats.getAppId());
assertEquals("0", stats.getHoursPlayed());
assertEquals(76561197985077150l, stats.getSteamId64());
}
@Test
public void achievements() throws Exception {
assertEquals(17, stats.getAchievementsDone());
}
}
|
gutomaia/steam-condenser-java
|
src/test/java/com/github/koraktor/steamcondenser/steam/community/Portal2StatsTest.java
|
Java
|
bsd-3-clause
| 1,630 |
package com.atlassian.pageobjects.components.aui;
import com.atlassian.pageobjects.PageBinder;
import com.atlassian.pageobjects.binder.Init;
import com.atlassian.pageobjects.binder.InvalidPageStateException;
import com.atlassian.pageobjects.components.TabbedComponent;
import com.atlassian.pageobjects.elements.PageElement;
import com.atlassian.pageobjects.elements.PageElementFinder;
import com.atlassian.pageobjects.elements.query.Poller;
import org.openqa.selenium.By;
import javax.inject.Inject;
import java.util.List;
/**
* Represents a tabbed content area created via AUI.
*
* This is an example of a reusable components.
*/
public class AuiTabs implements TabbedComponent
{
@Inject
protected PageBinder pageBinder;
@Inject
protected PageElementFinder elementFinder;
private final By rootLocator;
private PageElement rootElement;
public AuiTabs(By locator)
{
this.rootLocator = locator;
}
@Init
public void initialize()
{
this.rootElement = elementFinder.find(rootLocator);
}
public PageElement selectedTab()
{
List<PageElement> items = rootElement.find(By.className("tabs-menu")).findAll(By.tagName("li"));
for(int i = 0; i < items.size(); i++)
{
PageElement tab = items.get(i);
if(tab.hasClass("active-tab"))
{
return tab;
}
}
throw new InvalidPageStateException("A tab must be active.", this);
}
public PageElement selectedView()
{
List<PageElement> panes = rootElement.findAll(By.className("tabs-pane"));
for(int i = 0; i < panes.size(); i++)
{
PageElement pane = panes.get(i);
if(pane.hasClass("active-pane"))
{
return pane;
}
}
throw new InvalidPageStateException("A pane must be active", this);
}
public List<PageElement> tabs()
{
return rootElement.find(By.className("tabs-menu")).findAll(By.tagName("li"));
}
public PageElement openTab(String tabText)
{
List<PageElement> tabs = rootElement.find(By.className("tabs-menu")).findAll(By.tagName("a"));
for(int i = 0; i < tabs.size(); i++)
{
if(tabs.get(i).getText().equals(tabText))
{
PageElement listItem = tabs.get(i);
listItem.click();
// find the pane and wait until it has class "active-pane"
String tabViewHref = listItem.getAttribute("href");
String tabViewClassName = tabViewHref.substring(tabViewHref.indexOf('#') + 1);
PageElement pane = rootElement.find(By.id(tabViewClassName));
Poller.waitUntilTrue(pane.timed().hasClass("active-pane"));
return pane;
}
}
throw new InvalidPageStateException("Tab not found", this);
}
public PageElement openTab(PageElement tab)
{
String tabIdentifier = tab.getText();
return openTab(tabIdentifier);
}
}
|
adini121/atlassian
|
atlassian-pageobjects-elements/src/main/java/com/atlassian/pageobjects/components/aui/AuiTabs.java
|
Java
|
bsd-3-clause
| 3,108 |
package com.xoba.smr;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URI;
import java.util.Collection;
import java.util.Formatter;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.codec.binary.Base64;
import com.amazonaws.Request;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.handlers.AbstractRequestHandler;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.LaunchSpecification;
import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest;
import com.amazonaws.services.ec2.model.RequestSpotInstancesResult;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import com.amazonaws.services.ec2.model.RunInstancesResult;
import com.amazonaws.services.ec2.model.Tag;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.simpledb.AmazonSimpleDB;
import com.amazonaws.services.simpledb.AmazonSimpleDBClient;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.xoba.util.ILogger;
import com.xoba.util.LogFactory;
import com.xoba.util.MraUtils;
public class SimpleMapReduce {
private static final ILogger logger = LogFactory.getDefault().create();
public static void launch(Properties config, Collection<String> inputSplitPrefixes, AmazonInstance ai,
int machineCount) throws Exception {
launch(config, inputSplitPrefixes, ai, machineCount, true);
}
public static void launch(Properties config, Collection<String> inputSplitPrefixes, AmazonInstance ai,
int machineCount, boolean spotInstances) throws Exception {
if (!config.containsKey(ConfigKey.JOB_ID.toString())) {
config.put(ConfigKey.JOB_ID.toString(), MraUtils.md5Hash(new TreeMap<Object, Object>(config).toString())
.substring(0, 8));
}
String id = config.getProperty(ConfigKey.JOB_ID.toString());
AWSCredentials aws = create(config);
AmazonSimpleDB db = new AmazonSimpleDBClient(aws);
AmazonSQS sqs = new AmazonSQSClient(aws);
AmazonS3 s3 = new AmazonS3Client(aws);
final String mapQueue = config.getProperty(ConfigKey.MAP_QUEUE.toString());
final String reduceQueue = config.getProperty(ConfigKey.REDUCE_QUEUE.toString());
final String dom = config.getProperty(ConfigKey.SIMPLEDB_DOM.toString());
final String mapInputBucket = config.getProperty(ConfigKey.MAP_INPUTS_BUCKET.toString());
final String shuffleBucket = config.getProperty(ConfigKey.SHUFFLE_BUCKET.toString());
final String reduceOutputBucket = config.getProperty(ConfigKey.REDUCE_OUTPUTS_BUCKET.toString());
final int hashCard = new Integer(config.getProperty(ConfigKey.HASH_CARDINALITY.toString()));
s3.createBucket(reduceOutputBucket);
final long inputSplitCount = inputSplitPrefixes.size();
for (String key : inputSplitPrefixes) {
Properties p = new Properties();
p.setProperty("input", "s3://" + mapInputBucket + "/" + key);
sqs.sendMessage(new SendMessageRequest(mapQueue, serialize(p)));
}
SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "splits", "" + inputSplitCount);
SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "hashes", "" + hashCard);
SimpleDbCommitter.commitNewAttribute(db, dom, "parameters", "done", "1");
for (String hash : getAllHashes(hashCard)) {
Properties p = new Properties();
p.setProperty("input", "s3://" + shuffleBucket + "/" + hash);
sqs.sendMessage(new SendMessageRequest(reduceQueue, serialize(p)));
}
if (machineCount == 1) {
// run locally
SMRDriver.main(new String[] { MraUtils.convertToHex(serialize(config).getBytes()) });
} else if (machineCount > 1) {
// run in the cloud
String userData = produceUserData(ai, config,
new URI(config.getProperty(ConfigKey.RUNNABLE_JARFILE_URI.toString())));
logger.debugf("launching job with id %s:", id);
System.out.println(userData);
AmazonEC2 ec2 = new AmazonEC2Client(aws);
if (spotInstances) {
RequestSpotInstancesRequest sir = new RequestSpotInstancesRequest();
sir.setSpotPrice(new Double(ai.getPrice()).toString());
sir.setInstanceCount(machineCount);
sir.setType("one-time");
LaunchSpecification spec = new LaunchSpecification();
spec.setImageId(ai.getDefaultAMI());
spec.setUserData(new String(new Base64().encode(userData.getBytes("US-ASCII"))));
spec.setInstanceType(ai.getApiName());
sir.setLaunchSpecification(spec);
RequestSpotInstancesResult result = ec2.requestSpotInstances(sir);
logger.debugf("spot instance request result: %s", result);
} else {
RunInstancesRequest req = new RunInstancesRequest(ai.getDefaultAMI(), machineCount, machineCount);
req.setClientToken(id);
req.setInstanceType(ai.getApiName());
req.setInstanceInitiatedShutdownBehavior("terminate");
req.setUserData(new String(new Base64().encode(userData.getBytes("US-ASCII"))));
RunInstancesResult resp = ec2.runInstances(req);
logger.debugf("on demand reservation id: %s", resp.getReservation().getReservationId());
labelEc2Instance(ec2, resp, "smr-" + id);
}
}
}
public static void labelEc2Instance(AmazonEC2 ec2, RunInstancesResult resp, String title) throws Exception {
int tries = 0;
boolean done = false;
while (tries++ < 3 && !done) {
try {
List<String> resources = new LinkedList<String>();
for (Instance i : resp.getReservation().getInstances()) {
resources.add(i.getInstanceId());
}
List<Tag> tags = new LinkedList<Tag>();
tags.add(new Tag("Name", title));
CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
ec2.createTags(ctr);
done = true;
logger.debugf("set tag(s)");
} catch (Exception e) {
logger.warnf("exception setting tags: %s", e);
Thread.sleep(3000);
}
}
}
public static String produceUserData(AmazonInstance ai, Properties c, URI jarFileURI) throws Exception {
StringWriter sw = new StringWriter();
LinuxLineConventionPrintWriter pw = new LinuxLineConventionPrintWriter(new PrintWriter(sw));
pw.println("#!/bin/sh");
pw.println("cd /root");
pw.println("chmod 777 /mnt");
pw.println("aptitude update");
Set<String> set = new TreeSet<String>();
set.add("openjdk-6-jdk");
set.add("wget");
if (set.size() > 0) {
pw.print("aptitude install -y ");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String x = it.next();
pw.print(x);
if (it.hasNext()) {
pw.print(" ");
}
}
pw.println();
}
pw.printf("wget %s", jarFileURI);
pw.println();
String[] parts = jarFileURI.getPath().split("/");
String jar = parts[parts.length - 1];
pw.printf("java -Xmx%.0fm -cp %s %s %s", 1000 * 0.8 * ai.getMemoryGB(), jar, SMRDriver.class.getName(),
MraUtils.convertToHex(serialize(c).getBytes()));
pw.println();
pw.println("poweroff");
pw.close();
return sw.toString();
}
public static AmazonS3 getS3(AWSCredentials aws) {
AmazonS3Client s3 = new AmazonS3Client(aws);
s3.addRequestHandler(new AbstractRequestHandler() {
@Override
public void beforeRequest(Request<?> request) {
request.addHeader("x-amz-request-payer", "requester");
}
});
return s3;
}
public static String prefixedName(String p, String n) {
return p + "-" + n;
}
public static AWSCredentials create(final Properties p) {
return new AWSCredentials() {
@Override
public String getAWSSecretKey() {
return p.getProperty(ConfigKey.AWS_SECRETKEY.toString());
}
@Override
public String getAWSAccessKeyId() {
return p.getProperty(ConfigKey.AWS_KEYID.toString());
}
};
}
public static SortedSet<String> getAllHashes(long mod) {
SortedSet<String> out = new TreeSet<String>();
for (long i = 0; i < mod; i++) {
out.add(fmt(i, mod));
}
return out;
}
public static String hash(byte[] key, long mod) {
byte[] buf = MraUtils.md5HashBytesToBytes(key);
long x = Math.abs(MraUtils.extractLongValue(buf));
return fmt(x % mod, mod);
}
private static String fmt(long x, long mod) {
long places = Math.round(Math.ceil(Math.log10(mod)));
if (places == 0) {
places = 1;
}
return new Formatter().format("%0" + places + "d", x).toString();
}
public static String serialize(Properties p) throws Exception {
StringWriter sw = new StringWriter();
try {
p.store(sw, "n/a");
} finally {
sw.close();
}
return sw.toString();
}
public static Properties marshall(String s) throws Exception {
Properties p = new Properties();
StringReader sr = new StringReader(s);
try {
p.load(sr);
} finally {
sr.close();
}
return p;
}
}
|
mrallc/smr
|
code/src/com/xoba/smr/SimpleMapReduce.java
|
Java
|
bsd-3-clause
| 9,071 |
package org.broadinstitute.hellbender.engine;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.hellbender.cmdline.TestProgramGroup;
/**
* A Dummy / Placeholder class that can be used where a {@link GATKTool} is required.
* DO NOT USE THIS FOR ANYTHING OTHER THAN TESTING.
* THIS MUST BE IN THE ENGINE PACKAGE DUE TO SCOPE ON `features`!
* Created by jonn on 9/19/18.
*/
@CommandLineProgramProperties(
summary = "A dummy GATKTool to help test Funcotator.",
oneLineSummary = "Dummy dumb dumb tool for testing.",
programGroup = TestProgramGroup.class
)
public final class DummyPlaceholderGatkTool extends GATKTool {
public DummyPlaceholderGatkTool() {
parseArgs(new String[]{});
onStartup();
}
@Override
public void traverse() {
}
@Override
void initializeFeatures(){
features = new FeatureManager(this, FeatureDataSource.DEFAULT_QUERY_LOOKAHEAD_BASES, cloudPrefetchBuffer, cloudIndexPrefetchBuffer,
referenceArguments.getReferencePath());
}
}
|
magicDGS/gatk
|
src/test/java/org/broadinstitute/hellbender/engine/DummyPlaceholderGatkTool.java
|
Java
|
bsd-3-clause
| 1,099 |
/*
* Created on 02/04/2005
*
* JRandTest package
*
* Copyright (c) 2005, Zur Aougav, aougav@hotmail.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of the JRandTest nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.fasteasytrade.jrandtest.algo;
import java.math.BigInteger;
import java.util.Random;
/**
* QuadraidResidue1 Prng algorithm from NIST test package
* <p>
* Fix random p, prime, length 512 bits.
* <p>
* Fix random g, prime, length 512 bits. g < p.
* <p>
* Each prng iteration calculate g = g**2 mod p.<br>
* The lowest 64 bits of g are the prng result.
*
* @author Zur Aougav
*/
public class QuadraticResidue1Prng extends Cipher {
/**
* n's length/num of bits
*/
public final int bit_length = 512;
/**
* prime (with probability < 2 ** -100).
* <p>
* Length of p is bit_length = 512 bits = 64 bytes.
*/
BigInteger p;
/**
* Initial g is a random prime (with probability < 2 ** -100)
* <p>
* Length of g is bit_length = 512 bits = 64 bytes.
* <p>
* g is the "state" of the prng.
* <p>
* g = take 64 lowr bits of ( g**2 mod n ).
*/
BigInteger g;
/**
* g0 is the "initial state" of the prng.
* <p>
* reset method set g to g0.
*/
BigInteger g0;
QuadraticResidue1Prng() {
setup(bit_length);
}
QuadraticResidue1Prng(int x) {
if (x < bit_length) {
setup(bit_length);
} else {
setup(x);
}
}
QuadraticResidue1Prng(BigInteger p, BigInteger g) {
this.p = p;
this.g = g;
g0 = g;
}
QuadraticResidue1Prng(BigInteger p, BigInteger g, BigInteger g0) {
this.p = p;
this.g = g;
this.g0 = g0;
}
/**
* Generate the key and seed for Quadratic Residue Prng.
* <p>
* Select random primes - p, g. g < p.
*
* @param len
* length of p and g, num of bits.
*/
void setup(int len) {
Random rand = new Random();
p = BigInteger.probablePrime(len, rand);
g = BigInteger.probablePrime(len, rand);
/**
* if g >= p swap(g, p).
*/
if (g.compareTo(p) > -1) {
BigInteger temp = g;
g = p;
p = temp;
}
/**
* here for sure g < p
*/
g0 = g;
}
/**
* calculate g**2 mod p and returns lowest 64 bits, long.
*
*/
public long nextLong() {
g = g.multiply(g).mod(p);
/**
* set g to 2 if g <= 1.
*/
if (g.compareTo(BigInteger.ONE) < 1) {
g = BigInteger.valueOf(2);
}
return g.longValue();
}
/**
* Public key.
*
* @return p prime (with probability < 2 ** -100)
*/
public BigInteger getP() {
return p;
}
/**
* Secret key
*
* @return g prime (with probability < 2 ** -100)
*/
public BigInteger getG() {
return g;
}
/**
* Reset "state" of prng by setting g to g0 (initial g).
*
*/
public void reset() {
g = g0;
}
}
|
cryptopony/jrandtest
|
src/com/fasteasytrade/jrandtest/algo/QuadraticResidue1Prng.java
|
Java
|
bsd-3-clause
| 4,818 |
package de.uni.freiburg.iig.telematik.wolfgang.properties.check;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import de.invation.code.toval.graphic.component.DisplayFrame;
import de.invation.code.toval.graphic.util.SpringUtilities;
import de.uni.freiburg.iig.telematik.sepia.petrinet.cpn.properties.cwn.CWNProperties;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.PropertyCheckingResult;
import javax.swing.SpringLayout;
public class CWNPropertyCheckView extends AbstractPropertyCheckView<CWNProperties> {
private static final long serialVersionUID = -950169446391727139L;
private PropertyCheckResultLabel lblStructure;
private PropertyCheckResultLabel lblInOutPlaces;
private PropertyCheckResultLabel lblConnectedness;
private PropertyCheckResultLabel lblValidMarking;
private PropertyCheckResultLabel lblCFDependency;
private PropertyCheckResultLabel lblNoDeadTransitions;
private PropertyCheckResultLabel lblCompletion;
private PropertyCheckResultLabel lblOptionComplete;
private PropertyCheckResultLabel lblBounded;
@Override
protected String getHeadline() {
return "Colored WF Net Check";
}
@Override
protected void addSpecificFields(JPanel pnl) {
lblStructure = new PropertyCheckResultLabel("\u2022 CWN Structure", PropertyCheckingResult.UNKNOWN);
pnl.add(lblStructure);
JPanel pnlStructureSub = new JPanel(new SpringLayout());
pnl.add(pnlStructureSub);
lblInOutPlaces = new PropertyCheckResultLabel("\u2022 Valid InOut Places", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblInOutPlaces);
lblConnectedness = new PropertyCheckResultLabel("\u2022 Strong Connectedness", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblConnectedness);
lblValidMarking = new PropertyCheckResultLabel("\u2022 Valid Initial Marking", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblValidMarking);
lblCFDependency = new PropertyCheckResultLabel("\u2022 Control Flow Dependency", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblCFDependency);
SpringUtilities.makeCompactGrid(pnlStructureSub, pnlStructureSub.getComponentCount(), 1, 15, 0, 0, 0);
pnl.add(new JPopupMenu.Separator());
lblBounded = new PropertyCheckResultLabel("\u2022 Is Bounded", PropertyCheckingResult.UNKNOWN);
pnl.add(lblBounded);
pnl.add(new JPopupMenu.Separator());
lblOptionComplete = new PropertyCheckResultLabel("\u2022 Option To Complete", PropertyCheckingResult.UNKNOWN);
pnl.add(lblOptionComplete);
pnl.add(new JPopupMenu.Separator());
lblCompletion = new PropertyCheckResultLabel("\u2022 Proper Completion", PropertyCheckingResult.UNKNOWN);
pnl.add(lblCompletion);
pnl.add(new JPopupMenu.Separator());
lblNoDeadTransitions = new PropertyCheckResultLabel("\u2022 No Dead Transitions", PropertyCheckingResult.UNKNOWN);
pnl.add(lblNoDeadTransitions);
}
@Override
public void resetFieldContent() {
super.updateFieldContent(null, null);
lblStructure.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblInOutPlaces.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblConnectedness.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblValidMarking.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCFDependency.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblBounded.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblOptionComplete.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCompletion.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblNoDeadTransitions.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
}
@Override
public void updateFieldContent(CWNProperties checkResult, Exception exception) {
super.updateFieldContent(checkResult, exception);
lblStructure.updatePropertyCheckingResult(checkResult.hasCWNStructure);
lblInOutPlaces.updatePropertyCheckingResult(checkResult.validInOutPlaces);
lblConnectedness.updatePropertyCheckingResult(checkResult.strongConnectedness);
lblValidMarking.updatePropertyCheckingResult(checkResult.validInitialMarking);
lblCFDependency.updatePropertyCheckingResult(checkResult.controlFlowDependency);
lblBounded.updatePropertyCheckingResult(checkResult.isBounded);
lblOptionComplete.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblCompletion.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblNoDeadTransitions.updatePropertyCheckingResult(checkResult.noDeadTransitions);
}
public static void main(String[] args) {
CWNPropertyCheckView view = new CWNPropertyCheckView();
view.setUpGui();
view.updateFieldContent(new CWNProperties(), null);
new DisplayFrame(view, true);
}
}
|
iig-uni-freiburg/WOLFGANG
|
src/de/uni/freiburg/iig/telematik/wolfgang/properties/check/CWNPropertyCheckView.java
|
Java
|
bsd-3-clause
| 5,138 |
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* Neither the name of the <copyright holder> nor the names of its contributors may
* be used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package nom.bdezonia.zorbage.algorithm;
import java.math.BigDecimal;
import java.math.MathContext;
import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Conjugate;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.RealConstants;
import nom.bdezonia.zorbage.algebra.SetComplex;
import nom.bdezonia.zorbage.algebra.Trigonometric;
import nom.bdezonia.zorbage.algebra.Unity;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class InvFFT {
// do not instantiate
private InvFFT() {}
/**
*
* @param <T>
* @param <U>
* @param <V>
* @param <W>
* @param cmplxAlg
* @param realAlg
* @param a
* @param b
*/
public static
<T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Conjugate<U>,
U extends SetComplex<W>,
V extends Algebra<V,W> & Trigonometric<W> & RealConstants<W> & Unity<W> &
Multiplication<W> & Addition<W> & Invertible<W>,
W>
void compute(T cmplxAlg, V realAlg, IndexedDataSource<U> a,IndexedDataSource<U> b)
{
long aSize = a.size();
long bSize = b.size();
if (aSize != FFT.enclosingPowerOf2(aSize))
throw new IllegalArgumentException("input size is not a power of 2");
if (aSize != bSize)
throw new IllegalArgumentException("output size does not match input size");
U one_over_n = cmplxAlg.construct((BigDecimal.ONE.divide(BigDecimal.valueOf(aSize), new MathContext(100))).toString());
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, a, b);
FFT.compute(cmplxAlg, realAlg, b, b);
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, b, b);
Scale.compute(cmplxAlg, one_over_n, b, b);
}
}
|
bdezonia/zorbage
|
src/main/java/nom/bdezonia/zorbage/algorithm/InvFFT.java
|
Java
|
bsd-3-clause
| 3,423 |
package eu.monnetproject.sim.entity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import eu.monnetproject.util.Logger;
import eu.monnetproject.label.LabelExtractor;
import eu.monnetproject.label.LabelExtractorFactory;
import eu.monnetproject.lang.Language;
import eu.monnetproject.ontology.Entity;
import eu.monnetproject.sim.EntitySimilarityMeasure;
import eu.monnetproject.sim.StringSimilarityMeasure;
import eu.monnetproject.sim.string.Levenshtein;
import eu.monnetproject.sim.token.TokenBagOfWordsCosine;
import eu.monnetproject.sim.util.Functions;
import eu.monnetproject.sim.util.SimilarityUtils;
import eu.monnetproject.tokenizer.FairlyGoodTokenizer;
import eu.monnetproject.translatorimpl.Translator;
import eu.monnetproject.util.Logging;
/**
* Levenshtein similarity.
* Intralingual aggregation: average
* Interlingual aggregation: maximum
*
* @author Dennis Spohr
*
*/
public class MaximumAverageLevenshtein implements EntitySimilarityMeasure {
private Logger log = Logging.getLogger(this);
private final String name = this.getClass().getName();
private LabelExtractorFactory lef;
private LabelExtractor lex = null;
private Collection<Language> languages = Collections.emptySet();
private StringSimilarityMeasure measure;
private boolean includePuns = false;
private Translator translator;
public MaximumAverageLevenshtein(LabelExtractorFactory lef) {
this.lef = lef;
this.measure = new Levenshtein();
this.translator = new Translator();
}
public void configure(Properties properties) {
this.languages = SimilarityUtils.getLanguages(properties.getProperty("languages", ""));
for (Language lang : this.languages) {
log.info("Requested language: "+lang);
}
this.includePuns = SimilarityUtils.getIncludePuns(properties.getProperty("include_puns", "false"));
}
@Override
public double getScore(Entity srcEntity, Entity tgtEntity) {
if (this.lex == null) {
this.lex = this.lef.getExtractor(SimilarityUtils.determineLabelProperties(srcEntity, tgtEntity), true, false);
}
if (this.languages.size() < 1) {
log.warning("No languages specified in config file.");
this.languages = SimilarityUtils.determineLanguages(srcEntity, tgtEntity);
String langs = "";
for (Language lang : languages) {
langs += lang.getName()+", ";
}
try {
log.warning("Using "+langs.substring(0, langs.lastIndexOf(","))+".");
} catch (Exception e) {
log.severe("No languages in source and target ontology.");
}
}
Map<Language, Collection<String>> srcMap = null;
Map<Language, Collection<String>> tgtMap = null;
if (includePuns) {
srcMap = SimilarityUtils.getLabelsIncludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsIncludingPuns(tgtEntity,lex);
} else {
srcMap = SimilarityUtils.getLabelsExcludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsExcludingPuns(tgtEntity,lex);
}
List<Double> intralingualScores = new ArrayList<Double>();
for (Language language : this.languages) {
Collection<String> srcLabels = srcMap.get(language);
Collection<String> tgtLabels = tgtMap.get(language);
if (srcLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+srcEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
srcLabels = SimilarityUtils.getTranslatedLabels(srcEntity,language,translator,lex);
}
if (tgtLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+tgtEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
tgtLabels = SimilarityUtils.getTranslatedLabels(tgtEntity,language,translator,lex);
}
double[] scores = new double[srcLabels.size()*tgtLabels.size()];
int index = 0;
for (String srcLabel : srcLabels) {
for (String tgtLabel : tgtLabels) {
scores[index++] = measure.getScore(srcLabel, tgtLabel);
}
}
intralingualScores.add(Functions.mean(scores));
}
if (intralingualScores.size() < 1)
return 0.;
double[] intralingualScoresArray = new double[intralingualScores.size()];
for (int i = 0; i < intralingualScores.size(); i++) {
intralingualScoresArray[i] = intralingualScores.get(i);
}
return Functions.max(intralingualScoresArray);
}
@Override
public String getName() {
return this.name;
}
}
|
monnetproject/coal
|
nlp.sim/src/main/java/eu/monnetproject/sim/entity/MaximumAverageLevenshtein.java
|
Java
|
bsd-3-clause
| 4,639 |
package uk.ac.soton.ecs.comp3204.l3;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.swing.JPanel;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.data.dataset.VFSGroupDataset;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider;
import uk.ac.soton.ecs.comp3204.utils.Utils;
import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
/**
* Visualise mean-centered face images
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*
*/
@Demonstration(title = "Mean-centred faces demo")
public class MeanCenteredFacesDemo implements Slide {
@Override
public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
final FImage mean = dataset.getRandomInstance().fill(0f);
for (final FImage i : dataset) {
mean.addInplace(i);
}
mean.divideInplace(dataset.numInstances());
final JPanel outer = new JPanel();
outer.setOpaque(false);
outer.setPreferredSize(new Dimension(width, height));
outer.setLayout(new GridBagLayout());
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height - 50));
base.setLayout(new FlowLayout());
for (int i = 0; i < 60; i++) {
final FImage img = dataset.getRandomInstance().subtract(mean).normalise();
final ImageComponent ic = new ImageComponent(true, false);
ic.setAllowPanning(false);
ic.setAllowZoom(false);
ic.setShowPixelColours(false);
ic.setShowXYPosition(false);
ic.setImage(ImageUtilities.createBufferedImageForDisplay(img));
base.add(ic);
}
outer.add(base);
return outer;
}
@Override
public void close() {
// do nothing
}
public static void main(String[] args) throws IOException {
new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
}
}
|
jonhare/COMP3204
|
app/src/main/java/uk/ac/soton/ecs/comp3204/l3/MeanCenteredFacesDemo.java
|
Java
|
bsd-3-clause
| 2,176 |
package com.salesforce.dva.argus.service.mq.kafka;
import com.fasterxml.jackson.databind.JavaType;
import java.io.Serializable;
import java.util.List;
public interface Consumer {
<T extends Serializable> List<T> dequeueFromBuffer(String topic, Class<T> type, int timeout, int limit);
<T extends Serializable> List<T> dequeueFromBuffer(String topic, JavaType type, int timeout, int limit);
void shutdown();
}
|
salesforce/Argus
|
ArgusCore/src/main/java/com/salesforce/dva/argus/service/mq/kafka/Consumer.java
|
Java
|
bsd-3-clause
| 424 |
package eu.monnetproject.util;
import java.util.*;
/**
* Utility function to syntactically sugar properties for OSGi.
* This allows you to create a property map as follows
* <code>Props.prop("key1","value1")</code><br/>
* <code> .prop("key2","value2")</code>
*/
public final class Props {
public static PropsMap prop(String key, Object value) {
PropsMap pm = new PropsMap();
pm.put(key,value);
return pm;
}
public static class PropsMap extends Hashtable<String,Object> {
public PropsMap prop(String key, Object value) {
put(key,value);
return this;
}
}
}
|
monnetproject/coal
|
nlp.sim/src/main/java/eu/monnetproject/util/Props.java
|
Java
|
bsd-3-clause
| 590 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.wpilibj.hal.HAL;
/**
* Handle input from standard Joysticks connected to the Driver Station. This class handles standard
* input that comes from the Driver Station. Each time a value is requested the most recent value is
* returned. There is a single class instance for each joystick and the mapping of ports to hardware
* buttons depends on the code in the driver station.
*/
public class Joystick extends GenericHID {
static final byte kDefaultXAxis = 0;
static final byte kDefaultYAxis = 1;
static final byte kDefaultZAxis = 2;
static final byte kDefaultTwistAxis = 2;
static final byte kDefaultThrottleAxis = 3;
static final int kDefaultTriggerButton = 1;
static final int kDefaultTopButton = 2;
/**
* Represents an analog axis on a joystick.
*/
public enum AxisType {
kX(0), kY(1), kZ(2), kTwist(3), kThrottle(4), kNumAxis(5);
@SuppressWarnings("MemberName")
public final int value;
private AxisType(int value) {
this.value = value;
}
}
/**
* Represents a digital button on the JoyStick.
*/
public enum ButtonType {
kTrigger(0), kTop(1), kNumButton(2);
@SuppressWarnings("MemberName")
public final int value;
private ButtonType(int value) {
this.value = value;
}
}
/**
* Represents a rumble output on the JoyStick.
*/
public enum RumbleType {
kLeftRumble, kRightRumble
}
private final DriverStation m_ds;
private final int m_port;
private final byte[] m_axes;
private final byte[] m_buttons;
private int m_outputs;
private short m_leftRumble;
private short m_rightRumble;
/**
* Construct an instance of a joystick. The joystick index is the usb port on the drivers
* station.
*
* @param port The port on the driver station that the joystick is plugged into.
*/
public Joystick(final int port) {
this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value);
m_axes[AxisType.kX.value] = kDefaultXAxis;
m_axes[AxisType.kY.value] = kDefaultYAxis;
m_axes[AxisType.kZ.value] = kDefaultZAxis;
m_axes[AxisType.kTwist.value] = kDefaultTwistAxis;
m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis;
m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton;
m_buttons[ButtonType.kTop.value] = kDefaultTopButton;
HAL.report(tResourceType.kResourceType_Joystick, port);
}
/**
* Protected version of the constructor to be called by sub-classes.
*
* <p>This constructor allows the subclass to configure the number of constants for axes and
* buttons.
*
* @param port The port on the driver station that the joystick is plugged into.
* @param numAxisTypes The number of axis types in the enum.
* @param numButtonTypes The number of button types in the enum.
*/
protected Joystick(int port, int numAxisTypes, int numButtonTypes) {
m_ds = DriverStation.getInstance();
m_axes = new byte[numAxisTypes];
m_buttons = new byte[numButtonTypes];
m_port = port;
}
/**
* Get the X value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The X value of the joystick.
*/
public double getX(Hand hand) {
return getRawAxis(m_axes[AxisType.kX.value]);
}
/**
* Get the Y value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Y value of the joystick.
*/
public double getY(Hand hand) {
return getRawAxis(m_axes[AxisType.kY.value]);
}
/**
* Get the Z value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Z value of the joystick.
*/
public double getZ(Hand hand) {
return getRawAxis(m_axes[AxisType.kZ.value]);
}
/**
* Get the twist value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Twist value of the joystick.
*/
public double getTwist() {
return getRawAxis(m_axes[AxisType.kTwist.value]);
}
/**
* Get the throttle value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Throttle value of the joystick.
*/
public double getThrottle() {
return getRawAxis(m_axes[AxisType.kThrottle.value]);
}
/**
* Get the value of the axis.
*
* @param axis The axis to read, starting at 0.
* @return The value of the axis.
*/
public double getRawAxis(final int axis) {
return m_ds.getStickAxis(m_port, axis);
}
/**
* For the current joystick, return the axis determined by the argument.
*
* <p>This is for cases where the joystick axis is returned programatically, otherwise one of the
* previous functions would be preferable (for example getX()).
*
* @param axis The axis to read.
* @return The value of the axis.
*/
public double getAxis(final AxisType axis) {
switch (axis) {
case kX:
return getX();
case kY:
return getY();
case kZ:
return getZ();
case kTwist:
return getTwist();
case kThrottle:
return getThrottle();
default:
return 0.0;
}
}
/**
* For the current joystick, return the number of axis.
*/
public int getAxisCount() {
return m_ds.getStickAxisCount(m_port);
}
/**
* Read the state of the trigger on the joystick.
*
* <p>Look up which button has been assigned to the trigger and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the trigger.
*/
public boolean getTrigger(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTrigger.value]);
}
/**
* Read the state of the top button on the joystick.
*
* <p>Look up which button has been assigned to the top and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the top button.
*/
public boolean getTop(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTop.value]);
}
/**
* This is not supported for the Joystick. This method is only here to complete the GenericHID
* interface.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the bumper (always false)
*/
public boolean getBumper(Hand hand) {
return false;
}
/**
* Get the button value (starting at button 1).
*
* <p>The appropriate button is returned as a boolean value.
*
* @param button The button number to be read (starting at 1).
* @return The state of the button.
*/
public boolean getRawButton(final int button) {
return m_ds.getStickButton(m_port, (byte) button);
}
/**
* For the current joystick, return the number of buttons.
*/
public int getButtonCount() {
return m_ds.getStickButtonCount(m_port);
}
/**
* Get the angle in degrees of a POV on the joystick.
*
* <p>The POV angles start at 0 in the up direction, and increase clockwise (eg right is 90,
* upper-left is 315).
*
* @param pov The index of the POV to read (starting at 0)
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
public int getPOV(int pov) {
return m_ds.getStickPOV(m_port, pov);
}
/**
* For the current joystick, return the number of POVs.
*/
public int getPOVCount() {
return m_ds.getStickPOVCount(m_port);
}
/**
* Get buttons based on an enumerated type.
*
* <p>The button type will be looked up in the list of buttons and then read.
*
* @param button The type of button to read.
* @return The state of the button.
*/
public boolean getButton(ButtonType button) {
switch (button) {
case kTrigger:
return getTrigger();
case kTop:
return getTop();
default:
return false;
}
}
/**
* Get the magnitude of the direction vector formed by the joystick's current position relative to
* its origin.
*
* @return The magnitude of the direction vector
*/
public double getMagnitude() {
return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2));
}
/**
* Get the direction of the vector formed by the joystick and its origin in radians.
*
* @return The direction of the vector in radians
*/
public double getDirectionRadians() {
return Math.atan2(getX(), -getY());
}
/**
* Get the direction of the vector formed by the joystick and its origin in degrees.
*
* <p>Uses acos(-1) to represent Pi due to absence of readily accessable Pi constant in C++
*
* @return The direction of the vector in degrees
*/
public double getDirectionDegrees() {
return Math.toDegrees(getDirectionRadians());
}
/**
* Get the channel currently associated with the specified axis.
*
* @param axis The axis to look up the channel for.
* @return The channel fr the axis.
*/
public int getAxisChannel(AxisType axis) {
return m_axes[axis.value];
}
/**
* Set the channel associated with a specified axis.
*
* @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
public void setAxisChannel(AxisType axis, int channel) {
m_axes[axis.value] = (byte) channel;
}
/**
* Get the value of isXbox for the current joystick.
*
* @return A boolean that is true if the controller is an xbox controller.
*/
public boolean getIsXbox() {
return m_ds.getJoystickIsXbox(m_port);
}
/**
* Get the HID type of the current joystick.
*
* @return The HID type value of the current joystick.
*/
public int getType() {
return m_ds.getJoystickType(m_port);
}
/**
* Get the name of the current joystick.
*
* @return The name of the current joystick.
*/
public String getName() {
return m_ds.getJoystickName(m_port);
}
/**
* Get the port number of the joystick.
*
* @return The port number of the joystick.
*/
public int getPort() {
return m_port;
}
/**
* Get the axis type of a joystick axis.
*
* @return the axis type of a joystick axis.
*/
public int getAxisType(int axis) {
return m_ds.getJoystickAxisType(m_port, axis);
}
/**
* Set the rumble output for the joystick. The DS currently supports 2 rumble values, left rumble
* and right rumble.
*
* @param type Which rumble value to set
* @param value The normalized value (0 to 1) to set the rumble to
*/
public void setRumble(RumbleType type, float value) {
if (value < 0) {
value = 0;
} else if (value > 1) {
value = 1;
}
if (type == RumbleType.kLeftRumble) {
m_leftRumble = (short) (value * 65535);
} else {
m_rightRumble = (short) (value * 65535);
}
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set a single HID output value for the joystick.
*
* @param outputNumber The index of the output to set (1-32)
* @param value The value to set the output to
*/
public void setOutput(int outputNumber, boolean value) {
m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1));
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set all HID output values for the joystick.
*
* @param value The 32 bit output value (1 bit for each output)
*/
public void setOutputs(int value) {
m_outputs = value;
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
}
|
PeterMitrano/allwpilib
|
wpilibj/src/athena/java/edu/wpi/first/wpilibj/Joystick.java
|
Java
|
bsd-3-clause
| 12,635 |
package tools;
/*
* Extremely Compiler Collection
* Copyright (c) 2015-2020, Jianping Zeng.
*
* 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 java.io.PrintStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* This owns the files read by a parser, handles include stacks,
* and handles diagnostic wrangling.
*
* @author Jianping Zeng
* @version 0.4
*/
public final class SourceMgr {
public enum DiagKind {
DK_Error,
DK_Warning,
DK_Remark,
DK_Note
}
private DiagKind getDiagKindByName(String name) {
switch (name) {
case "error":
return DiagKind.DK_Error;
case "warning":
return DiagKind.DK_Warning;
case "remark":
return DiagKind.DK_Remark;
case "note":
return DiagKind.DK_Note;
default:
Util.assertion("Unknown diagnostic kind!");
return null;
}
}
public static class SMLoc {
private MemoryBuffer buffer;
private int startPos;
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (this == obj) return true;
if (getClass() != obj.getClass())
return false;
SMLoc loc = (SMLoc) obj;
return loc.buffer.equals(buffer) && startPos == loc.startPos;
}
public static SMLoc get(MemoryBuffer buf, int start) {
SMLoc loc = new SMLoc();
loc.buffer = buf;
loc.startPos = start;
return loc;
}
public static SMLoc get(MemoryBuffer buf) {
SMLoc loc = new SMLoc();
loc.buffer = buf;
loc.startPos = buf.getBufferStart();
return loc;
}
public boolean isValid() {
return buffer != null;
}
public int getPointer() {
return startPos;
}
}
static class SrcBuffer {
MemoryBuffer buffer;
/**
* This is the location of the parent include, or
* null if it is in the top level.
*/
SMLoc includeLoc;
}
private static class LineNoCache {
int lastQueryBufferID;
MemoryBuffer lastQuery;
int lineNoOfQuery;
}
/**
* This is all of the buffers that we are reading from.
*/
private ArrayList<SrcBuffer> buffers = new ArrayList<>();
/**
* This is the list of directories we should search for
* include files in.
*/
private LinkedList<String> includeDirs;
/**
* This s cache for line number queries.
*/
private LineNoCache lineNoCache;
public void setIncludeDirs(List<String> dirs) {
includeDirs = new LinkedList<>(dirs);
}
public SrcBuffer getBufferInfo(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i);
}
public MemoryBuffer getMemoryBuffer(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i).buffer;
}
public SMLoc getParentIncludeLoc(int i) {
Util.assertion(i >= 0 && i < buffers.size(), "Invalid buffer ID!");
return buffers.get(i).includeLoc;
}
public int addNewSourceBuffer(MemoryBuffer buf, SMLoc includeLoc) {
SrcBuffer buffer = new SrcBuffer();
buffer.buffer = buf;
buffer.includeLoc = includeLoc;
buffers.add(buffer);
return buffers.size() - 1;
}
/**
* Search for a file with the specified name in the current directory or
* in one of the {@linkplain #includeDirs}. If no such file found, this return
* ~0, otherwise it returns the buffer ID of the stacked file.
*
* @param filename
* @param includeLoc
* @return
*/
public int addIncludeFile(String filename, SMLoc includeLoc) {
MemoryBuffer newBuf = MemoryBuffer.getFile(filename);
for (int i = 0, e = includeDirs.size(); i < e && newBuf == null; i++) {
String incFile = includeDirs.get(i) + "/" + filename;
newBuf = MemoryBuffer.getFile(incFile);
}
if (newBuf == null)
return ~0;
return addNewSourceBuffer(newBuf, includeLoc);
}
/**
* Return the ID of the buffer containing the specified location, return -1
* if not found.
*
* @param loc
* @return
*/
public int findBufferContainingLoc(SMLoc loc) {
for (int i = 0, e = buffers.size(); i < e; i++) {
MemoryBuffer buf = buffers.get(i).buffer;
if (buf.contains(loc.buffer))
return i;
}
return ~0;
}
/**
* Find the line number for the specified location in the specified file.
*
* @param loc
* @param bufferID
* @return
*/
public int findLineNumber(SMLoc loc, int bufferID) {
if (bufferID == -1) bufferID = findBufferContainingLoc(loc);
Util.assertion(bufferID != -1, "Invalid location!");
int lineNo = 1;
MemoryBuffer buf = getBufferInfo(bufferID).buffer;
if (lineNoCache != null) {
if (lineNoCache.lastQueryBufferID == bufferID
&& lineNoCache.lastQuery.getCharBuffer().equals(buf.getCharBuffer())
&& lineNoCache.lastQuery.getBufferStart() <= buf.getBufferStart()) {
buf = lineNoCache.lastQuery;
lineNo = lineNoCache.lineNoOfQuery;
}
}
for (; !SMLoc.get(buf).equals(loc); buf.advance()) {
if (buf.getCurChar() == '\n')
++lineNo;
}
if (lineNoCache == null)
lineNoCache = new LineNoCache();
lineNoCache.lastQueryBufferID = bufferID;
lineNoCache.lastQuery = buf;
lineNoCache.lineNoOfQuery = lineNo;
return lineNo;
}
public int findLineNumber(SMLoc loc) {
return findLineNumber(loc, -1);
}
/**
* Emit a message about the specified location with the specified string.
* This method is deprecated, you should use {@linkplain Error#printMessage(SMLoc, String, DiagKind)} instead.
*
* @param loc
* @param msg
* @param type If not null, it specified the kind of message to be emitted (e.g. "error")
* which is prefixed to the message.
*/
@Deprecated
public void printMessage(SMLoc loc, String msg, String type) {
Error.printMessage(loc, msg, getDiagKindByName(type));
}
/**
* Return an SMDiagnostic at the specified location with the specified string.
*
* @param loc
* @param msg
* @param kind If not null, it specified the kind of message to be emitted (e.g. "error")
* which is prefixed to the message.
* @return
*/
public SMDiagnostic getMessage(SMLoc loc, String msg, DiagKind kind) {
int curBuf = findBufferContainingLoc(loc);
Util.assertion(curBuf != -1, "Invalid or unspecified location!");
MemoryBuffer curMB = getBufferInfo(curBuf).buffer;
Util.assertion(curMB.getCharBuffer() == loc.buffer.getCharBuffer());
int columnStart = loc.getPointer();
while (columnStart >= curMB.getBufferStart()
&& curMB.getCharAt(columnStart) != '\n'
&& curMB.getCharAt(columnStart) != '\r')
--columnStart;
int columnEnd = loc.getPointer();
while (columnEnd < curMB.length()
&& curMB.getCharAt(columnEnd) != '\n'
&& curMB.getCharAt(columnEnd) != '\r')
++columnEnd;
String printedMsg = "";
switch (kind) {
case DK_Error:
printedMsg = "error: ";
break;
case DK_Remark:
printedMsg = "remark: ";
break;
case DK_Note:
printedMsg = "note: ";
break;
case DK_Warning:
printedMsg = "warning: ";
break;
}
printedMsg += msg;
return new SMDiagnostic(curMB.getBufferIdentifier(), findLineNumber(loc, curBuf),
curMB.getBufferStart() - columnStart, printedMsg,
curMB.getSubString(columnStart, columnEnd));
}
private void printIncludeStack(SMLoc includeLoc, PrintStream os) {
// Top stack.
if (includeLoc.buffer == null) return;
int curBuf = findBufferContainingLoc(includeLoc);
Util.assertion(curBuf != -1, "Invalid or unspecified location!");
printIncludeStack(getBufferInfo(curBuf).includeLoc, os);
os.printf("Included from %s:%d:\n", getBufferInfo(curBuf).buffer.getBufferIdentifier(),
findLineNumber(includeLoc, curBuf));
}
}
|
JianpingZeng/xcc
|
xcc/java/tools/SourceMgr.java
|
Java
|
bsd-3-clause
| 8,511 |
package com.logicalpractice.collections;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.* ;
import org.junit.Test;
public class ExpressionTest {
@Test
public void script1() throws Exception {
Person billy = new Person("Billy", "Smith");
Expression<Person,String> testObject = new Expression<Person,String>(){{
each(Person.class).getFirstName();
}};
String result = testObject.apply(billy);
assertThat(result, equalTo("Billy"));
}
}
|
tempredirect/lps-collections
|
src/test/java/com/logicalpractice/collections/ExpressionTest.java
|
Java
|
bsd-3-clause
| 534 |
package com.btr.proxy.search.desktop.gnome;
import java.io.File;
import java.io.IOException;
import java.net.ProxySelector;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.btr.proxy.search.ProxySearchStrategy;
import com.btr.proxy.selector.direct.NoProxySelector;
import com.btr.proxy.selector.fixed.FixedProxySelector;
import com.btr.proxy.selector.misc.ProtocolDispatchSelector;
import com.btr.proxy.selector.whitelist.ProxyBypassListSelector;
import com.btr.proxy.util.EmptyXMLResolver;
import com.btr.proxy.util.Logger;
import com.btr.proxy.util.PlatformUtil;
import com.btr.proxy.util.ProxyException;
import com.btr.proxy.util.ProxyUtil;
import com.btr.proxy.util.Logger.LogLevel;
/*****************************************************************************
* Loads the Gnome proxy settings from the Gnome GConf settings.
* <p>
* The following settings are extracted from the configuration that is stored
* in <i>.gconf</i> folder found in the user's home directory:
* </p>
* <ul>
* <li><i>/system/http_proxy/use_http_proxy</i> -> bool used only by gnome-vfs </li>
* <li><i>/system/http_proxy/host</i> -> string "my-proxy.example.com" without "http://"</li>
* <li><i>/system/http_proxy/port</i> -> int</li>
* <li><i>/system/http_proxy/use_authentication</i> -> bool</li>
* <li><i>/system/http_proxy/authentication_user</i> -> string</li>
* <li><i>/system/http_proxy/authentication_password</i> -> string</li>
* <li><i>/system/http_proxy/ignore_hosts</i> -> list-of-string</li>
* <li><i>/system/proxy/mode</i> -> string THIS IS THE CANONICAL KEY; SEE BELOW</li>
* <li><i>/system/proxy/secure_host</i> -> string "proxy-for-https.example.com"</li>
* <li><i>/system/proxy/secure_port</i> -> int</li>
* <li><i>/system/proxy/ftp_host</i> -> string "proxy-for-ftp.example.com"</li>
* <li><i>/system/proxy/ftp_port</i> -> int</li>
* <li><i>/system/proxy/socks_host</i> -> string "proxy-for-socks.example.com"</li>
* <li><i>/system/proxy/socks_port</i> -> int</li>
* <li><i>/system/proxy/autoconfig_url</i> -> string "http://proxy-autoconfig.example.com"</li>
* </ul>
* <i>/system/proxy/mode</i> can be either:<br/>
* "none" -> No proxy is used<br/>
* "manual" -> The user's configuration values are used (/system/http_proxy/{host,port,etc.})<br/>
* "auto" -> The "/system/proxy/autoconfig_url" key is used <br/>
* <p>
* GNOME Proxy_configuration settings are explained
* <a href="http://en.opensuse.org/GNOME/Proxy_configuration">here</a> in detail
* </p>
* @author Bernd Rosstauscher (proxyvole@rosstauscher.de) Copyright 2009
****************************************************************************/
public class GnomeProxySearchStrategy implements ProxySearchStrategy {
/*************************************************************************
* ProxySelector
* @see java.net.ProxySelector#ProxySelector()
************************************************************************/
public GnomeProxySearchStrategy() {
super();
}
/*************************************************************************
* Loads the proxy settings and initializes a proxy selector for the Gnome
* proxy settings.
* @return a configured ProxySelector, null if none is found.
* @throws ProxyException on file reading error.
************************************************************************/
public ProxySelector getProxySelector() throws ProxyException {
Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings");
Properties settings = readSettings();
String type = settings.getProperty("/system/proxy/mode");
ProxySelector result = null;
if (type == null) {
String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy");
if (useProxy == null) {
return null;
}
type = Boolean.parseBoolean(useProxy)?"manual":"none";
}
if ("none".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy");
result = NoProxySelector.getInstance();
}
if ("manual".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings");
result = setupFixedProxySelector(settings);
}
if ("auto".equals(type)) {
String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", "");
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl);
result = ProxyUtil.buildPacSelectorForUrl(pacScriptUrl);
}
// Wrap into white-list filter?
String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null);
if (result != null && noProxyList != null && noProxyList.trim().length() > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList);
result = new ProxyBypassListSelector(noProxyList, result);
}
return result;
}
/*************************************************************************
* Load the proxy settings from the gconf settings XML file.
* @return the loaded settings stored in a properties object.
* @throws ProxyException on processing error.
************************************************************************/
public Properties readSettings() throws ProxyException {
Properties settings = new Properties();
try {
parseSettings("/system/proxy/", settings);
parseSettings("/system/http_proxy/", settings);
} catch (IOException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e);
throw new ProxyException(e);
}
return settings;
}
/*************************************************************************
* Finds the Gnome GConf settings file.
* @param context the gconf context to parse.
* @return a file or null if does not exist.
************************************************************************/
private File findSettingsFile(String context) {
// Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is.
// But for normal systems this is always stored in .gconf folder in the user's home directory.
File userDir = new File(PlatformUtil.getUserHomeDir());
// Build directory path for context
StringBuilder path = new StringBuilder();
String[] parts = context.split("/");
for (String part : parts) {
path.append(part);
path.append(File.separator);
}
File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml");
if (!settingsFile.exists()) {
Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile);
return null;
}
return settingsFile;
}
/*************************************************************************
* Parse the fixed proxy settings and build an ProxySelector for this a
* chained configuration.
* @param settings the proxy settings to evaluate.
************************************************************************/
private ProxySelector setupFixedProxySelector(Properties settings) {
if (!hasProxySettings(settings)) {
return null;
}
ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
installHttpSelector(settings, ps);
if (useForAllProtocols(settings)) {
ps.setFallbackSelector(ps.getSelector("http"));
} else {
installSecureSelector(settings, ps);
installFtpSelector(settings, ps);
installSocksSelector(settings, ps);
}
return ps;
}
/*************************************************************************
* Check if the http proxy should also be used for all other protocols.
* @param settings to inspect.
* @return true if only one proxy is configured else false.
************************************************************************/
private boolean useForAllProtocols(Properties settings) {
return Boolean.parseBoolean(
settings.getProperty("/system/http_proxy/use_same_proxy", "false"));
}
/*************************************************************************
* Checks if we have Proxy configuration settings in the properties.
* @param settings to inspect.
* @return true if we have found Proxy settings.
************************************************************************/
private boolean hasProxySettings(Properties settings) {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
return proxyHost != null && proxyHost.length() > 0;
}
/*************************************************************************
* Install a http proxy from the given settings.
* @param settings to inspect
* @param ps the dispatch selector to configure.
* @throws NumberFormatException
************************************************************************/
private void installHttpSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("http", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* Install a socks proxy from the given settings.
* @param settings to inspect
* @param ps the dispatch selector to configure.
* @throws NumberFormatException
************************************************************************/
private void installSocksSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/socks_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("socks", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* @param settings
* @param ps
* @throws NumberFormatException
************************************************************************/
private void installFtpSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/ftp_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("ftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* @param settings
* @param ps
* @throws NumberFormatException
************************************************************************/
private void installSecureSelector(Properties settings,
ProtocolDispatchSelector ps) throws NumberFormatException {
String proxyHost = settings.getProperty("/system/proxy/secure_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("https", new FixedProxySelector(proxyHost.trim(), proxyPort));
ps.setSelector("sftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
/*************************************************************************
* Parse the settings file and extract all network.proxy.* settings from it.
* @param context the gconf context to parse.
* @param settings the settings object to fill.
* @return the parsed properties.
* @throws IOException on read error.
************************************************************************/
private Properties parseSettings(String context, Properties settings) throws IOException {
// Read settings from file
File settingsFile = findSettingsFile(context);
if (settingsFile == null) {
return settings;
}
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
documentBuilder.setEntityResolver(new EmptyXMLResolver());
Document doc = documentBuilder.parse(settingsFile);
Element root = doc.getDocumentElement();
Node entry = root.getFirstChild();
while (entry != null) {
if ("entry".equals(entry.getNodeName()) && entry instanceof Element) {
String entryName = ((Element)entry).getAttribute("name");
settings.setProperty(context+entryName, getEntryValue((Element) entry));
}
entry = entry.getNextSibling();
}
} catch (SAXException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
} catch (ParserConfigurationException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
}
return settings;
}
/*************************************************************************
* Parse an entry value from a given entry node.
* @param entry the XML node to inspect.
* @return the value, null if it has no value.
************************************************************************/
private String getEntryValue(Element entry) {
String type = entry.getAttribute("type");
if ("int".equals(type) || "bool".equals(type)) {
return entry.getAttribute("value");
}
if ("string".equals(type)) {
NodeList list = entry.getElementsByTagName("stringvalue");
if (list.getLength() > 0) {
return list.item(0).getTextContent();
}
}
if ("list".equals(type)) {
StringBuilder result = new StringBuilder();
NodeList list = entry.getElementsByTagName("li");
// Build comma separated list of items
for (int i = 0; i < list.getLength(); i++) {
if (result.length() > 0) {
result.append(",");
}
result.append(getEntryValue((Element) list.item(i)));
}
return result.toString();
}
return null;
}
}
|
brsanthu/proxy-vole
|
src/main/java/com/btr/proxy/search/desktop/gnome/GnomeProxySearchStrategy.java
|
Java
|
bsd-3-clause
| 14,860 |
/*
* Copyright (C) 2014 The Async HBase Authors. All rights reserved.
* This file is part of Async HBase.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the StumbleUpon nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.hbase.async;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import java.nio.charset.Charset;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hbase.async.HBaseClient.ZKClient;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.channel.socket.nio.NioClientBossPool;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.junit.Before;
import org.junit.Ignore;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.reflect.Whitebox;
import com.stumbleupon.async.Deferred;
@PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class,
GetRequest.class, RegionInfo.class, NioClientSocketChannelFactory.class,
Executors.class, HashedWheelTimer.class, NioClientBossPool.class,
NioWorkerPool.class })
@Ignore // ignore for test runners
public class BaseTestHBaseClient {
protected static final Charset CHARSET = Charset.forName("ASCII");
protected static final byte[] COMMA = { ',' };
protected static final byte[] TIMESTAMP = "1234567890".getBytes();
protected static final byte[] INFO = getStatic("INFO");
protected static final byte[] REGIONINFO = getStatic("REGIONINFO");
protected static final byte[] SERVER = getStatic("SERVER");
protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' };
protected static final byte[] KEY = { 'k', 'e', 'y' };
protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' };
protected static final byte[] FAMILY = { 'f' };
protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' };
protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' };
protected static final byte[] EMPTY_ARRAY = new byte[0];
protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE);
protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890");
protected static final RegionInfo region = mkregion("table", "table,,1234567890");
protected static final int RS_PORT = 50511;
protected static final String ROOT_IP = "192.168.0.1";
protected static final String META_IP = "192.168.0.2";
protected static final String REGION_CLIENT_IP = "192.168.0.3";
protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient";
protected static String MOCK_ROOT_CLIENT_NAME = "Mock RootClient";
protected static String MOCK_META_CLIENT_NAME = "Mock MetaClient";
protected HBaseClient client = null;
/** Extracted from {@link #client}. */
protected ConcurrentSkipListMap<byte[], RegionInfo> regions_cache;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionInfo, RegionClient> region2client;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions;
/** Extracted from {@link #client}. */
protected ConcurrentSkipListMap<byte[], ArrayList<HBaseRpc>> got_nsre;
/** Extracted from {@link #client}. */
protected HashMap<String, RegionClient> ip2client;
/** Extracted from {@link #client}. */
protected Counter num_nsre_rpcs;
/** Fake client supposedly connected to -ROOT-. */
protected RegionClient rootclient;
/** Fake client supposedly connected to .META.. */
protected RegionClient metaclient;
/** Fake client supposedly connected to our fake test table. */
protected RegionClient regionclient;
/** Each new region client is dumped here */
protected List<RegionClient> region_clients = new ArrayList<RegionClient>();
/** Fake Zookeeper client */
protected ZKClient zkclient;
/** Fake channel factory */
protected NioClientSocketChannelFactory channel_factory;
/** Fake channel returned from the factory */
protected SocketChannel chan;
/** Fake timer for testing */
protected FakeTimer timer;
@Before
public void before() throws Exception {
region_clients.clear();
rootclient = mock(RegionClient.class);
when(rootclient.toString()).thenReturn(MOCK_ROOT_CLIENT_NAME);
metaclient = mock(RegionClient.class);
when(metaclient.toString()).thenReturn(MOCK_META_CLIENT_NAME);
regionclient = mock(RegionClient.class);
when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME);
zkclient = mock(ZKClient.class);
channel_factory = mock(NioClientSocketChannelFactory.class);
chan = mock(SocketChannel.class);
timer = new FakeTimer();
when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>());
PowerMockito.mockStatic(Executors.class);
PowerMockito.when(Executors.defaultThreadFactory())
.thenReturn(mock(ThreadFactory.class));
PowerMockito.when(Executors.newCachedThreadPool())
.thenReturn(mock(ExecutorService.class));
PowerMockito.whenNew(NioClientSocketChannelFactory.class).withAnyArguments()
.thenReturn(channel_factory);
PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments()
.thenReturn(timer);
PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments()
.thenReturn(mock(NioClientBossPool.class));
PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments()
.thenReturn(mock(NioWorkerPool.class));
client = PowerMockito.spy(new HBaseClient("test-quorum-spec"));
Whitebox.setInternalState(client, "zkclient", zkclient);
Whitebox.setInternalState(client, "rootregion", rootclient);
Whitebox.setInternalState(client, "jitter_percent", 0);
regions_cache = Whitebox.getInternalState(client, "regions_cache");
region2client = Whitebox.getInternalState(client, "region2client");
client2regions = Whitebox.getInternalState(client, "client2regions");
got_nsre = Whitebox.getInternalState(client, "got_nsre");
ip2client = Whitebox.getInternalState(client, "ip2client");
injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT);
injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT);
when(channel_factory.newChannel(any(ChannelPipeline.class)))
.thenReturn(chan);
when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class));
when(rootclient.toString()).thenReturn("Mock RootClient");
PowerMockito.doAnswer(new Answer<RegionClient>(){
@Override
public RegionClient answer(InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final String endpoint = (String)args[0] + ":" + (Integer)args[1];
final RegionClient rc = mock(RegionClient.class);
when(rc.getRemoteAddress()).thenReturn(endpoint);
client2regions.put(rc, new ArrayList<RegionInfo>());
region_clients.add(rc);
return rc;
}
}).when(client, "newClient", anyString(), anyInt());
}
/**
* Injects an entry in the local caches of the client.
*/
protected void injectRegionInCache(final RegionInfo region,
final RegionClient client,
final String ip) {
regions_cache.put(region.name(), region);
region2client.put(region, client);
ArrayList<RegionInfo> regions = client2regions.get(client);
if (regions == null) {
regions = new ArrayList<RegionInfo>(1);
client2regions.put(client, regions);
}
regions.add(region);
ip2client.put(ip, client);
}
// ----------------- //
// Helper functions. //
// ----------------- //
protected void clearCaches(){
regions_cache.clear();
region2client.clear();
client2regions.clear();
}
protected static <T> T getStatic(final String fieldname) {
return Whitebox.getInternalState(HBaseClient.class, fieldname);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for all keys of {@link #TABLE}.
*/
protected static ArrayList<KeyValue> metaRow() {
return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for {@link #TABLE}.
* @param start_key The start key of the region in this entry.
* @param stop_key The stop key of the region in this entry.
*/
protected static ArrayList<KeyValue> metaRow(final byte[] start_key,
final byte[] stop_key) {
final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2);
row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE));
row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes()));
return row;
}
protected static KeyValue metaRegionInfo( final byte[] start_key,
final byte[] stop_key, final boolean offline, final boolean splitting,
final byte[] table) {
final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP);
final byte is_splitting = (byte) (splitting ? 1 : 0);
final byte[] regioninfo = concat(
new byte[] {
0, // version
(byte) stop_key.length, // vint: stop key length
},
stop_key,
offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline
Bytes.fromLong(name.hashCode()), // long: region ID (make it random)
new byte[] { (byte) name.length }, // vint: region name length
name, // region name
new byte[] {
is_splitting, // boolean: splitting
(byte) start_key.length, // vint: start key length
},
start_key
);
return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo);
}
protected static RegionInfo mkregion(final String table, final String name) {
return new RegionInfo(table.getBytes(), name.getBytes(),
HBaseClient.EMPTY_ARRAY);
}
protected static byte[] anyBytes() {
return any(byte[].class);
}
/** Concatenates byte arrays together. */
protected static byte[] concat(final byte[]... arrays) {
int len = 0;
for (final byte[] array : arrays) {
len += array.length;
}
final byte[] result = new byte[len];
len = 0;
for (final byte[] array : arrays) {
System.arraycopy(array, 0, result, len, array.length);
len += array.length;
}
return result;
}
/** Creates a new Deferred that's already called back. */
protected static <T> Answer<Deferred<T>> newDeferred(final T result) {
return new Answer<Deferred<T>>() {
public Deferred<T> answer(final InvocationOnMock invocation) {
return Deferred.fromResult(result);
}
};
}
/**
* A fake {@link Timer} implementation that fires up tasks immediately.
* Tasks are called immediately from the current thread and a history of the
* various tasks is logged.
*/
static final class FakeTimer extends HashedWheelTimer {
final List<Map.Entry<TimerTask, Long>> tasks =
new ArrayList<Map.Entry<TimerTask, Long>>();
final ArrayList<Timeout> timeouts = new ArrayList<Timeout>();
boolean run = true;
@Override
public Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
try {
tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay));
if (run) {
task.run(null); // Argument never used in this code base.
}
final Timeout timeout = mock(Timeout.class);
timeouts.add(timeout);
return timeout; // Return value never used in this code base.
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + task, e);
}
}
@Override
public Set<Timeout> stop() {
run = false;
return new HashSet<Timeout>(timeouts);
}
}
/**
* A fake {@link org.jboss.netty.util.Timer} implementation.
* Instead of executing the task it will store that task in a internal state
* and provides a function to start the execution of the stored task.
* This implementation thus allows the flexibility of simulating the
* things that will be going on during the time out period of a TimerTask.
* This was mainly return to simulate the timeout period for
* alreadyNSREdRegion test, where the region will be in the NSREd mode only
* during this timeout period, which was difficult to simulate using the
* above {@link FakeTimer} implementation, as we don't get back the control
* during the timeout period
*
* Here it will hold at most two Tasks. We have two tasks here because when
* one is being executed, it may call for newTimeOut for another task.
*/
static final class FakeTaskTimer extends HashedWheelTimer {
protected TimerTask newPausedTask = null;
protected TimerTask pausedTask = null;
@Override
public synchronized Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
if (pausedTask == null) {
pausedTask = task;
} else if (newPausedTask == null) {
newPausedTask = task;
} else {
throw new IllegalStateException("Cannot Pause Two Timer Tasks");
}
return null;
}
@Override
public Set<Timeout> stop() {
return null;
}
public boolean continuePausedTask() {
if (pausedTask == null) {
return false;
}
try {
if (newPausedTask != null) {
throw new IllegalStateException("Cannot be in this state");
}
pausedTask.run(null); // Argument never used in this code base
pausedTask = newPausedTask;
newPausedTask = null;
return true;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + pausedTask, e);
}
}
}
/**
* Generate and return a mocked HBase RPC for testing purposes with a valid
* Deferred that can be called on execution.
* @param deferred A deferred to watch for results
* @return The RPC to pass through unit tests.
*/
protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) {
final HBaseRpc rpc = mock(HBaseRpc.class);
rpc.attempt = 0;
when(rpc.getDeferred()).thenReturn(deferred);
when(rpc.toString()).thenReturn("MockRPC");
PowerMockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (deferred != null) {
deferred.callback(invocation.getArguments()[0]);
} else {
System.out.println("Deferred was null!!");
}
return null;
}
}).when(rpc).callback(Object.class);
return rpc;
}
}
|
manolama/asynchbase
|
test/BaseTestHBaseClient.java
|
Java
|
bsd-3-clause
| 17,282 |
package xcordion.impl.command;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.Ignore;
public class ForEachCommandTest {
@Test
@Ignore
public void testPlaceholder() {
Assert.fail("WRITE ME");
}
}
|
pobrelkey/xcordion
|
xcordion2/xcordion2-java/src/test/java/xcordion/impl/command/ForEachCommandTest.java
|
Java
|
bsd-3-clause
| 282 |
/**
* Copyright (c) 2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms
*/
package visualoozie.api;
public class WorkflowNode {
public enum NodeType{
START
, KILL
, DECISION
, FORK
, JOIN
, END
, ACTION
}
private String name;
private NodeType type;
private String[] to;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public NodeType getType() { return type; }
public void setType(NodeType type) { this.type = type; }
public String[] getTo() { return to; }
public void setTo(String[] to) { this.to = to; }
}
|
jaoki/visualoozie
|
src/main/java/visualoozie/api/WorkflowNode.java
|
Java
|
bsd-3-clause
| 747 |
package com.navisens.pojostick.navishare;
import com.navisens.motiondnaapi.MotionDna;
import com.navisens.pojostick.navisenscore.*;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Created by Joseph on 11/30/17.
* <p>
* NaviShare provides functionality for communicating with other devices
* </p>
*/
@SuppressWarnings("unused")
public class NaviShare implements NavisensPlugin {
private static final long QUERY_INTERVAL = 500000000;
private String host, port, room;
private boolean changed;
private boolean configured;
private boolean connected;
private NavisensCore core;
private final Set<String> rooms;
private final Set<NaviShareListener> listeners;
private long roomsQueriedAt;
@SuppressWarnings("unused")
public NaviShare() {
this.rooms = new HashSet<>();
this.listeners = new HashSet<>();
this.roomsQueriedAt = System.nanoTime();
}
/**
* Configure a server. This does not connect to it yet, but is required before calling connect.
*
* @param host server ip
* @param port server port
* @return a reference to this NaviShare
*/
@SuppressWarnings("unused")
public NaviShare configure(String host, String port) {
core.getSettings().overrideHost(null, null);
this.host = host;
this.port = port;
this.changed = true;
this.configured = true;
return this;
}
/**
* Connect to a room in the server.
*
* @param room The room to connect to
* @return Whether this device connected to a server
*/
@SuppressWarnings("unused")
public boolean connect(String room) {
core.getSettings().overrideRoom(null);
if (configured) {
if (connected && !changed) {
core.getMotionDna().setUDPRoom(room);
} else {
this.disconnect();
core.getMotionDna().startUDP(room, host, port);
this.connected = true;
}
this.changed = false;
return true;
}
return false;
}
/**
* Disconnect from the server.
*/
@SuppressWarnings("unused")
public void disconnect() {
core.getMotionDna().stopUDP();
this.connected = false;
}
/**
* Connect to a public test server. Don't use this for official release, as it is public
* and can get filled up quickly. Each organization can claim one room, so if you need
* multiple independent servers within your organization, you should test on a private
* server instead, and use configure(host, port) to target that server instead.
*/
@SuppressWarnings("unused")
public boolean testConnect() {
if (!connected) {
this.disconnect();
core.getMotionDna().startUDP();
return this.connected = true;
}
return false;
}
/**
* Send a message to all other devices on the network
*
* @param msg A string to send, recommended web safe
*/
@SuppressWarnings("unused")
public void sendMessage(String msg) {
if (connected) {
core.getMotionDna().sendUDPPacket(msg);
}
}
/**
* Add a listener to receive network events
*
* @param listener The listener to receive events
* @return Whether the listener was added successfully
*/
@SuppressWarnings("unused")
public boolean addListener(NaviShareListener listener) {
return this.listeners.add(listener);
}
/**
* Remove a listener to stop receiving events
*
* @param listener Ths listener to remove
* @return Whether the listener was removed successfully
*/
@SuppressWarnings("unused")
public boolean removeListener(NaviShareListener listener) {
return this.listeners.remove(listener);
}
/**
* Track a room so you can query its status. Call refreshRoomStatus to
* receive a new roomStatus event
*
* @param room A room to track
* @return Whether the room was added to be tracked or not
*/
@SuppressWarnings("unused")
public boolean trackRoom(String room) {
return this.rooms.add(room);
}
/**
* Stop tracking a room. Call refreshRoomStatus to receive a new roomStatusEvent
*
* @param room A room to stop tracking
* @return Whether the room was removed from tracking or not
*/
@SuppressWarnings("unused")
public boolean untrackRoom(String room) {
return this.rooms.remove(room);
}
/**
* Refresh the status of any tracked rooms. Updates will be received from the
* roomOccupancyChanged event
* @return Whether a refresh request was sent or not
*/
@SuppressWarnings("unused")
public boolean refreshRoomStatus() {
final long now = System.nanoTime();
if (connected && now - roomsQueriedAt > QUERY_INTERVAL) {
roomsQueriedAt = now;
core.getMotionDna().sendUDPQueryRooms(rooms.toArray(new String[0]));
return true;
}
return false;
}
@Override
public boolean init(NavisensCore navisensCore, Object[] objects) {
this.core = navisensCore;
core.subscribe(this, NavisensCore.NETWORK_DATA);
core.getSettings().requestNetworkRate(100);
core.applySettings();
return true;
}
@Override
public boolean stop() {
this.disconnect();
core.remove(this);
return true;
}
@Override
public void receiveMotionDna(MotionDna motionDna) {
}
@Override
public void receiveNetworkData(MotionDna motionDna) {
}
@Override
public void receiveNetworkData(MotionDna.NetworkCode networkCode, Map<String, ?> map) {
switch (networkCode) {
case RAW_NETWORK_DATA:
for (NaviShareListener listener : listeners)
listener.messageReceived((String) map.get("ID"), (String) map.get("payload"));
break;
case ROOM_CAPACITY_STATUS:
for (NaviShareListener listener : listeners)
listener.roomOccupancyChanged((Map<String, Integer>) map.get("payload"));
break;
case EXCEEDED_SERVER_ROOM_CAPACITY:
for (NaviShareListener listener : listeners)
listener.serverCapacityExceeded();
this.disconnect();
break;
case EXCEEDED_ROOM_CONNECTION_CAPACITY:
for (NaviShareListener listener : listeners)
listener.roomCapacityExceeded();
this.disconnect();
break;
}
}
@Override
public void receivePluginData(String id, int operator, Object... payload) {
}
@Override
public void reportError(MotionDna.ErrorCode errorCode, String s) {
}
}
|
navisens/Android-Plugin
|
navishare/src/main/java/com/navisens/pojostick/navishare/NaviShare.java
|
Java
|
bsd-3-clause
| 6,973 |
package org.mafagafogigante.dungeon.stats;
import org.mafagafogigante.dungeon.game.Id;
import org.jetbrains.annotations.NotNull;
import java.io.Serializable;
/**
* CauseOfDeath class that defines what kind of death happened and the ID of the related Item or Spell.
*/
public class CauseOfDeath implements Serializable {
private static final CauseOfDeath UNARMED = new CauseOfDeath(TypeOfCauseOfDeath.UNARMED, new Id("UNARMED"));
private final TypeOfCauseOfDeath type;
private final Id id;
/**
* Constructs a CauseOfDeath with the specified TypeOfCauseOfDeath and ID.
*
* @param type a TypeOfCauseOfDeath
* @param id an ID
*/
public CauseOfDeath(@NotNull TypeOfCauseOfDeath type, @NotNull Id id) {
this.type = type;
this.id = id;
}
/**
* Convenience method that returns a CauseOfDeath that represents an unarmed kill.
*/
public static CauseOfDeath getUnarmedCauseOfDeath() {
return UNARMED;
}
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (object == null || getClass() != object.getClass()) {
return false;
}
CauseOfDeath that = (CauseOfDeath) object;
return id.equals(that.id) && type == that.type;
}
@Override
public int hashCode() {
int result = type.hashCode();
result = 31 * result + id.hashCode();
return result;
}
@Override
public String toString() {
return String.format("%s : %s", type, id);
}
}
|
ffurkanhas/dungeon
|
src/main/java/org/mafagafogigante/dungeon/stats/CauseOfDeath.java
|
Java
|
bsd-3-clause
| 1,483 |
package net.jloop.rejoice;
import net.jloop.rejoice.types.Symbol;
import net.jloop.rejoice.types.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class MacroHelper {
public static List<Value> collect(Env env, Iterator<Value> input, Symbol terminator) {
List<Value> output = new ArrayList<>();
while (true) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Input stream ended before finding the terminating symbol '" + terminator.print() + "'");
}
Value next = input.next();
if (next instanceof Symbol) {
if (next.equals(terminator)) {
return output;
}
Function function = env.lookup((Symbol) next);
if (function instanceof Macro) {
env.trace().push((Symbol) next);
Iterator<Value> values = ((Macro) function).call(env, input);
while (values.hasNext()) {
output.add(values.next());
}
env.trace().pop();
} else {
output.add(next);
}
} else {
output.add(next);
}
}
}
@SuppressWarnings("unchecked")
public static <T extends Value> T match(Iterator<Value> input, Type type) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match " + type.print());
}
Value next = input.next();
if (type == next.type()) {
return (T) next;
} else {
throw new RuntimeError("MACRO", "Expecting to match " + type.print() + ", but found " + next.type().print() + " with value '" + next.print() + "'");
}
}
public static void match(Iterator<Value> input, Symbol symbol) {
if (!input.hasNext()) {
throw new RuntimeError("MACRO", "Unexpected EOF when attempting to match ^symbol '" + symbol.print() + "'");
}
Value next = input.next();
if (!next.equals(symbol)) {
throw new RuntimeError("MACRO", "Expecting to match symbol '" + symbol.print() + "' , but found " + next.type().print() + " with value '" + next.print() + "'");
}
}
}
|
jeremyheiler/rejoice
|
src/main/java/net/jloop/rejoice/MacroHelper.java
|
Java
|
bsd-3-clause
| 2,365 |
/*
* Copyright Matt Palmer 2011-2013, All rights reserved.
*
* This code is licensed under a standard 3-clause BSD license:
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * The names of its contributors may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.byteseek.searcher.sequence.sunday;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import net.byteseek.io.reader.Window;
import net.byteseek.io.reader.WindowReader;
import net.byteseek.matcher.bytes.ByteMatcher;
import net.byteseek.matcher.sequence.SequenceMatcher;
import net.byteseek.object.factory.DoubleCheckImmutableLazyObject;
import net.byteseek.object.factory.LazyObject;
import net.byteseek.object.factory.ObjectFactory;
import net.byteseek.searcher.SearchResult;
import net.byteseek.searcher.SearchUtils;
import net.byteseek.searcher.sequence.AbstractSequenceSearcher;
/**
*
* @author Matt Palmer
*/
public final class SundayQuickSearcher extends AbstractSequenceSearcher {
private final LazyObject<int[]> forwardInfo;
private final LazyObject<int[]> backwardInfo;
/**
* Constructs a Sunday Quick searcher given a {@link SequenceMatcher}
* to search for.
*
* @param sequence The sequence to search for.
*/
public SundayQuickSearcher(final SequenceMatcher sequence) {
super(sequence);
forwardInfo = new DoubleCheckImmutableLazyObject<int[]>(new ForwardInfoFactory());
backwardInfo = new DoubleCheckImmutableLazyObject<int[]>(new BackwardInfoFactory());
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> searchForwards(final byte[] bytes, final int fromPosition, final int toPosition) {
// Get the objects needed to search:
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
// Calculate safe bounds for the search:
final int length = sequence.length();
final int finalPosition = bytes.length - length;
final int lastLoopPosition = finalPosition - 1;
final int lastPosition = toPosition < lastLoopPosition?
toPosition : lastLoopPosition;
int searchPosition = fromPosition > 0?
fromPosition : 0;
// Search forwards. The loop does not check for the final
// position, as we shift on the byte after the sequence.
while (searchPosition <= lastPosition) {
if (sequence.matchesNoBoundsCheck(bytes, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition += safeShifts[bytes[searchPosition + length] & 0xFF];
}
// Check the final position if necessary:
if (searchPosition == finalPosition &&
toPosition >= finalPosition &&
sequence.matches(bytes, finalPosition)) {
return SearchUtils.singleResult(finalPosition, sequence);
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> doSearchForwards(final WindowReader reader,
final long fromPosition, final long toPosition ) throws IOException {
// Initialise
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
final int length = sequence.length();
long searchPosition = fromPosition;
// While there is a window to search in...
// If there is no window immediately after the sequence,
// then there is no match, since this is only invoked if the
// sequence is already crossing into another window.
Window window;
while (searchPosition <= toPosition &&
(window = reader.getWindow(searchPosition + length)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition + length);
final int arrayEndPosition = window.length() - 1;
final long distanceToEnd = toPosition - window.getWindowPosition() + length ;
final int finalPosition = distanceToEnd < arrayEndPosition?
(int) distanceToEnd : arrayEndPosition;
int arraySearchPosition = arrayStartPosition;
// Search fowards in the array using the reader interface to match.
// The loop does not check the final position, as we shift on the byte
// after the sequence (so would get an IndexOutOfBoundsException in the final position).
while (arraySearchPosition < finalPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
final int shift = safeShifts[array[arraySearchPosition] & 0xFF];
searchPosition += shift;
arraySearchPosition += shift;
}
// Check final position if necessary:
if (arraySearchPosition == finalPosition ||
searchPosition == toPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition += safeShifts[array[arraySearchPosition] & 0xFF];
}
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> searchBackwards(final byte[] bytes, final int fromPosition, final int toPosition) {
// Get objects needed to search:
final int[] safeShifts = backwardInfo.get();
final SequenceMatcher sequence = getMatcher();
// Calculate safe bounds for the search:
final int lastLoopPosition = toPosition > 1?
toPosition : 1;
final int firstPossiblePosition = bytes.length - sequence.length();
int searchPosition = fromPosition < firstPossiblePosition ?
fromPosition : firstPossiblePosition;
// Search backwards. The loop does not check the
// first position in the array, because we shift on the byte
// immediately before the current search position.
while (searchPosition >= lastLoopPosition) {
if (sequence.matchesNoBoundsCheck(bytes, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition -= safeShifts[bytes[searchPosition - 1] & 0xFF];
}
// Check for first position if necessary:
if (searchPosition == 0 &&
toPosition < 1 &&
sequence.matches(bytes, 0)) {
return SearchUtils.singleResult(0, sequence);
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public List<SearchResult<SequenceMatcher>> doSearchBackwards(final WindowReader reader,
final long fromPosition, final long toPosition ) throws IOException {
// Initialise
final int[] safeShifts = forwardInfo.get();
final SequenceMatcher sequence = getMatcher();
long searchPosition = fromPosition;
// While there is a window to search in...
// If there is no window immediately before the sequence,
// then there is no match, since this is only invoked if the
// sequence is already crossing into another window.
Window window;
while (searchPosition >= toPosition &&
(window = reader.getWindow(searchPosition - 1)) != null) {
// Initialise array search:
final byte[] array = window.getArray();
final int arrayStartPosition = reader.getWindowOffset(searchPosition - 1);
// Search to the beginning of the array, or the final search position,
// whichver comes first.
final long endRelativeToWindow = toPosition - window.getWindowPosition();
final int arrayEndSearchPosition = endRelativeToWindow > 0?
(int) endRelativeToWindow : 0;
int arraySearchPosition = arrayStartPosition;
// Search backwards in the array using the reader interface to match.
// The loop does not check the final position, as we shift on the byte
// before it.
while (arraySearchPosition > arrayEndSearchPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
final int shift = safeShifts[array[arraySearchPosition] & 0xFF];
searchPosition -= shift;
arraySearchPosition -= shift;
}
// Check final position if necessary:
if (arraySearchPosition == arrayEndSearchPosition ||
searchPosition == toPosition) {
if (sequence.matches(reader, searchPosition)) {
return SearchUtils.singleResult(searchPosition, sequence);
}
searchPosition -= safeShifts[array[arraySearchPosition] & 0xFF];
}
}
return SearchUtils.noResults();
}
/**
* {@inheritDoc}
*/
@Override
public void prepareForwards() {
forwardInfo.get();
}
/**
* {@inheritDoc}
*/
@Override
public void prepareBackwards() {
backwardInfo.get();
}
@Override
public String toString() {
return getClass().getSimpleName() + "[sequence:" + matcher + ']';
}
private final class ForwardInfoFactory implements ObjectFactory<int[]> {
private ForwardInfoFactory() {
}
/**
* Calculates the safe shifts to use if searching forwards.
* A safe shift is either the length of the sequence plus one, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the end of the matcher.
*/
@Override
public int[] create() {
// First set the default shift to the length of the sequence plus one.
final int[] shifts = new int[256];
final SequenceMatcher sequence = getMatcher();
final int numBytes = sequence.length();
Arrays.fill(shifts, numBytes + 1);
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the end of the sequence, where the last position equals 1.
// Each position can match more than one byte (e.g. if a byte class appears).
for (int sequenceByteIndex = 0; sequenceByteIndex < numBytes; sequenceByteIndex++) {
final ByteMatcher aMatcher = sequence.getMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
final int distanceFromEnd = numBytes - sequenceByteIndex;
for (final byte b : matchingBytes) {
shifts[b & 0xFF] = distanceFromEnd;
}
}
return shifts;
}
}
private final class BackwardInfoFactory implements ObjectFactory<int[]> {
private BackwardInfoFactory() {
}
/**
* Calculates the safe shifts to use if searching backwards.
* A safe shift is either the length of the sequence plus one, if the
* byte does not appear in the {@link SequenceMatcher}, or
* the shortest distance it appears from the beginning of the matcher.
*/
@Override
public int[] create() {
// First set the default shift to the length of the sequence
// (negative if search direction is reversed)
final int[] shifts = new int[256];
final SequenceMatcher sequence = getMatcher();
final int numBytes = sequence.length();
Arrays.fill(shifts, numBytes + 1);
// Now set specific byte shifts for the bytes actually in
// the sequence itself. The shift is the distance of each character
// from the start of the sequence, where the first position equals 1.
// Each position can match more than one byte (e.g. if a byte class appears).
for (int sequenceByteIndex = numBytes - 1; sequenceByteIndex >= 0; sequenceByteIndex--) {
final ByteMatcher aMatcher = sequence.getMatcherForPosition(sequenceByteIndex);
final byte[] matchingBytes = aMatcher.getMatchingBytes();
final int distanceFromStart = sequenceByteIndex + 1;
for (final byte b : matchingBytes) {
shifts[b & 0xFF] = distanceFromStart;
}
}
return shifts;
}
}
}
|
uzen/byteseek
|
src/net/byteseek/searcher/sequence/sunday/SundayQuickSearcher.java
|
Java
|
bsd-3-clause
| 14,817 |
/**
* Copyright (c) 2013, impossibl.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of impossibl.com nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.impossibl.postgres.system.procs;
/**
* Marker interface for dynamically loaded postgis data types, to be used by {@link ServiceLoader}.
*/
public interface OptionalProcProvider extends ProcProvider {
}
|
frode-carlsen/pgjdbc-ng
|
src/main/java/com/impossibl/postgres/system/procs/OptionalProcProvider.java
|
Java
|
bsd-3-clause
| 1,789 |
//
// $Id$
package org.ductilej.tests;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests handling of varags with parameterized variable argument. Edge case extraordinaire!
*/
public class ParamVarArgsTest
{
public static interface Predicate<T> {
boolean apply (T arg);
}
public static <T> Predicate<T> or (final Predicate<? super T>... preds) {
return new Predicate<T>() {
public boolean apply (T arg) {
for (Predicate<? super T> pred : preds) {
if (pred.apply(arg)) {
return true;
}
}
return false;
}
};
}
@SuppressWarnings("unchecked") // this use of parameterized varargs is safe
@Test public void testParamVarArgs () {
Predicate<Integer> test = or(FALSE);
assertEquals(false, test.apply(1));
}
protected static final Predicate<Integer> FALSE = new Predicate<Integer>() {
public boolean apply (Integer arg) {
return false;
}
};
}
|
scaladyno/ductilej
|
src/test/java/org/ductilej/tests/ParamVarArgsTest.java
|
Java
|
bsd-3-clause
| 1,100 |
package ga;
import engine.*;
import java.util.*;
public class GAPopulation {
/* Evolutionary parameters: */
public int size; // size of the population
public int ngens; // total number of generations
public int currgen; // current generation
/* Crossover parameters */
int tournamentK; // size of tournament
int elite; // size of elite
int immigrant; // number of new random individuals
double mutrate; // chance that a mutation will occur
double xoverrate; // chance that the xover will occur
/* Containers */
public ArrayList<Genome> individual;
Genome parent;
Trainer T;
/* Progress data */
public double[] max_fitness;
public double[] avg_fitness;
public double[] terminals; // average total number of terminals
public double[] bigterminals; // average total number of sig. terminals
/**
* Initialize and load parameters.
* Parameter comp is a node from a previous
* scenario, which is used for distance calculations.
*/
public GAPopulation(Genome comp)
{
individual = new ArrayList<Genome>();
parent = comp;
// reading parameters
Parameter param = Parameter.getInstance();
String paramval;
paramval = param.getParam("population size");
if (paramval != null)
size = Integer.valueOf(paramval);
else
{
System.err.println("\"population size\" not defined on parameter file.");
size = 10;
}
paramval = param.getParam("generation number");
if (paramval != null)
ngens = Integer.valueOf(paramval);
else
{
System.err.println("\"generation number\" not defined on parameter file.");
ngens = 10;
}
paramval = param.getParam("tournament K");
if (paramval != null)
tournamentK = Integer.valueOf(paramval);
else
{
System.err.println("\"tournament K\" not defined on parameter file.");
tournamentK = 5;
}
paramval = param.getParam("elite size");
if (paramval != null)
elite = Integer.valueOf(paramval);
else
{
System.err.println("\"elite size\" not defined on parameter file.");
elite = 1;
}
paramval = param.getParam("immigrant size");
if (paramval != null)
immigrant = Integer.valueOf(paramval);
else
{
System.err.println("\"immigrant size\" not defined on parameter file.");
immigrant = 0;;
}
paramval = param.getParam("mutation rate");
if (paramval != null)
mutrate = Double.valueOf(paramval);
else
{
System.err.println("\"mutation rate\" not defined on parameter file.");
mutrate = 0.01;
}
paramval = param.getParam("crossover rate");
if (paramval != null)
xoverrate = Double.valueOf(paramval);
else
{
System.err.println("\"crossover rate\" not defined on parameter file.");
xoverrate = 0.9;
}
}
/**
* Initialize the new population and the local
* variables. Startd is the target date for the
* @param startd
*/
public void initPopulation(Date startd)
{
T = new Trainer(startd);
currgen = 0;
for (int i = 0; i < size; i++)
{
Genome n = new Genome();
n.init();
individual.add(n);
}
max_fitness = new double[ngens];
avg_fitness = new double[ngens];
terminals = new double[ngens];
bigterminals = new double[ngens];
}
/**
* Runs one generation loop
*
*/
public void runGeneration()
{
eval();
breed();
currgen++;
}
/**
* update the values of the maxfitness/avg fitness/etc
* public arrays;
*/
public void updateStatus()
{
Parameter p = Parameter.getInstance();
String param = p.getParam("asset treshold");
double tresh = Double.valueOf(param);
avg_fitness[currgen-1] = 0;
terminals[currgen-1] = 0;
bigterminals[currgen-1] = 0;
for (int i = 0; i < individual.size(); i++)
{
avg_fitness[currgen-1] += individual.get(i).fitness;
terminals[currgen-1] += individual.get(i).countAsset(0.0);
bigterminals[currgen-1] += individual.get(i).countAsset(tresh);
}
max_fitness[currgen-1] = individual.get(0).fitness;
avg_fitness[currgen-1] /= size;
terminals[currgen-1] /= size;
bigterminals[currgen-1] /= size;
}
/**
* Calculates the fitness value for each individual
* in the population.
*/
public void eval()
{
for (int i = 0; i < size; i++)
{
individual.get(i).eval(T);
}
Collections.sort(individual);
}
/**
* Perform selection, crossover, mutation in
* order to create a new population.
*
* Assumes the eval function has already been
* performed.
*
*/
public void breed()
{
RNG d = RNG.getInstance();
ArrayList<Genome> nextGen = new ArrayList<Genome>();
Genome p1,p2;
// elite: (few copied individuals)
for (int i = 0; i < elite; i++)
{
nextGen.add(individual.get(i).copy());
}
// immigrant: (usually 0)
for (int i = 0; i < immigrant; i++)
{
Genome n = new Genome();
n.init();
nextGen.add(n);
}
// crossover:
for (int i = 0; i < size - (immigrant + elite); i+=2)
{
// selection - the selection function should
// return copies already.
p1 = Tournament();
p2 = Tournament();
// rolls for xover
if (d.nextDouble() < xoverrate)
{
p1.crossover(p2);
}
// rolls for mutation
if (d.nextDouble() < mutrate)
p1.mutation();
if (d.nextDouble() < mutrate)
p2.mutation();
nextGen.add(p1);
nextGen.add(p2);
}
individual = nextGen;
}
/**
* Select one parent from the population by using
* fitness-proportional tournament selection
* (eat candidate has a chance proportional to his
* fitness of being chosen).
*
* The function copy the chosen candidate and send
* him back.
* @return
*/
public Genome Tournament()
{
RNG d = RNG.getInstance();
Genome[] list = new Genome[tournamentK];
double[] rank = new double[tournamentK];
double sum = 0.0;
double ticket = 0.0;
double min = 0.0;
/* Selects individuals and removes negative fitness */
for (int i = 0; i < tournamentK; i++)
{
list[i] = individual.get(d.nextInt(size));
if (list[i].fitness < min)
min = list[i].fitness;
}
/* I'm not sure if this is the best way to
* make the proportion between the fitnesses.
* Some sort of scaling factor should be put here
* to avoit high fitnesses from superdominating.
*
* But maybe the tournament proccess already guarantees this?
*/
for (int i = 0; i < tournamentK; i++)
{
sum += list[i].fitness - min;
rank[i] = sum;
}
ticket = d.nextDouble()*sum;
for (int i = 0; i < tournamentK; i++)
{
if ((ticket) <= rank[i])
return list[i].copy();
}
// should never get here
System.err.println("x" + ticket + " + " + sum);
System.err.println("Warning: MemeTournament - reached unreachable line");
return list[0].copy();
}
}
|
caranha/MTGA-old
|
code/ga/GAPopulation.java
|
Java
|
bsd-3-clause
| 6,710 |
/**
* (c) 2017 TIBCO Software Inc. All rights reserved.
*
* Except as specified below, this software is licensed pursuant to the Eclipse Public License v. 1.0.
* The details can be found in the file LICENSE.
*
* The following proprietary files are included as a convenience, and may not be used except pursuant
* to valid license to Composite Information Server or TIBCO(R) Data Virtualization Server:
* csadmin-XXXX.jar, csarchive-XXXX.jar, csbase-XXXX.jar, csclient-XXXX.jar, cscommon-XXXX.jar,
* csext-XXXX.jar, csjdbc-XXXX.jar, csserverutil-XXXX.jar, csserver-XXXX.jar, cswebapi-XXXX.jar,
* and customproc-XXXX.jar (where -XXXX is an optional version number). Any included third party files
* are licensed under the terms contained in their own accompanying LICENSE files, generally named .LICENSE.txt.
*
* This software is licensed AS-IS. Support for this software is not covered by standard maintenance agreements with TIBCO.
* If you would like to obtain assistance with this software, such assistance may be obtained through a separate paid consulting
* agreement with TIBCO.
*
*/
package com.tibco.ps.deploytool.services;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContextException;
import com.tibco.ps.common.CommonConstants;
import com.tibco.ps.common.exception.CompositeException;
import com.tibco.ps.common.util.CommonUtils;
import com.tibco.ps.deploytool.dao.ServerDAO;
import com.tibco.ps.deploytool.dao.wsapi.ServerWSDAOImpl;
public class ServerManagerImpl implements ServerManager {
private ServerDAO serverDAO = null;
// Get the configuration property file set in the environment with a default of deploy.properties
String propertyFile = CommonUtils.getFileOrSystemPropertyValue(CommonConstants.propertyFile, "CONFIG_PROPERTY_FILE");
private static Log logger = LogFactory.getLog(ServerManagerImpl.class);
// @Override
public void startServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "startServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.START.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while starting server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
// @Override
public void stopServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "stopServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.STOP.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while stopping server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
// @Override
public void restartServer(String serverId, String pathToServersXML) throws CompositeException {
String prefix = "restartServer";
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
if(logger.isDebugEnabled()){
logger.debug(" Entering ServerManagerImpl.start() with following params - serverId: " + serverId + ", pathToServersXML: " + pathToServersXML);
}
try {
serverManagerAction(ServerDAO.action.RESTART.name(), serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error while restarting server: " , e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
private void serverManagerAction(String actionName, String serverId, String pathToServersXML) throws CompositeException {
String prefix = "serverManagerAction";
String processedIds = null;
// Extract variables for the serverId
serverId = CommonUtils.extractVariable(prefix, serverId, propertyFile, true);
// Set the Module Action Objective
String s1 = (serverId == null) ? "no_serverId" : "Ids="+serverId;
System.setProperty("MODULE_ACTION_OBJECTIVE", actionName+" : "+s1);
// Validate whether the files exist or not
if (!CommonUtils.fileExists(pathToServersXML)) {
throw new CompositeException("File ["+pathToServersXML+"] does not exist.");
}
try {
if(logger.isInfoEnabled()){
logger.info("processing action "+ actionName + " on server "+ serverId);
}
getServerDAO().takeServerManagerAction(actionName, serverId, pathToServersXML);
} catch (CompositeException e) {
logger.error("Error on server action (" + actionName + "): ", e);
throw new ApplicationContextException(e.getMessage(), e);
}
}
/**
* @return serverDAO
*/
public ServerDAO getServerDAO() {
if(this.serverDAO == null){
this.serverDAO = new ServerWSDAOImpl();
}
return serverDAO;
}
/**
* @param set serverDAO
*/
public void setServerDAO(ServerDAO serverDAO) {
this.serverDAO = serverDAO;
}
}
|
cisco/PDTool
|
src/com/tibco/ps/deploytool/services/ServerManagerImpl.java
|
Java
|
bsd-3-clause
| 5,374 |
/*
* Created on Oct 18, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.tolweb.tapestry;
import java.util.Collection;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.IRequestCycle;
import org.tolweb.hibernate.TitleIllustration;
import org.tolweb.tapestry.injections.BaseInjectable;
import org.tolweb.tapestry.injections.ImageInjectable;
import org.tolweb.treegrow.main.Contributor;
import org.tolweb.treegrow.main.ImageVersion;
import org.tolweb.treegrow.main.NodeImage;
import org.tolweb.treegrow.main.StringUtils;
/**
* @author dmandel
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public abstract class TitleIllustrations extends BaseComponent implements
ImageInjectable, BaseInjectable {
@SuppressWarnings("unchecked")
public abstract Collection getIllustrations();
public abstract TitleIllustration getCurrentIllustration();
public abstract void setCurrentIllustration(TitleIllustration value);
public abstract void setIsSingleIllustration(boolean value);
public abstract boolean getIsSingleIllustration();
public abstract int getIndex();
public abstract void setContributor(Contributor contributor);
public String getAltText() {
if (getCurrentIllustration().getImage() != null) {
NodeImage img = getCurrentIllustration().getImage();
if (StringUtils.notEmpty(img.getAltText())) {
return img.getAltText();
} else {
return " ";
}
} else {
return " ";
}
}
public void prepareForRender(IRequestCycle cycle) {
super.prepareForRender(cycle);
if (getIllustrations() != null && getIllustrations().size() == 1) {
setIsSingleIllustration(true);
} else {
setIsSingleIllustration(false);
}
}
public String getCurrentImageLocation() {
TitleIllustration currentIllustration = getCurrentIllustration();
ImageVersion version = currentIllustration.getVersion();
String url;
if (StringUtils.isEmpty(version.getFileName())) {
url = getImageDAO().generateAndSaveVersion(version);
} else {
url = getImageUtils().getVersionUrl(currentIllustration.getVersion());
}
return url;
}
public String getCurrentImageClass() {
if (getIsSingleIllustration()) {
return "singletillus";
} else {
return null;
}
}
}
|
tolweb/tolweb-app
|
OnlineContributors/src/org/tolweb/tapestry/TitleIllustrations.java
|
Java
|
bsd-3-clause
| 2,683 |
/*
* GaussianKernel.java
*
* Created on September 25, 2004, 4:52 PM
*/
package jpview.graphics;
/**
* This class creates a kernel for use by an AffineTransformOp
*
* @author clyon
*/
public class GaussianKernel {
private int radius = 5;
private float sigma = 1;
private float[] kernel;
/** Creates a new instance of GaussianKernel */
public GaussianKernel() {
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius
*
* @param r
* the radius for the gaussian kernel
*/
public GaussianKernel(int r) {
radius = r;
kernel = makeKernel();
}
/**
* Creates a gaussian kernel with the provided radius and sigma value
*
* @param r
* the radius of the blur
* @param s
* the sigma value for the kernel
*/
public GaussianKernel(int r, float s) {
radius = r;
sigma = s;
kernel = makeKernel();
}
private float[] makeKernel() {
kernel = new float[radius * radius];
float sum = 0;
for (int y = 0; y < radius; y++) {
for (int x = 0; x < radius; x++) {
int off = y * radius + x;
int xx = x - radius / 2;
int yy = y - radius / 2;
kernel[off] = (float) Math.pow(Math.E, -(xx * xx + yy * yy)
/ (2 * (sigma * sigma)));
sum += kernel[off];
}
}
for (int i = 0; i < kernel.length; i++)
kernel[i] /= sum;
return kernel;
}
/**
* Dumps a string representation of the kernel to standard out
*/
public void dump() {
for (int x = 0; x < radius; x++) {
for (int y = 0; y < radius; y++) {
System.out.print(kernel[y * radius + x] + "\t");
}
System.out.println();
}
}
/**
* returns the kernel as a float [] suitable for use with an affine
* transform
*
* @return the kernel values
*/
public float[] getKernel() {
return kernel;
}
public static void main(String args[]) {
GaussianKernel gk = new GaussianKernel(5, 100f);
gk.dump();
}
}
|
synergynet/synergynet3
|
synergynet3-museum-parent/synergynet3-museum-table/src/main/java/jpview/graphics/GaussianKernel.java
|
Java
|
bsd-3-clause
| 2,024 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net.impl;
import android.content.Context;
import android.os.Build;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.util.Log;
import org.chromium.base.ObserverList;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.NativeClassQualifiedName;
import org.chromium.base.annotations.UsedByReflection;
import org.chromium.net.BidirectionalStream;
import org.chromium.net.CronetEngine;
import org.chromium.net.NetworkQualityRttListener;
import org.chromium.net.NetworkQualityThroughputListener;
import org.chromium.net.RequestFinishedInfo;
import org.chromium.net.UrlRequest;
import org.chromium.net.urlconnection.CronetHttpURLConnection;
import org.chromium.net.urlconnection.CronetURLStreamHandlerFactory;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.concurrent.GuardedBy;
/**
* CronetEngine using Chromium HTTP stack implementation.
*/
@JNINamespace("cronet")
@UsedByReflection("CronetEngine.java")
@VisibleForTesting
public class CronetUrlRequestContext extends CronetEngine {
private static final int LOG_NONE = 3; // LOG(FATAL), no VLOG.
private static final int LOG_DEBUG = -1; // LOG(FATAL...INFO), VLOG(1)
private static final int LOG_VERBOSE = -2; // LOG(FATAL...INFO), VLOG(2)
static final String LOG_TAG = "ChromiumNetwork";
/**
* Synchronize access to mUrlRequestContextAdapter and shutdown routine.
*/
private final Object mLock = new Object();
private final ConditionVariable mInitCompleted = new ConditionVariable(false);
private final AtomicInteger mActiveRequestCount = new AtomicInteger(0);
private long mUrlRequestContextAdapter = 0;
private Thread mNetworkThread;
private boolean mNetworkQualityEstimatorEnabled;
/**
* Locks operations on network quality listeners, because listener
* addition and removal may occur on a different thread from notification.
*/
private final Object mNetworkQualityLock = new Object();
/**
* Locks operations on the list of RequestFinishedInfo.Listeners, because operations can happen
* on any thread.
*/
private final Object mFinishedListenerLock = new Object();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityRttListener> mRttListenerList =
new ObserverList<NetworkQualityRttListener>();
@GuardedBy("mNetworkQualityLock")
private final ObserverList<NetworkQualityThroughputListener> mThroughputListenerList =
new ObserverList<NetworkQualityThroughputListener>();
@GuardedBy("mFinishedListenerLock")
private final List<RequestFinishedInfo.Listener> mFinishedListenerList =
new ArrayList<RequestFinishedInfo.Listener>();
/**
* Synchronize access to mCertVerifierData.
*/
private ConditionVariable mWaitGetCertVerifierDataComplete = new ConditionVariable();
/** Holds CertVerifier data. */
private String mCertVerifierData;
@UsedByReflection("CronetEngine.java")
public CronetUrlRequestContext(final CronetEngine.Builder builder) {
CronetLibraryLoader.ensureInitialized(builder.getContext(), builder);
nativeSetMinLogLevel(getLoggingLevel());
synchronized (mLock) {
mUrlRequestContextAdapter = nativeCreateRequestContextAdapter(
createNativeUrlRequestContextConfig(builder.getContext(), builder));
if (mUrlRequestContextAdapter == 0) {
throw new NullPointerException("Context Adapter creation failed.");
}
mNetworkQualityEstimatorEnabled = builder.networkQualityEstimatorEnabled();
}
// Init native Chromium URLRequestContext on main UI thread.
Runnable task = new Runnable() {
@Override
public void run() {
CronetLibraryLoader.ensureInitializedOnMainThread(builder.getContext());
synchronized (mLock) {
// mUrlRequestContextAdapter is guaranteed to exist until
// initialization on main and network threads completes and
// initNetworkThread is called back on network thread.
nativeInitRequestContextOnMainThread(mUrlRequestContextAdapter);
}
}
};
// Run task immediately or post it to the UI thread.
if (Looper.getMainLooper() == Looper.myLooper()) {
task.run();
} else {
new Handler(Looper.getMainLooper()).post(task);
}
}
@VisibleForTesting
public static long createNativeUrlRequestContextConfig(
final Context context, CronetEngine.Builder builder) {
final long urlRequestContextConfig = nativeCreateRequestContextConfig(
builder.getUserAgent(), builder.storagePath(), builder.quicEnabled(),
builder.getDefaultQuicUserAgentId(context), builder.http2Enabled(),
builder.sdchEnabled(), builder.dataReductionProxyKey(),
builder.dataReductionProxyPrimaryProxy(), builder.dataReductionProxyFallbackProxy(),
builder.dataReductionProxySecureProxyCheckUrl(), builder.cacheDisabled(),
builder.httpCacheMode(), builder.httpCacheMaxSize(), builder.experimentalOptions(),
builder.mockCertVerifier(), builder.networkQualityEstimatorEnabled(),
builder.publicKeyPinningBypassForLocalTrustAnchorsEnabled(),
builder.certVerifierData());
for (Builder.QuicHint quicHint : builder.quicHints()) {
nativeAddQuicHint(urlRequestContextConfig, quicHint.mHost, quicHint.mPort,
quicHint.mAlternatePort);
}
for (Builder.Pkp pkp : builder.publicKeyPins()) {
nativeAddPkp(urlRequestContextConfig, pkp.mHost, pkp.mHashes, pkp.mIncludeSubdomains,
pkp.mExpirationDate.getTime());
}
return urlRequestContextConfig;
}
@Override
public UrlRequest createRequest(String url, UrlRequest.Callback callback, Executor executor,
int priority, Collection<Object> requestAnnotations, boolean disableCache,
boolean disableConnectionMigration) {
synchronized (mLock) {
checkHaveAdapter();
boolean metricsCollectionEnabled = false;
synchronized (mFinishedListenerLock) {
metricsCollectionEnabled = !mFinishedListenerList.isEmpty();
}
return new CronetUrlRequest(this, url, priority, callback, executor, requestAnnotations,
metricsCollectionEnabled, disableCache, disableConnectionMigration);
}
}
@Override
public BidirectionalStream createBidirectionalStream(String url,
BidirectionalStream.Callback callback, Executor executor, String httpMethod,
List<Map.Entry<String, String>> requestHeaders,
@BidirectionalStream.Builder.StreamPriority int priority, boolean disableAutoFlush,
boolean delayRequestHeadersUntilFirstFlush) {
synchronized (mLock) {
checkHaveAdapter();
return new CronetBidirectionalStream(this, url, priority, callback, executor,
httpMethod, requestHeaders, disableAutoFlush,
delayRequestHeadersUntilFirstFlush);
}
}
@Override
public boolean isEnabled() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
@Override
public String getVersionString() {
return "Cronet/" + ImplVersion.getVersion();
}
@Override
public void shutdown() {
synchronized (mLock) {
checkHaveAdapter();
if (mActiveRequestCount.get() != 0) {
throw new IllegalStateException("Cannot shutdown with active requests.");
}
// Destroying adapter stops the network thread, so it cannot be
// called on network thread.
if (Thread.currentThread() == mNetworkThread) {
throw new IllegalThreadStateException("Cannot shutdown from network thread.");
}
}
// Wait for init to complete on main and network thread (without lock,
// so other thread could access it).
mInitCompleted.block();
synchronized (mLock) {
// It is possible that adapter is already destroyed on another thread.
if (!haveRequestContextAdapter()) {
return;
}
nativeDestroy(mUrlRequestContextAdapter);
mUrlRequestContextAdapter = 0;
}
}
@Override
public void startNetLogToFile(String fileName, boolean logAll) {
synchronized (mLock) {
checkHaveAdapter();
nativeStartNetLogToFile(mUrlRequestContextAdapter, fileName, logAll);
}
}
@Override
public void stopNetLog() {
synchronized (mLock) {
checkHaveAdapter();
nativeStopNetLog(mUrlRequestContextAdapter);
}
}
@Override
public String getCertVerifierData(long timeout) {
if (timeout < 0) {
throw new IllegalArgumentException("timeout must be a positive value");
} else if (timeout == 0) {
timeout = 100;
}
mWaitGetCertVerifierDataComplete.close();
synchronized (mLock) {
checkHaveAdapter();
nativeGetCertVerifierData(mUrlRequestContextAdapter);
}
mWaitGetCertVerifierDataComplete.block(timeout);
return mCertVerifierData;
}
// This method is intentionally non-static to ensure Cronet native library
// is loaded by class constructor.
@Override
public byte[] getGlobalMetricsDeltas() {
return nativeGetHistogramDeltas();
}
@VisibleForTesting
@Override
public void configureNetworkQualityEstimatorForTesting(
boolean useLocalHostRequests, boolean useSmallerResponses) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mLock) {
checkHaveAdapter();
nativeConfigureNetworkQualityEstimatorForTesting(
mUrlRequestContextAdapter, useLocalHostRequests, useSmallerResponses);
}
}
@Override
public void addRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, true);
}
}
mRttListenerList.addObserver(listener);
}
}
@Override
public void removeRttListener(NetworkQualityRttListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mRttListenerList.removeObserver(listener);
if (mRttListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideRTTObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, true);
}
}
mThroughputListenerList.addObserver(listener);
}
}
@Override
public void removeThroughputListener(NetworkQualityThroughputListener listener) {
if (!mNetworkQualityEstimatorEnabled) {
throw new IllegalStateException("Network quality estimator must be enabled");
}
synchronized (mNetworkQualityLock) {
mThroughputListenerList.removeObserver(listener);
if (mThroughputListenerList.isEmpty()) {
synchronized (mLock) {
checkHaveAdapter();
nativeProvideThroughputObservations(mUrlRequestContextAdapter, false);
}
}
}
}
@Override
public void addRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.add(listener);
}
}
@Override
public void removeRequestFinishedListener(RequestFinishedInfo.Listener listener) {
synchronized (mFinishedListenerLock) {
mFinishedListenerList.remove(listener);
}
}
@Override
public URLConnection openConnection(URL url) {
return openConnection(url, Proxy.NO_PROXY);
}
@Override
public URLConnection openConnection(URL url, Proxy proxy) {
if (proxy.type() != Proxy.Type.DIRECT) {
throw new UnsupportedOperationException();
}
String protocol = url.getProtocol();
if ("http".equals(protocol) || "https".equals(protocol)) {
return new CronetHttpURLConnection(url, this);
}
throw new UnsupportedOperationException("Unexpected protocol:" + protocol);
}
@Override
public URLStreamHandlerFactory createURLStreamHandlerFactory() {
return new CronetURLStreamHandlerFactory(this);
}
/**
* Mark request as started to prevent shutdown when there are active
* requests.
*/
void onRequestStarted() {
mActiveRequestCount.incrementAndGet();
}
/**
* Mark request as finished to allow shutdown when there are no active
* requests.
*/
void onRequestDestroyed() {
mActiveRequestCount.decrementAndGet();
}
@VisibleForTesting
public long getUrlRequestContextAdapter() {
synchronized (mLock) {
checkHaveAdapter();
return mUrlRequestContextAdapter;
}
}
private void checkHaveAdapter() throws IllegalStateException {
if (!haveRequestContextAdapter()) {
throw new IllegalStateException("Engine is shut down.");
}
}
private boolean haveRequestContextAdapter() {
return mUrlRequestContextAdapter != 0;
}
/**
* @return loggingLevel see {@link #LOG_NONE}, {@link #LOG_DEBUG} and
* {@link #LOG_VERBOSE}.
*/
private int getLoggingLevel() {
int loggingLevel;
if (Log.isLoggable(LOG_TAG, Log.VERBOSE)) {
loggingLevel = LOG_VERBOSE;
} else if (Log.isLoggable(LOG_TAG, Log.DEBUG)) {
loggingLevel = LOG_DEBUG;
} else {
loggingLevel = LOG_NONE;
}
return loggingLevel;
}
@SuppressWarnings("unused")
@CalledByNative
private void initNetworkThread() {
synchronized (mLock) {
mNetworkThread = Thread.currentThread();
mInitCompleted.open();
}
Thread.currentThread().setName("ChromiumNet");
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
}
@SuppressWarnings("unused")
@CalledByNative
private void onRttObservation(final int rttMs, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityRttListener listener : mRttListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRttObservation(rttMs, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onThroughputObservation(
final int throughputKbps, final long whenMs, final int source) {
synchronized (mNetworkQualityLock) {
for (final NetworkQualityThroughputListener listener : mThroughputListenerList) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onThroughputObservation(throughputKbps, whenMs, source);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
}
@SuppressWarnings("unused")
@CalledByNative
private void onGetCertVerifierData(String certVerifierData) {
mCertVerifierData = certVerifierData;
mWaitGetCertVerifierDataComplete.open();
}
void reportFinished(final CronetUrlRequest request) {
final RequestFinishedInfo requestInfo = request.getRequestFinishedInfo();
ArrayList<RequestFinishedInfo.Listener> currentListeners;
synchronized (mFinishedListenerLock) {
currentListeners = new ArrayList<RequestFinishedInfo.Listener>(mFinishedListenerList);
}
for (final RequestFinishedInfo.Listener listener : currentListeners) {
Runnable task = new Runnable() {
@Override
public void run() {
listener.onRequestFinished(requestInfo);
}
};
postObservationTaskToExecutor(listener.getExecutor(), task);
}
}
private static void postObservationTaskToExecutor(Executor executor, Runnable task) {
try {
executor.execute(task);
} catch (RejectedExecutionException failException) {
Log.e(CronetUrlRequestContext.LOG_TAG, "Exception posting task to executor",
failException);
}
}
// Native methods are implemented in cronet_url_request_context_adapter.cc.
private static native long nativeCreateRequestContextConfig(String userAgent,
String storagePath, boolean quicEnabled, String quicUserAgentId, boolean http2Enabled,
boolean sdchEnabled, String dataReductionProxyKey,
String dataReductionProxyPrimaryProxy, String dataReductionProxyFallbackProxy,
String dataReductionProxySecureProxyCheckUrl, boolean disableCache, int httpCacheMode,
long httpCacheMaxSize, String experimentalOptions, long mockCertVerifier,
boolean enableNetworkQualityEstimator,
boolean bypassPublicKeyPinningForLocalTrustAnchors, String certVerifierData);
private static native void nativeAddQuicHint(
long urlRequestContextConfig, String host, int port, int alternatePort);
private static native void nativeAddPkp(long urlRequestContextConfig, String host,
byte[][] hashes, boolean includeSubdomains, long expirationTime);
private static native long nativeCreateRequestContextAdapter(long urlRequestContextConfig);
private static native int nativeSetMinLogLevel(int loggingLevel);
private static native byte[] nativeGetHistogramDeltas();
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeDestroy(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStartNetLogToFile(long nativePtr, String fileName, boolean logAll);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeStopNetLog(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeGetCertVerifierData(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeInitRequestContextOnMainThread(long nativePtr);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeConfigureNetworkQualityEstimatorForTesting(
long nativePtr, boolean useLocalHostRequests, boolean useSmallerResponses);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideRTTObservations(long nativePtr, boolean should);
@NativeClassQualifiedName("CronetURLRequestContextAdapter")
private native void nativeProvideThroughputObservations(long nativePtr, boolean should);
}
|
danakj/chromium
|
components/cronet/android/java/src/org/chromium/net/impl/CronetUrlRequestContext.java
|
Java
|
bsd-3-clause
| 21,435 |
/*L
* Copyright Oracle Inc
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cadsr-cgmdr-nci-uk/LICENSE.txt for details.
*/
/*
* eXist Open Source Native XML Database
* Copyright (C) 2001-04 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.storage.index;
import java.nio.ByteBuffer;
import org.exist.storage.DBBroker;
import org.exist.storage.journal.LogException;
import org.exist.storage.txn.Txn;
/**
* @author wolf
*
*/
public class RemoveValueLoggable extends AbstractBFileLoggable {
protected long page;
protected short tid;
protected byte[] oldData;
protected int offset = 0;
protected int len;
/**
*
*
* @param page
* @param tid
* @param oldData
* @param offset
* @param len
* @param fileId
* @param transaction
*/
public RemoveValueLoggable(Txn transaction, byte fileId, long page, short tid, byte[] oldData, int offset, int len) {
super(BFile.LOG_REMOVE_VALUE, fileId, transaction);
this.page = page;
this.tid = tid;
this.oldData = oldData;
this.offset = offset;
this.len = len;
}
/**
* @param broker
* @param transactionId
*/
public RemoveValueLoggable(DBBroker broker, long transactionId) {
super(broker, transactionId);
}
public void write(ByteBuffer out) {
super.write(out);
out.putInt((int) page);
out.putShort(tid);
out.putShort((short) len);
out.put(oldData, offset, len);
}
public void read(ByteBuffer in) {
super.read(in);
page = in.getInt();
tid = in.getShort();
len = in.getShort();
oldData = new byte[len];
in.get(oldData);
}
public int getLogSize() {
return super.getLogSize() + len + 8;
}
public void redo() throws LogException {
getIndexFile().redoRemoveValue(this);
}
public void undo() throws LogException {
getIndexFile().undoRemoveValue(this);
}
public String dump() {
return super.dump() + " - remove value with tid " + tid + " from page " + page;
}
}
|
NCIP/cadsr-cgmdr-nci-uk
|
src/org/exist/storage/index/RemoveValueLoggable.java
|
Java
|
bsd-3-clause
| 3,088 |
/*
* Copyright (c) 2016, Salesforce.com, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of Salesforce.com nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.dva.argus.service.metric.transform;
import com.salesforce.dva.argus.entity.Metric;
import com.salesforce.dva.argus.system.SystemAssert;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* COUNT, GROUP, UNION.
*
* @author rzhang
*/
public class MetricUnionTransform implements Transform {
//~ Static fields/initializers *******************************************************************************************************************
/** The metric name for this transform is result. */
public static final String RESULT_METRIC_NAME = "result";
//~ Instance fields ******************************************************************************************************************************
private final ValueReducer valueUnionReducer;
private final String defaultScope;
private final String defaultMetricName;
//~ Constructors *********************************************************************************************************************************
/**
* Creates a new ReduceTransform object.
*
* @param valueUnionReducer valueReducerOrMapping The valueMapping.
*/
protected MetricUnionTransform(ValueReducer valueUnionReducer) {
this.defaultScope = TransformFactory.Function.UNION.name();
this.defaultMetricName = TransformFactory.DEFAULT_METRIC_NAME;
this.valueUnionReducer = valueUnionReducer;
}
//~ Methods **************************************************************************************************************************************
@Override
public String getResultScopeName() {
return defaultScope;
}
/**
* If constants is not null, apply mapping transform to metrics list. Otherwise, apply reduce transform to metrics list
*
* @param metrics The metrics to transform.
*
* @return The transformed metrics.
*/
@Override
public List<Metric> transform(List<Metric> metrics) {
return union(metrics);
}
/**
* Performs a columnar union of metrics.
*
* @param metrics The metrics to merge.
*
* @return The merged metrics.
*/
public List<Metric> union(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
if (metrics.isEmpty()) {
return metrics;
}
Metric newMetric = reduce(metrics);
Map<Long, String> reducedDatapoints = newMetric.getDatapoints();
Set<Long> sharedTimestamps = reducedDatapoints.keySet();
Map<Long, String> unionDatapoints = new TreeMap<Long, String>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> entry : metric.getDatapoints().entrySet()) {
if (!sharedTimestamps.contains(entry.getKey())) {
unionDatapoints.put(entry.getKey(), entry.getValue());
}
}
}
newMetric.addDatapoints(unionDatapoints);
return Arrays.asList(newMetric);
}
/**
* Reduce transform for the list of metrics.
*
* @param metrics The list of metrics to reduce.
*
* @return The reduced metric.
*/
protected Metric reduce(List<Metric> metrics) {
SystemAssert.requireArgument(metrics != null, "Cannot transform empty metric/metrics");
/*
* if (metrics.isEmpty()) { return new Metric(defaultScope, defaultMetricName); }
*/
MetricDistiller distiller = new MetricDistiller();
distiller.distill(metrics);
Map<Long, List<String>> collated = collate(metrics);
Map<Long, String> minDatapoints = reduce(collated, metrics);
String newMetricName = distiller.getMetric() == null ? defaultMetricName : distiller.getMetric();
Metric newMetric = new Metric(defaultScope, newMetricName);
newMetric.setDisplayName(distiller.getDisplayName());
newMetric.setUnits(distiller.getUnits());
newMetric.setTags(distiller.getTags());
newMetric.setDatapoints(minDatapoints);
return newMetric;
}
private Map<Long, List<String>> collate(List<Metric> metrics) {
Map<Long, List<String>> collated = new HashMap<Long, List<String>>();
for (Metric metric : metrics) {
for (Map.Entry<Long, String> point : metric.getDatapoints().entrySet()) {
if (!collated.containsKey(point.getKey())) {
collated.put(point.getKey(), new ArrayList<String>());
}
collated.get(point.getKey()).add(point.getValue());
}
}
return collated;
}
private Map<Long, String> reduce(Map<Long, List<String>> collated, List<Metric> metrics) {
Map<Long, String> reducedDatapoints = new HashMap<>();
for (Map.Entry<Long, List<String>> entry : collated.entrySet()) {
if (entry.getValue().size() < metrics.size()) {
continue;
}
reducedDatapoints.put(entry.getKey(), this.valueUnionReducer.reduce(entry.getValue()));
}
return reducedDatapoints;
}
@Override
public List<Metric> transform(List<Metric> metrics, List<String> constants) {
throw new UnsupportedOperationException("Union transform can't be used with constants!");
}
@Override
public List<Metric> transform(List<Metric>... listOfList) {
throw new UnsupportedOperationException("Union doesn't need list of list");
}
}
/* Copyright (c) 2016, Salesforce.com, Inc. All rights reserved. */
|
rmelick/Argus
|
ArgusCore/src/main/java/com/salesforce/dva/argus/service/metric/transform/MetricUnionTransform.java
|
Java
|
bsd-3-clause
| 7,287 |
package org.cagrid.gme.common.exceptions;
import java.io.IOException;
@SuppressWarnings("serial")
public class SchemaParsingException extends IOException {
public SchemaParsingException() {
super();
}
public SchemaParsingException(String s) {
super(s);
}
}
|
NCIP/cagrid
|
cagrid/Software/core/caGrid/projects/globalModelExchange/src/org/cagrid/gme/common/exceptions/SchemaParsingException.java
|
Java
|
bsd-3-clause
| 296 |
/* Copyright (c) 2009, University of Oslo, Norway
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the University of Oslo nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package vtk.text.tl.expr;
import java.math.BigDecimal;
import vtk.text.tl.Symbol;
public class Multiply extends NumericOperator {
public Multiply(Symbol symbol) {
super(symbol);
}
@Override
protected Object evalNumeric(BigDecimal n1, BigDecimal n2) {
return n1.multiply(n2);
}
}
|
vtkio/vtk
|
src/main/java/vtk/text/tl/expr/Multiply.java
|
Java
|
bsd-3-clause
| 1,929 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.SimpleRobot;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the SimpleRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends SimpleRobot {
private Joystick joystick = new Joystick(1);
private Drivetrain drivetrain;
private BowlerArm arm;
Compressor compressor;
Pan pan;
//int port_1 = 7; //these ports were placeholders, no longer applicable
//int port_2 = 7;
public RobotTemplate() {
drivetrain = new Drivetrain();
arm = new BowlerArm();
pan = new Pan();
compressor = new Compressor(7, 7);//7 for the switch, 7 for the relay
}
/**
* This function is called once each time the robot enters autonomous mode.
*/
public void autonomous() {
drivetrain.set(1, 1);
sleep(5000);
drivetrain.set(0,0);
// arm.auto();
}
/**
* This function is called once each time the robot enters operator control.
*/
public void operatorControl() {
compressor.start();
arm.setSolenoid(-1);
while (isOperatorControl()) {
//drivetrain updates
double lstick = -joystick.getRawAxis(2);
double rstick = -joystick.getRawAxis(4);
drivetrain.set(Math.abs(lstick) * lstick, Math.abs(rstick) * rstick); //If I'm not mistaken, this is the most convenient way to square in Java?
//pan updates version 2 (Amita); this is basic and can be used for backup
if(joystick.getRawButton(10)){
pan.endGame();
}
else{
pan.resetServo();
}
//bowler arm updates
if (joystick.getRawButton(7)) {
arm.rampDown();
} else if (joystick.getRawButton(5)) {
arm.rampUp();
} else {
arm.setRamp(0);
}
arm.setSolenoid((int) joystick.getRawAxis(6));
}
}
/*
*changes the servo state based on the button being pressed.
*once it is pressed, it is set to the opposite of what is was at the start, ditto for release.
*/
/**
* This function is called once each time the robot enters test mode.
*/
public void test() {
}
public void updateDrivetrain(){
}
public void updateArm(){
}
public void updatePan(){
}
public static void sleep(long ms){
long t=System.currentTimeMillis()+ms;
while(System.currentTimeMillis()<t){
//do nothing!
}
}
}
|
2374/chris
|
src/edu/wpi/first/wpilibj/templates/RobotTemplate.java
|
Java
|
bsd-3-clause
| 3,586 |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.ui.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.BuildConfig;
import java.lang.ref.WeakReference;
/**
* An {@link OptimizedFrameLayout} that increases the speed of frequent view lookup by ID by caching
* the result of the lookup. Adding or removing a view with the same ID as a cached version will
* cause the cache to be invalidated for that view and cause a re-lookup the next time it is
* queried. The goal of this view type is to be used in cases where child views are frequently
* accessed or reused, for example as part of a {@link androidx.recyclerview.widget.RecyclerView}.
* The logic in the {@link #fastFindViewById(int)} method would be in {@link #findViewById(int)} if
* it weren't final on the {@link View} class.
*
* {@link android.view.ViewGroup.OnHierarchyChangeListener}s cannot be used on ViewGroups that are
* children of this group since they would overwrite the listeners that are critical to this class'
* functionality.
*
* Usage:
* Use the same way that you would use a normal {@link android.widget.FrameLayout}, but instead
* of using {@link #findViewById(int)} to access views, use {@link #fastFindViewById(int)}.
*/
public class ViewLookupCachingFrameLayout extends OptimizedFrameLayout {
/** A map containing views that have had lookup performed on them for quicker access. */
private final SparseArray<WeakReference<View>> mCachedViews = new SparseArray<>();
/** The hierarchy listener responsible for notifying the cache that the tree has changed. */
@VisibleForTesting
final OnHierarchyChangeListener mListener = new OnHierarchyChangeListener() {
@Override
public void onChildViewAdded(View parent, View child) {
mCachedViews.remove(child.getId());
setHierarchyListenerOnTree(child, this);
}
@Override
public void onChildViewRemoved(View parent, View child) {
mCachedViews.remove(child.getId());
setHierarchyListenerOnTree(child, null);
}
};
/** Default constructor for use in XML. */
public ViewLookupCachingFrameLayout(Context context, AttributeSet atts) {
super(context, atts);
setOnHierarchyChangeListener(mListener);
}
@Override
public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
assert listener == mListener : "Hierarchy change listeners cannot be set for this group!";
super.setOnHierarchyChangeListener(listener);
}
/**
* Set the hierarchy listener that invalidates relevant parts of the cache when subtrees change.
* @param view The root of the tree to attach listeners to.
* @param listener The listener to attach (null to unset).
*/
private void setHierarchyListenerOnTree(View view, OnHierarchyChangeListener listener) {
if (!(view instanceof ViewGroup)) return;
ViewGroup group = (ViewGroup) view;
group.setOnHierarchyChangeListener(listener);
for (int i = 0; i < group.getChildCount(); i++) {
setHierarchyListenerOnTree(group.getChildAt(i), listener);
}
}
/**
* Does the same thing as {@link #findViewById(int)} but caches the result if not null.
* Subsequent lookups are cheaper as a result. Adding or removing a child view invalidates
* the cache for the ID of the view removed and causes a re-lookup.
* @param id The ID of the view to lookup.
* @return The view if it exists.
*/
@Nullable
public View fastFindViewById(@IdRes int id) {
WeakReference<View> ref = mCachedViews.get(id);
View view = null;
if (ref != null) view = ref.get();
if (view == null) view = findViewById(id);
if (BuildConfig.DCHECK_IS_ON) {
assert view == findViewById(id) : "View caching logic is broken!";
assert ref == null
|| ref.get() != null : "Cache held reference to garbage collected view!";
}
if (view != null) mCachedViews.put(id, new WeakReference<>(view));
return view;
}
@VisibleForTesting
SparseArray<WeakReference<View>> getCache() {
return mCachedViews;
}
}
|
endlessm/chromium-browser
|
ui/android/java/src/org/chromium/ui/widget/ViewLookupCachingFrameLayout.java
|
Java
|
bsd-3-clause
| 4,641 |
/*
* Copyright (c) 2016, Groupon, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of GROUPON nor the names of its contributors may be
* used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.groupon.lex.metrics;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import org.junit.Test;
/**
*
* @author ariane
*/
public class SimpleMetricTest {
@Test
public void constructor_number() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), (short)7);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 7, m.getValue());
}
@Test
public void constructor_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), "chocoladevla");
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateString("chocoladevla", m.getValue());
}
@Test
public void constructor_bool() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), true);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateBoolean(true, m.getValue());
}
@Test
public void constructor_metric() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromNumberValue(9000));
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateNumber(true, 9000, m.getValue());
}
@Test
public void constructor_empty() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.EMPTY);
assertEquals(MetricName.valueOf("foobar"), m.getName());
assertNotNull(m.getValue());
MetricValueTest.validateEmpty(m.getValue());
}
@Test
public void to_string() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertThat(m.toString(), Matchers.allOf(containsString("foobar"), containsString("19")));
}
@Test
public void equality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertEquals(m0, m1);
assertEquals(m0.hashCode(), m1.hashCode());
}
@Test
public void inequality() {
Metric m0 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(17));
Metric m1 = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
Metric m2 = new SimpleMetric(MetricName.valueOf("fizzbuzz"), MetricValue.fromIntValue(19));
assertNotEquals(m0, m1);
assertNotEquals(m0, m2);
assertNotEquals(m1, m0);
assertNotEquals(m1, m2);
assertNotEquals(m2, m0);
assertNotEquals(m2, m1);
}
@Test
public void equal_across_types() {
Metric m = new SimpleMetric(MetricName.valueOf("foobar"), MetricValue.fromIntValue(19));
assertFalse(m.equals(null));
assertFalse(m.equals(new Object()));
}
}
|
groupon/monsoon
|
intf/src/test/java/com/groupon/lex/metrics/SimpleMetricTest.java
|
Java
|
bsd-3-clause
| 4,854 |
/*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.patientdiscovery.inbound.deferred.request;
import gov.hhs.fha.nhinc.aspect.InboundProcessingEvent;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.patientdiscovery.PatientDiscoveryAuditor;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.AdapterPatientDiscoveryDeferredReqProxy;
import gov.hhs.fha.nhinc.patientdiscovery.adapter.deferred.request.proxy.AdapterPatientDiscoveryDeferredReqProxyObjectFactory;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.MCCIIN000002UV01EventDescriptionBuilder;
import gov.hhs.fha.nhinc.patientdiscovery.aspect.PRPAIN201305UV02EventDescriptionBuilder;
import org.hl7.v3.MCCIIN000002UV01;
import org.hl7.v3.PRPAIN201305UV02;
public abstract class AbstractInboundPatientDiscoveryDeferredRequest implements InboundPatientDiscoveryDeferredRequest {
private final AdapterPatientDiscoveryDeferredReqProxyObjectFactory adapterFactory;
public AbstractInboundPatientDiscoveryDeferredRequest(AdapterPatientDiscoveryDeferredReqProxyObjectFactory factory) {
adapterFactory = factory;
}
abstract MCCIIN000002UV01 process(PRPAIN201305UV02 request, AssertionType assertion);
abstract PatientDiscoveryAuditor getAuditLogger();
/**
* Processes the PD Deferred request message. This call will audit the message and send it to the Nhin.
*
* @param request
* @param assertion
* @return MCCIIN000002UV01
*/
@InboundProcessingEvent(beforeBuilder = PRPAIN201305UV02EventDescriptionBuilder.class,
afterReturningBuilder = MCCIIN000002UV01EventDescriptionBuilder.class,
serviceType = "Patient Discovery Deferred Request",
version = "1.0")
public MCCIIN000002UV01 respondingGatewayPRPAIN201305UV02(PRPAIN201305UV02 request, AssertionType assertion) {
auditRequestFromNhin(request, assertion);
MCCIIN000002UV01 response = process(request, assertion);
auditResponseToNhin(response, assertion);
return response;
}
protected MCCIIN000002UV01 sendToAdapter(PRPAIN201305UV02 request, AssertionType assertion) {
AdapterPatientDiscoveryDeferredReqProxy proxy = adapterFactory.getAdapterPatientDiscoveryDeferredReqProxy();
return proxy.processPatientDiscoveryAsyncReq(request, assertion);
}
private void auditRequestFromNhin(PRPAIN201305UV02 request, AssertionType assertion) {
getAuditLogger().auditNhinDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION);
}
private void auditResponseToNhin(MCCIIN000002UV01 response, AssertionType assertion) {
getAuditLogger().auditAck(response, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION,
NhincConstants.AUDIT_LOG_NHIN_INTERFACE);
}
protected void auditRequestToAdapter(PRPAIN201305UV02 request, AssertionType assertion) {
getAuditLogger().auditAdapterDeferred201305(request, assertion, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION);
}
protected void auditResponseFromAdapter(MCCIIN000002UV01 response, AssertionType assertion) {
getAuditLogger().auditAck(response, assertion, NhincConstants.AUDIT_LOG_INBOUND_DIRECTION,
NhincConstants.AUDIT_LOG_ADAPTER_INTERFACE);
}
}
|
sailajaa/CONNECT
|
Product/Production/Services/PatientDiscoveryCore/src/main/java/gov/hhs/fha/nhinc/patientdiscovery/inbound/deferred/request/AbstractInboundPatientDiscoveryDeferredRequest.java
|
Java
|
bsd-3-clause
| 5,048 |
package com.mistraltech.smogen.codegenerator.javabuilder;
public class InterfaceMethodBuilder extends MethodSignatureBuilder<InterfaceMethodBuilder> {
private InterfaceMethodBuilder() {
}
public static InterfaceMethodBuilder anInterfaceMethod() {
return new InterfaceMethodBuilder();
}
@Override
public String build(JavaBuilderContext context) {
return super.build(context) + ";";
}
}
|
mistraltechnologies/smogen
|
src/main/java/com/mistraltech/smogen/codegenerator/javabuilder/InterfaceMethodBuilder.java
|
Java
|
bsd-3-clause
| 432 |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.sync;
import android.test.FlakyTest;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Pair;
import org.chromium.base.ThreadUtils;
import org.chromium.base.test.util.Feature;
import org.chromium.chrome.browser.ChromeApplication;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelUtils;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.chrome.test.util.browser.sync.SyncTestUtil;
import org.chromium.content.browser.test.util.Criteria;
import org.chromium.sync.protocol.EntitySpecifics;
import org.chromium.sync.protocol.SessionHeader;
import org.chromium.sync.protocol.SessionSpecifics;
import org.chromium.sync.protocol.SessionTab;
import org.chromium.sync.protocol.SessionWindow;
import org.chromium.sync.protocol.SyncEnums;
import org.chromium.sync.protocol.TabNavigation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
/**
* Test suite for the open tabs (sessions) sync data type.
*/
public class OpenTabsTest extends SyncTestBase {
private static final String TAG = "OpenTabsTest";
private static final String OPEN_TABS_TYPE = "Sessions";
// EmbeddedTestServer is preferred here but it can't be used. The test server
// serves pages on localhost and Chrome doesn't sync localhost URLs as typed URLs.
// This type of URL requires no external data connection or resources.
private static final String URL = "data:text,OpenTabsTestURL";
private static final String URL2 = "data:text,OpenTabsTestURL2";
private static final String URL3 = "data:text,OpenTabsTestURL3";
private static final String SESSION_TAG_PREFIX = "FakeSessionTag";
private static final String FAKE_CLIENT = "FakeClient";
// The client name for tabs generated locally will vary based on the device the test is
// running on, so it is determined once in the setUp() method and cached here.
private String mClientName;
// A counter used for generating unique session tags. Resets to 0 in setUp().
private int mSessionTagCounter;
// A container to store OpenTabs information for data verification.
private static class OpenTabs {
public final String headerId;
public final List<String> tabIds;
public final List<String> urls;
private OpenTabs(String headerId, List<String> tabIds, List<String> urls) {
this.headerId = headerId;
this.tabIds = tabIds;
this.urls = urls;
}
}
@Override
protected void setUp() throws Exception {
super.setUp();
setUpTestAccountAndSignInToSync();
mClientName = getClientName();
mSessionTagCounter = 0;
}
// Test syncing an open tab from client to server.
@LargeTest
@Feature({"Sync"})
public void testUploadOpenTab() throws Exception {
loadUrl(URL);
waitForLocalTabsForClient(mClientName, URL);
waitForServerTabs(URL);
}
/*
// Test syncing multiple open tabs from client to server.
@LargeTest
@Feature({"Sync"})
https://crbug.com/592437
*/
@FlakyTest
public void testUploadMultipleOpenTabs() throws Exception {
loadUrl(URL);
loadUrlInNewTab(URL2);
loadUrlInNewTab(URL3);
waitForLocalTabsForClient(mClientName, URL, URL2, URL3);
waitForServerTabs(URL, URL2, URL3);
}
/*
// Test syncing an open tab from client to server.
@LargeTest
@Feature({"Sync"})
https://crbug.com/592437
*/
@FlakyTest
public void testUploadAndCloseOpenTab() throws Exception {
loadUrl(URL);
// Can't have zero tabs, so we have to open two to test closing one.
loadUrlInNewTab(URL2);
waitForLocalTabsForClient(mClientName, URL, URL2);
waitForServerTabs(URL, URL2);
ThreadUtils.runOnUiThreadBlocking(new Runnable() {
@Override
public void run() {
TabModelSelector selector = FeatureUtilities.isDocumentMode(getActivity())
? ChromeApplication.getDocumentTabModelSelector()
: getActivity().getTabModelSelector();
assertTrue(TabModelUtils.closeCurrentTab(selector.getCurrentModel()));
}
});
waitForLocalTabsForClient(mClientName, URL);
waitForServerTabs(URL);
}
// Test syncing an open tab from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadOpenTab() throws Exception {
addFakeServerTabs(FAKE_CLIENT, URL);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL);
}
// Test syncing multiple open tabs from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadMultipleOpenTabs() throws Exception {
addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL, URL2, URL3);
}
// Test syncing a tab deletion from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadDeletedOpenTab() throws Exception {
// Add the entity to test deleting.
addFakeServerTabs(FAKE_CLIENT, URL);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL);
// Delete on server, sync, and verify deleted locally.
deleteServerTabsForClient(FAKE_CLIENT);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT);
}
// Test syncing multiple tab deletions from server to client.
@LargeTest
@Feature({"Sync"})
public void testDownloadMultipleDeletedOpenTabs() throws Exception {
// Add the entity to test deleting.
addFakeServerTabs(FAKE_CLIENT, URL, URL2, URL3);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT, URL, URL2, URL3);
// Delete on server, sync, and verify deleted locally.
deleteServerTabsForClient(FAKE_CLIENT);
SyncTestUtil.triggerSync();
waitForLocalTabsForClient(FAKE_CLIENT);
}
private String makeSessionTag() {
return SESSION_TAG_PREFIX + (mSessionTagCounter++);
}
private void addFakeServerTabs(String clientName, String... urls)
throws InterruptedException {
String tag = makeSessionTag();
EntitySpecifics header = makeSessionEntity(tag, clientName, urls.length);
mFakeServerHelper.injectUniqueClientEntity(tag, header);
for (int i = 0; i < urls.length; i++) {
EntitySpecifics tab = makeTabEntity(tag, urls[i], i);
// It is critical that the name here is "<tag> <tabNodeId>", otherwise sync crashes
// when it tries to sync due to the use of TabIdToTag in sessions_sync_manager.cc.
mFakeServerHelper.injectUniqueClientEntity(tag + " " + i, tab);
}
}
private EntitySpecifics makeSessionEntity(String tag, String clientName, int numTabs) {
EntitySpecifics specifics = new EntitySpecifics();
specifics.session = new SessionSpecifics();
specifics.session.sessionTag = tag;
specifics.session.header = new SessionHeader();
specifics.session.header.clientName = clientName;
specifics.session.header.deviceType = SyncEnums.TYPE_PHONE;
SessionWindow window = new SessionWindow();
window.windowId = 0;
window.selectedTabIndex = 0;
window.tab = new int[numTabs];
for (int i = 0; i < numTabs; i++) {
window.tab[i] = i;
}
specifics.session.header.window = new SessionWindow[] { window };
return specifics;
}
private EntitySpecifics makeTabEntity(String tag, String url, int id) {
EntitySpecifics specifics = new EntitySpecifics();
specifics.session = new SessionSpecifics();
specifics.session.sessionTag = tag;
specifics.session.tabNodeId = id;
SessionTab tab = new SessionTab();
tab.tabId = id;
tab.currentNavigationIndex = 0;
TabNavigation nav = new TabNavigation();
nav.virtualUrl = url;
tab.navigation = new TabNavigation[] { nav };
specifics.session.tab = tab;
return specifics;
}
private void deleteServerTabsForClient(String clientName) throws JSONException {
OpenTabs openTabs = getLocalTabsForClient(clientName);
mFakeServerHelper.deleteEntity(openTabs.headerId);
for (String tabId : openTabs.tabIds) {
mFakeServerHelper.deleteEntity(tabId);
}
}
private void waitForLocalTabsForClient(final String clientName, String... urls)
throws InterruptedException {
final List<String> urlList = new ArrayList<String>(urls.length);
for (String url : urls) urlList.add(url);
pollInstrumentationThread(Criteria.equals(urlList, new Callable<List<String>>() {
@Override
public List<String> call() throws Exception {
return getLocalTabsForClient(clientName).urls;
}
}));
}
private void waitForServerTabs(final String... urls)
throws InterruptedException {
pollInstrumentationThread(
new Criteria("Expected server open tabs: " + Arrays.toString(urls)) {
@Override
public boolean isSatisfied() {
try {
return mFakeServerHelper.verifySessions(urls);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
private String getClientName() throws Exception {
pollInstrumentationThread(Criteria.equals(2, new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return SyncTestUtil.getLocalData(mContext, OPEN_TABS_TYPE).size();
}
}));
List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData(
mContext, OPEN_TABS_TYPE);
for (Pair<String, JSONObject> tabEntity : tabEntities) {
if (tabEntity.second.has("header")) {
return tabEntity.second.getJSONObject("header").getString("client_name");
}
}
throw new IllegalStateException("No client name found.");
}
private static class HeaderInfo {
public final String sessionTag;
public final String headerId;
public final List<String> tabIds;
public HeaderInfo(String sessionTag, String headerId, List<String> tabIds) {
this.sessionTag = sessionTag;
this.headerId = headerId;
this.tabIds = tabIds;
}
}
// Distills the local session data into a simple data object for the given client.
private OpenTabs getLocalTabsForClient(String clientName) throws JSONException {
List<Pair<String, JSONObject>> tabEntities = SyncTestUtil.getLocalData(
mContext, OPEN_TABS_TYPE);
// Output lists.
List<String> urls = new ArrayList<String>();
List<String> tabEntityIds = new ArrayList<String>();
HeaderInfo info = findHeaderInfoForClient(clientName, tabEntities);
if (info.sessionTag == null) {
// No client was found. Here we still want to return an empty list of urls.
return new OpenTabs("", tabEntityIds, urls);
}
Map<String, String> tabIdsToUrls = new HashMap<String, String>();
Map<String, String> tabIdsToEntityIds = new HashMap<String, String>();
findTabMappings(info.sessionTag, tabEntities, tabIdsToUrls, tabIdsToEntityIds);
// Convert the tabId list to the url list.
for (String tabId : info.tabIds) {
urls.add(tabIdsToUrls.get(tabId));
tabEntityIds.add(tabIdsToEntityIds.get(tabId));
}
return new OpenTabs(info.headerId, tabEntityIds, urls);
}
// Find the header entity for clientName and extract its sessionTag and tabId list.
private HeaderInfo findHeaderInfoForClient(
String clientName, List<Pair<String, JSONObject>> tabEntities) throws JSONException {
String sessionTag = null;
String headerId = null;
List<String> tabIds = new ArrayList<String>();
for (Pair<String, JSONObject> tabEntity : tabEntities) {
JSONObject header = tabEntity.second.optJSONObject("header");
if (header != null && header.getString("client_name").equals(clientName)) {
sessionTag = tabEntity.second.getString("session_tag");
headerId = tabEntity.first;
JSONArray windows = header.getJSONArray("window");
if (windows.length() == 0) {
// The client was found but there are no tabs.
break;
}
assertEquals("Only single windows are supported.", 1, windows.length());
JSONArray tabs = windows.getJSONObject(0).getJSONArray("tab");
for (int i = 0; i < tabs.length(); i++) {
tabIds.add(tabs.getString(i));
}
break;
}
}
return new HeaderInfo(sessionTag, headerId, tabIds);
}
// Find the associated tabs and record their tabId -> url and entityId mappings.
private void findTabMappings(String sessionTag, List<Pair<String, JSONObject>> tabEntities,
// Populating these maps is the output of this function.
Map<String, String> tabIdsToUrls, Map<String, String> tabIdsToEntityIds)
throws JSONException {
for (Pair<String, JSONObject> tabEntity : tabEntities) {
JSONObject json = tabEntity.second;
if (json.has("tab") && json.getString("session_tag").equals(sessionTag)) {
JSONObject tab = json.getJSONObject("tab");
int i = tab.getInt("current_navigation_index");
String tabId = tab.getString("tab_id");
String url = tab.getJSONArray("navigation")
.getJSONObject(i).getString("virtual_url");
tabIdsToUrls.put(tabId, url);
tabIdsToEntityIds.put(tabId, tabEntity.first);
}
}
}
}
|
was4444/chromium.src
|
chrome/android/sync_shell/javatests/src/org/chromium/chrome/browser/sync/OpenTabsTest.java
|
Java
|
bsd-3-clause
| 14,827 |
//To Test:http://localhost:8080/nbia-auth/services/v3/getProtectionGrpList?format=html
package gov.nih.nci.nbia.restAPI;
import gov.nih.nci.nbia.dao.TrialDataProvenanceDAO;
import gov.nih.nci.nbia.util.SpringApplicationContext;
import gov.nih.nci.security.SecurityServiceProvider;
import gov.nih.nci.security.UserProvisioningManager;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.dao.RoleSearchCriteria;
import gov.nih.nci.security.dao.SearchCriteria;
import gov.nih.nci.security.exceptions.CSConfigurationException;
import gov.nih.nci.security.exceptions.CSException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.springframework.dao.DataAccessException;
@Path("/v3/getProtectionGrpList")
public class V3_getProtectionGrpList extends getData{
private static final String[] columns={"pgName", "description", "dataSetName"};
public final static String TEXT_CSV = "text/csv";
@Context private HttpServletRequest httpRequest;
/**
* This method get a list of names of protection group
*
* @return String - list of names of protection group
*/
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_HTML, TEXT_CSV})
public Response constructResponse(@QueryParam("format") String format) {
List<Object[]> data = null;
try {
UserProvisioningManager upm = getUpm();
java.util.List<ProtectionGroup> protectionGrpLst = upm.getProtectionGroups();
if ( protectionGrpLst != null) {
data = new ArrayList<Object []>();
for(ProtectionGroup pg : protectionGrpLst) {
List<ProtectionElement> pes = new ArrayList<ProtectionElement>(upm.getProtectionElements(pg.getProtectionGroupId().toString()));
for (ProtectionElement pe : pes) {
Object [] objs = {pg.getProtectionGroupName(),
pg.getProtectionGroupDescription(),
pe.getProtectionElementName()};
data.add(objs);
}
}
}
else {
Object [] objs = {"Warning: No Protection Group has defined yet!", "NA", "NA"};
data.add(objs);
}
} catch (CSConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return formatResponse(format, data, columns);
}
}
|
NCIP/national-biomedical-image-archive
|
software/nbia-api/src/gov/nih/nci/nbia/restAPI/V3_getProtectionGrpList.java
|
Java
|
bsd-3-clause
| 2,741 |
/*
* Copyright (c) 2013-2013, KNOPFLERFISH project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* - Neither the name of the KNOPFLERFISH project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.knopflerfish.service.repositorymanager;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;
import org.osgi.service.repository.Repository;
public class RepositoryInfo implements Comparable<RepositoryInfo> {
final private long id;
final private int rank;
final ServiceReference<Repository> sr;
public RepositoryInfo(ServiceReference<Repository> sr) {
this.id = ((Long)sr.getProperty(Constants.SERVICE_ID)).longValue();
Object r = sr.getProperty(Constants.SERVICE_RANKING);
if (r != null && r instanceof Integer) {
this.rank = ((Integer)r).intValue();
} else {
this.rank = 0;
}
this.sr = sr;
}
public RepositoryInfo(RepositoryInfo old, int rank) {
this.id = old.id;
this.rank = rank;
this.sr = old.sr;
}
public long getId() {
return id;
}
public int getRank() {
return rank;
}
public Object getProperty(String prop) {
return sr.getProperty(prop);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null)
return false;
if (getClass() != o.getClass())
return false;
RepositoryInfo rio = (RepositoryInfo) o;
if (id != rio.id || rank != rio.rank)
return false;
return true;
}
@Override
public int compareTo(RepositoryInfo o) {
if (equals(o)) {
return 0;
}
if (rank != o.rank) {
return o.rank - rank;
} else {
return id < o.id ? -1 : 1;
}
}
public ServiceReference<Repository> getServiceReference() {
return sr;
}
@Override
public String toString() {
return "RepositoryInfo [id=" + id + ", rank=" + rank + "]";
}
}
|
knopflerfish/knopflerfish.org
|
osgi/bundles/repository/repositorymanager/src/org/knopflerfish/service/repositorymanager/RepositoryInfo.java
|
Java
|
bsd-3-clause
| 3,464 |
package org.chasen.mecab.wrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.junit.Test;
public class NodeIteratorTest {
@Test
public void threads() throws InterruptedException {
List<Thread> threads = new ArrayList<Thread>();
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("本日は晴天なり")){
System.out.println(node.getSurface());
}
}
});
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("本日は雨です")){
System.out.println(node.getSurface());
}
}
});
threads.add(new Thread(){
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator("昨日は曇りでした")){
System.out.println(node.getSurface());
}
}
});
for(Thread th: threads){
th.start();
}
for(Thread th: threads){
th.join();
}
}
@Test
public void executors() throws InterruptedException, ExecutionException {
class Hoge {
public void parse(String str){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator(str)){
System.out.println(node.getSurface());
}
}
}
final Hoge hoge = new Hoge();
ExecutorService executors = Executors.newCachedThreadPool();
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("本日は晴天なり");
return null;
}
}));
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("本日は雨です");
return null;
}
}));
futures.add(executors.submit(new Callable<Void>(){
public Void call() throws Exception {
hoge.parse("昨日は曇りでした");
return null;
}
}));
for(Future<?> f: futures){
f.get();
}
}
@Test
public void executors_runnable() throws InterruptedException, ExecutionException {
class Hoge implements Runnable {
String str;
Hoge(String str){
this.str = str;
}
public void run(){
Tagger t = Tagger.create("-r /opt/local/etc/mecabrc");
for(MecabNode<Node, Path> node: t.iterator(str)){
System.out.println(node.getSurface());
}
}
}
ExecutorService executors = Executors.newCachedThreadPool();
List<Future<?>> futures = new ArrayList<Future<?>>();
futures.add(executors.submit(new Hoge("本日は晴天なり")));
futures.add(executors.submit(new Hoge("本日は雨です")));
futures.add(executors.submit(new Hoge("昨日は曇りでした")));
for(Future<?> f: futures){
f.get();
}
}
}
|
nowelium/jna-libmecab
|
test/org/chasen/mecab/wrapper/NodeIteratorTest.java
|
Java
|
bsd-3-clause
| 3,838 |
/*
* Copyright (c) 2006, 2007 ThoughtWorks, Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
package com.thoughtworks.cozmos;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.util.StringTokenizer;
public class ModDavSvnProxyServlet2 extends HttpServlet {
private String targetURL;
private String newPageTemplate;
public void init(ServletConfig servletConfig) throws ServletException {
targetURL = servletConfig.getInitParameter("mod_dav_svn_url");
newPageTemplate = servletConfig.getInitParameter("new_page_template_file");
super.init(servletConfig);
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String path = req.getServletPath();
Socket socket = startGet(new URL(targetURL + path));
InputStream is = socket.getInputStream();
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is));
boolean ok = isOk(lnr);
if (!ok) {
socket = startGet(new URL(targetURL + newPageTemplate));
lnr = new LineNumberReader(new InputStreamReader(is));
ok = isOk(lnr);
}
if (ok) {
lnr.readLine(); // Date:
lnr.readLine(); // Server:
lnr.readLine(); // ETag:
lnr.readLine(); // Accept-Ranges:
int contentLength = getContentLen(lnr.readLine());
lnr.readLine(); // Content-Type:
lnr.readLine(); // end of header
resp.setContentType(getServletContext().getMimeType(path));
OutputStream os = resp.getOutputStream();
int done = 0;
while (done < contentLength) {
int i = lnr.read();
done++;
os.write(i);
}
socket.close();
}
}
private int getContentLen(String s) {
StringTokenizer st = new StringTokenizer(s);
st.nextToken();
return Integer.parseInt(st.nextToken());
}
private boolean isOk(LineNumberReader lnr) throws IOException {
return "HTTP/1.1 200 OK".equals(lnr.readLine());
}
private Socket startGet(URL url) throws IOException {
Socket socket = new Socket(url.getHost(), 80);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("GET " + url.getPath() + " HTTP/1.1");
pw.println("Host: " + url.getHost());
pw.println();
return socket;
}
}
|
codehaus/cozmos
|
src/main/java/com/thoughtworks/cozmos/ModDavSvnProxyServlet2.java
|
Java
|
isc
| 3,638 |
package schoolprojects;
import java.util.Random;
import java.util.Scanner;
/**
* Piedra, papel o tijera es un juego infantil.
* Un juego de manos en el cual existen tres elementos.
* La piedra que vence a la tijera rompiéndola; la tijera que vencen al papel cortándolo;
* y el papel que vence a la piedra envolviéndola. Esto representa un ciclo, el cual
* le da su esencia al juego. Este juego es muy utilizado para decidir quien de dos
* personas hará algo, tal y como a veces se hace usando una moneda, o para dirimir algún asunto.
*
* En esta version del juego habra un Jugador Humano y un jugador artificial ( es decir el ordenador )
*
* @author Velik Georgiev Chelebiev
* @version 0.0.1
*/
public class Juego {
/**
* @param args Argumentos de la linea de comandos
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
/**
* Movimientos disponibles en forma de cadena.
*/
String[] movimientos = {"Piedra", "Papel", "Tijera"};
/**
* Moviemiento elegido por el usuario en forma de numero entero.
*/
int entradaUsuario = 0;
/**
* Un numero aleatorio que representara el movimiento del ordenador.
*/
int movimientoAleatorio = 0;
/**
* Los resultados posibles de la partida. 0 EMPATE 1 El jugador gana 2
* El jugador pierde
*/
String[] resultados = {"Empate", "Ganas", "Pierdes"};
/**
* El resultado de la partida respecto el jugador.
*/
int resultadoJugador = -1;
/**
* Aqui es donde epieza el juego.
*
* Pedimos al usuario que elija uno de los movimientos disponibles
* y generamos un movimiento aleatorio, que sera el movimiento del ordenador.
* Despues comptrobamos si el jugador gana al ordenador , si pierde o si hay un empate.
* Mostramos el resultado en la pantalla y el bucle se repite hasta que
* el jugador no introduce -1 como movimiento.
*/
do {
// Mostramos informacion sobre los movimientos validos y
// los numeros que le corresponden.
for (int i = 0; i < movimientos.length; i++) {
System.out.print("(" + (i + 1) + ") " + movimientos[i] + "\n");
}
// Valor predeterminado ( o entrada no valida, por si el usuario no introduce ningun valor )
entradaUsuario = 0;
// Leemos la entrada ( el moviemiento ) del usuario
try {
System.out.print("Movimiento: ");
entradaUsuario = Integer.parseInt(scan.nextLine());
} catch (NumberFormatException ex) {
// Si la entrada no tiene un formato valido, mostraremos un mensaje de error
// y le pediremos al usuario que introduzca un movimiento nuevamente.
entradaUsuario = 0;
}
// Si la opcion elegida por el usuario no es valida imprimimos un
// mensaje de error y le volvemos a pedir que introduzca una opcion
if (entradaUsuario < 1 || entradaUsuario > 3) {
System.out.println("\n*** El movimiento elegido no es valido. ***");
continue;
}
// Restamos 1 a la entrada del usuario.
// Esto lo hacemos para que sea un indice de vector valido.
entradaUsuario -= 1;
// Generamos un movimiento aleatorio
movimientoAleatorio = rand.nextInt(movimientos.length);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
// Imprimimos las jugadas del jugador y del ordenador
System.out.println("Tu: (" + movimientos[entradaUsuario] + ") [VS] PC: (" + movimientos[movimientoAleatorio] + ")");
// Comprobamos si el jugador gana
if ((entradaUsuario == 0 && movimientoAleatorio == 2) ||
(entradaUsuario == 1 && movimientoAleatorio == 0) ||
(entradaUsuario == 2 && movimientoAleatorio == 1)) {
resultadoJugador = 1;
} else if(entradaUsuario == movimientoAleatorio) { // Comprobamos si es un empate
resultadoJugador = 0;
} else { // en el resto de los casos el jugador pierde
resultadoJugador = 2;
}
// Imprimimos el resultado de la partida
System.out.println("Resultado: " + resultados[resultadoJugador]);
// Para separar el "menu" de moviemientos y la entrada del usuario
// con la salida/resultado de la partida marco
System.out.println("\n*******************************\n");
} while (entradaUsuario != -1);
}
}
|
velikGeorgiev/School
|
PRG/PiedraPapelTijera/Juego.java
|
Java
|
mit
| 5,080 |
package PracticeLeetCode;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class _127WordLadder {
psvm
}
|
darshanhs90/Java-InterviewPrep
|
src/PracticeLeetCode/_127WordLadder.java
|
Java
|
mit
| 169 |
package de.hilling.maven.release.testprojects.versioninheritor;
public class App {
public static void main(String[] args) {
System.out.println("1 + 2 = 3");
}
}
|
guhilling/smart-release-plugin
|
test-projects/ear-project/project-lib/src/main/java/de/hilling/maven/release/testprojects/versioninheritor/App.java
|
Java
|
mit
| 178 |
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.contracts.paymentservice.extensibility.v1;
import java.util.List;
import java.util.HashMap;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import com.mozu.api.contracts.paymentservice.extensibility.v1.ConnectionStatuses;
import com.mozu.api.contracts.paymentservice.extensibility.v1.KeyValueTuple;
/**
* Contains a credit response
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class GatewayCreditResponse implements Serializable
{
// Default Serial Version UID
private static final long serialVersionUID = 1L;
/**
* Set this to true if the transaction is declined or fails for any reason.
*/
protected Boolean isDeclined;
public Boolean getIsDeclined() {
return this.isDeclined;
}
public void setIsDeclined(Boolean isDeclined) {
this.isDeclined = isDeclined;
}
/**
* Contains the response code from the gateway.
*/
protected String responseCode;
public String getResponseCode() {
return this.responseCode;
}
public void setResponseCode(String responseCode) {
this.responseCode = responseCode;
}
/**
* Contains the text for the response, eg, 'Insufficient funds'.
*/
protected String responseText;
public String getResponseText() {
return this.responseText;
}
public void setResponseText(String responseText) {
this.responseText = responseText;
}
/**
* Contains the id for the transaction provided by the gateway.
*/
protected String transactionId;
public String getTransactionId() {
return this.transactionId;
}
public void setTransactionId(String transactionId) {
this.transactionId = transactionId;
}
/**
* Contains information about the interaction with the gateway.
*/
protected ConnectionStatuses remoteConnectionStatus;
public ConnectionStatuses getRemoteConnectionStatus() {
return this.remoteConnectionStatus;
}
public void setRemoteConnectionStatus(ConnectionStatuses remoteConnectionStatus) {
this.remoteConnectionStatus = remoteConnectionStatus;
}
/**
* Contains information not in the object allowing flexibility.
*/
protected List<KeyValueTuple> responseData;
public List<KeyValueTuple> getResponseData() {
return this.responseData;
}
public void setResponseData(List<KeyValueTuple> responseData) {
this.responseData = responseData;
}
}
|
Mozu/mozu-java
|
mozu-javaasync-core/src/main/java/com/mozu/api/contracts/paymentservice/extensibility/v1/GatewayCreditResponse.java
|
Java
|
mit
| 2,610 |
package uk.org.fyodor.generators;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import org.junit.Test;
import uk.org.fyodor.BaseTest;
public class PercentageChanceGeneratorTest extends BaseTest {
Multiset<Boolean> results = HashMultiset.create();
@Test
public void percentageChances(){
for (int p = 1; p < 100; p++) {
Generator<Boolean> percentageChance = RDG.percentageChanceOf(p);
for (int i = 0; i < 10000; i++) {
results.add(percentageChance.next());
}
print(p);
print("True: " + results.count(Boolean.TRUE));
print("False: " + results.count(Boolean.FALSE));
results.clear();
}
}
}
|
KarlWalsh/fyodor
|
fyodor-core/src/test/java/uk/org/fyodor/generators/PercentageChanceGeneratorTest.java
|
Java
|
mit
| 766 |
/*
Copyright 2006 by Sean Luke
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.parity.func;
import ec.*;
import ec.app.parity.*;
import ec.gp.*;
import ec.util.*;
/*
* D31.java
*
* Created: Wed Nov 3 18:31:38 1999
* By: Sean Luke
*/
/**
* @author Sean Luke
* @version 1.0
*/
public class D31 extends GPNode
{
public String toString() { return "D31"; }
/*
public void checkConstraints(final EvolutionState state,
final int tree,
final GPIndividual typicalIndividual,
final Parameter individualBase)
{
super.checkConstraints(state,tree,typicalIndividual,individualBase);
if (children.length!=0)
state.output.error("Incorrect number of children for node " +
toStringForError() + " at " +
individualBase);
}
*/
public int expectedChildren() { return 0; }
public void eval(final EvolutionState state,
final int thread,
final GPData input,
final ADFStack stack,
final GPIndividual individual,
final Problem problem)
{
((ParityData)input).x =
((((Parity)problem).bits >>> 31 ) & 1);
}
}
|
meiyi1986/GPJSS
|
src/ec/app/parity/func/D31.java
|
Java
|
mit
| 1,195 |
package mahout;
/**
* Date: 12/11/14
* Time: 8:33 PM
* To change this template use File | Settings | File Templates.
*/
public class AppConstants {
public static final String TEST_FILE = "dataset.csv";
}
|
syednasar/datascience
|
recommendations/mahoutrecommender/src/main/java/mahout/AppConstants.java
|
Java
|
mit
| 213 |
package org.jinstagram.auth.model;
import org.jinstagram.http.Request;
import org.jinstagram.http.Verbs;
import java.util.HashMap;
import java.util.Map;
/**
* The representation of an OAuth HttpRequest.
*
* Adds OAuth-related functionality to the {@link Request}
*/
public class OAuthRequest extends Request {
private static final String OAUTH_PREFIX = "oauth_";
private Map<String, String> oauthParameters;
/**
* Default constructor.
*
* @param verb Http verb/method
* @param url resource URL
*/
public OAuthRequest(Verbs verb, String url) {
super(verb, url);
this.oauthParameters = new HashMap<String, String>();
}
/**
* Adds an OAuth parameter.
*
* @param key name of the parameter
* @param value value of the parameter
*
* @throws IllegalArgumentException if the parameter is not an OAuth
* parameter
*/
public void addOAuthParameter(String key, String value) {
oauthParameters.put(checkKey(key), value);
}
private static String checkKey(String key) {
if (key.startsWith(OAUTH_PREFIX) || key.equals(OAuthConstants.SCOPE)) {
return key;
}
else {
throw new IllegalArgumentException(String.format(
"OAuth parameters must either be '%s' or start with '%s'",
OAuthConstants.SCOPE, OAUTH_PREFIX));
}
}
/**
* Returns the {@link Map} containing the key-value pair of parameters.
*
* @return parameters as map
*/
public Map<String, String> getOauthParameters() {
return oauthParameters;
}
@Override
public String toString() {
return String.format("@OAuthRequest(%s, %s)", getVerb(), getUrl());
}
}
|
zauberlabs/jInstagram
|
src/main/java/org/jinstagram/auth/model/OAuthRequest.java
|
Java
|
mit
| 1,596 |
package tracker.message.handlers;
import elasta.composer.message.handlers.MessageHandler;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
/**
* Created by sohan on 2017-07-26.
*/
public interface ReplayMessageHandler extends MessageHandler<JsonObject> {
@Override
void handle(Message<JsonObject> event);
}
|
codefacts/Elastic-Components
|
tracker/src/main/java/tracker/message/handlers/ReplayMessageHandler.java
|
Java
|
mit
| 347 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.eventhubs.v2017_04_01.implementation;
import java.util.List;
import org.joda.time.DateTime;
import com.microsoft.azure.management.eventhubs.v2017_04_01.EntityStatus;
import com.microsoft.azure.management.eventhubs.v2017_04_01.CaptureDescription;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.ProxyResource;
/**
* Single item in List or Get Event Hub operation.
*/
@JsonFlatten
public class EventhubInner extends ProxyResource {
/**
* Current number of shards on the Event Hub.
*/
@JsonProperty(value = "properties.partitionIds", access = JsonProperty.Access.WRITE_ONLY)
private List<String> partitionIds;
/**
* Exact time the Event Hub was created.
*/
@JsonProperty(value = "properties.createdAt", access = JsonProperty.Access.WRITE_ONLY)
private DateTime createdAt;
/**
* The exact time the message was updated.
*/
@JsonProperty(value = "properties.updatedAt", access = JsonProperty.Access.WRITE_ONLY)
private DateTime updatedAt;
/**
* Number of days to retain the events for this Event Hub, value should be
* 1 to 7 days.
*/
@JsonProperty(value = "properties.messageRetentionInDays")
private Long messageRetentionInDays;
/**
* Number of partitions created for the Event Hub, allowed values are from
* 1 to 32 partitions.
*/
@JsonProperty(value = "properties.partitionCount")
private Long partitionCount;
/**
* Enumerates the possible values for the status of the Event Hub. Possible
* values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled',
* 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
*/
@JsonProperty(value = "properties.status")
private EntityStatus status;
/**
* Properties of capture description.
*/
@JsonProperty(value = "properties.captureDescription")
private CaptureDescription captureDescription;
/**
* Get current number of shards on the Event Hub.
*
* @return the partitionIds value
*/
public List<String> partitionIds() {
return this.partitionIds;
}
/**
* Get exact time the Event Hub was created.
*
* @return the createdAt value
*/
public DateTime createdAt() {
return this.createdAt;
}
/**
* Get the exact time the message was updated.
*
* @return the updatedAt value
*/
public DateTime updatedAt() {
return this.updatedAt;
}
/**
* Get number of days to retain the events for this Event Hub, value should be 1 to 7 days.
*
* @return the messageRetentionInDays value
*/
public Long messageRetentionInDays() {
return this.messageRetentionInDays;
}
/**
* Set number of days to retain the events for this Event Hub, value should be 1 to 7 days.
*
* @param messageRetentionInDays the messageRetentionInDays value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withMessageRetentionInDays(Long messageRetentionInDays) {
this.messageRetentionInDays = messageRetentionInDays;
return this;
}
/**
* Get number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions.
*
* @return the partitionCount value
*/
public Long partitionCount() {
return this.partitionCount;
}
/**
* Set number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions.
*
* @param partitionCount the partitionCount value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withPartitionCount(Long partitionCount) {
this.partitionCount = partitionCount;
return this;
}
/**
* Get enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
*
* @return the status value
*/
public EntityStatus status() {
return this.status;
}
/**
* Set enumerates the possible values for the status of the Event Hub. Possible values include: 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', 'Renaming', 'Unknown'.
*
* @param status the status value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withStatus(EntityStatus status) {
this.status = status;
return this;
}
/**
* Get properties of capture description.
*
* @return the captureDescription value
*/
public CaptureDescription captureDescription() {
return this.captureDescription;
}
/**
* Set properties of capture description.
*
* @param captureDescription the captureDescription value to set
* @return the EventhubInner object itself.
*/
public EventhubInner withCaptureDescription(CaptureDescription captureDescription) {
this.captureDescription = captureDescription;
return this;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/eventhubs/mgmt-v2017_04_01/src/main/java/com/microsoft/azure/management/eventhubs/v2017_04_01/implementation/EventhubInner.java
|
Java
|
mit
| 5,503 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.advisor.v2017_04_19;
import com.microsoft.azure.arm.collection.SupportsCreating;
import rx.Completable;
import rx.Observable;
import com.microsoft.azure.management.advisor.v2017_04_19.implementation.SuppressionsInner;
import com.microsoft.azure.arm.model.HasInner;
/**
* Type representing Suppressions.
*/
public interface Suppressions extends SupportsCreating<SuppressionContract.DefinitionStages.Blank>, HasInner<SuppressionsInner> {
/**
* Retrieves the list of snoozed or dismissed suppressions for a subscription. The snoozed or dismissed attribute of a recommendation is referred to as a suppression.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<SuppressionContract> listAsync();
/**
* Obtains the details of a suppression.
*
* @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies.
* @param recommendationId The recommendation ID.
* @param name The name of the suppression.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<SuppressionContract> getAsync(String resourceUri, String recommendationId, String name);
/**
* Enables the activation of a snoozed or dismissed recommendation. The snoozed or dismissed attribute of a recommendation is referred to as a suppression.
*
* @param resourceUri The fully qualified Azure Resource Manager identifier of the resource to which the recommendation applies.
* @param recommendationId The recommendation ID.
* @param name The name of the suppression.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Completable deleteAsync(String resourceUri, String recommendationId, String name);
}
|
selvasingh/azure-sdk-for-java
|
sdk/advisor/mgmt-v2017_04_19/src/main/java/com/microsoft/azure/management/advisor/v2017_04_19/Suppressions.java
|
Java
|
mit
| 2,252 |
package com.xeiam.xchange.anx.v2.account.polling;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Assert;
import org.junit.Test;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.anx.v2.dto.account.polling.ANXWalletHistoryWrapper;
//import static org.fest.assertions.api.Assertions.assertThat;
/**
* Test ANXWalletHistory JSON parsing
*/
public class WalletHistoryJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is = WalletHistoryJSONTest.class.getResourceAsStream("/v2/account/example-wallethistory-response.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
ANXWalletHistoryWrapper anxWalletHistoryWrapper = mapper.readValue(is, ANXWalletHistoryWrapper.class);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory() != null);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getRecords() == 104);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getCurrentPage() == 1);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxPage() == 3);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getMaxResults() == 50);
Assert.assertTrue(anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries().length == 50);
Assert.assertEquals("BTC bought: [tid:264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51] 10.00000000 BTC at 280.65500 HKD", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0]
.getInfo());
Assert.assertEquals(104, anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getIndex());
Assert.assertEquals("1394594770000", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getDate());
Assert.assertEquals("fee", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getType());
Assert.assertEquals("BTC", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getCurrency());
// Assert.assertEquals(new BigDecimal(0),
// anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getValue().getValue());
Assert.assertEquals(new BigDecimal("103168.75400000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getBalance().getValue());
Assert.assertEquals("cc496636-4849-4acf-a390-e4091a5009c3", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getOid());
Assert.assertEquals("264f7b7f-f70c-4fc6-ba27-2bcf33b6cd51", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getTid());
Assert.assertEquals(new BigDecimal("10.00000000"), anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getAmount().getValue());
Assert.assertEquals("market", anxWalletHistoryWrapper.getANXWalletHistory().getANXWalletHistoryEntries()[0].getTrade().getProperties());
}
}
|
Achterhoeker/XChange
|
xchange-anx/src/test/java/com/xeiam/xchange/anx/v2/account/polling/WalletHistoryJSONTest.java
|
Java
|
mit
| 3,272 |
public class LeetCode0363 {
public int maxSumSubmatrix(int[][] matrix, int k) {
int m = matrix.length, n = matrix[0].length, ans = Integer.MIN_VALUE;
long[] sum = new long[m + 1];
for (int i = 0; i < n; ++i) {
long[] sumInRow = new long[m];
for (int j = i; j < n; ++j) {
for (int p = 0; p < m; ++p) {
sumInRow[p] += matrix[p][j];
sum[p + 1] = sum[p] + sumInRow[p];
}
ans = Math.max(ans, mergeSort(sum, 0, m + 1, k));
if (ans == k)
return k;
}
}
return ans;
}
int mergeSort(long[] sum, int start, int end, int k) {
if (end == start + 1)
return Integer.MIN_VALUE;
int mid = start + (end - start) / 2, cnt = 0;
int ans = mergeSort(sum, start, mid, k);
if (ans == k)
return k;
ans = Math.max(ans, mergeSort(sum, mid, end, k));
if (ans == k)
return k;
long[] cache = new long[end - start];
for (int i = start, j = mid, p = mid; i < mid; ++i) {
while (j < end && sum[j] - sum[i] <= k){
++j;
}
if (j - 1 >= mid) {
ans = Math.max(ans, (int) (sum[j - 1] - sum[i]));
if (ans == k){
return k;
}
}
while (p < end && sum[p] < sum[i]){
cache[cnt++] = sum[p++];
}
cache[cnt++] = sum[i];
}
System.arraycopy(cache, 0, sum, start, cnt);
return ans;
}
}
|
dunso/algorithm
|
Java/Devide/LeetCode0363.java
|
Java
|
mit
| 1,278 |
package com.ocdsoft.bacta.swg.shared.localization;
/**
* Created by crush on 11/21/2015.
*/
public class LocalizedString {
}
|
bacta/pre-cu
|
src/main/java/com/ocdsoft/bacta/swg/shared/localization/LocalizedString.java
|
Java
|
mit
| 128 |
package de.andreasgiemza.mangadownloader.gui.chapter;
import de.andreasgiemza.mangadownloader.MangaDownloader;
import de.andreasgiemza.mangadownloader.helpers.RegexHelper;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
/**
*
* @author Andreas Giemza <andreas@giemza.net>
*/
public class ChapterListSearchDocumentListener implements DocumentListener {
private final MangaDownloader mangaDownloader;
private final JTextField chapterListSearchTextField;
private final TableRowSorter<ChapterTableModel> chapterTableRowSorter;
@SuppressWarnings("unchecked")
public ChapterListSearchDocumentListener(MangaDownloader mangaDownloader,
JTextField chapterListSearchTextField, JTable chapterListTable) {
this.mangaDownloader = mangaDownloader;
this.chapterListSearchTextField = chapterListSearchTextField;
chapterTableRowSorter = (TableRowSorter<ChapterTableModel>) chapterListTable
.getRowSorter();
}
@Override
public void insertUpdate(DocumentEvent e) {
changed();
}
@Override
public void removeUpdate(DocumentEvent e) {
changed();
}
@Override
public void changedUpdate(DocumentEvent e) {
changed();
}
private void changed() {
mangaDownloader.chapterSearchChanged();
final String searchText = chapterListSearchTextField.getText();
if (searchText.length() == 0) {
chapterTableRowSorter.setRowFilter(null);
} else if (searchText.length() > 0) {
chapterTableRowSorter.setRowFilter(RowFilter
.regexFilter(RegexHelper.build(searchText)));
}
}
}
|
hurik/MangaDownloader
|
src/main/java/de/andreasgiemza/mangadownloader/gui/chapter/ChapterListSearchDocumentListener.java
|
Java
|
mit
| 1,897 |
package nxt.http;
import nxt.Account;
import nxt.Attachment;
import nxt.Constants;
import nxt.NxtException;
import nxt.util.Convert;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_ASSET;
import static nxt.http.JSONResponses.INCORRECT_PRICE;
import static nxt.http.JSONResponses.INCORRECT_QUANTITY;
import static nxt.http.JSONResponses.MISSING_ASSET;
import static nxt.http.JSONResponses.MISSING_PRICE;
import static nxt.http.JSONResponses.MISSING_QUANTITY;
import static nxt.http.JSONResponses.NOT_ENOUGH_ASSETS;
import static nxt.http.JSONResponses.UNKNOWN_ACCOUNT;
public final class PlaceAskOrder extends CreateTransaction {
static final PlaceAskOrder instance = new PlaceAskOrder();
private PlaceAskOrder() {
super("asset", "quantity", "price");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException {
String assetValue = req.getParameter("asset");
String quantityValue = req.getParameter("quantity");
String priceValue = req.getParameter("price");
if (assetValue == null) {
return MISSING_ASSET;
} else if (quantityValue == null) {
return MISSING_QUANTITY;
} else if (priceValue == null) {
return MISSING_PRICE;
}
long price;
try {
price = Long.parseLong(priceValue);
if (price <= 0 || price > Constants.MAX_BALANCE * 100L) {
return INCORRECT_PRICE;
}
} catch (NumberFormatException e) {
return INCORRECT_PRICE;
}
Long asset;
try {
asset = Convert.parseUnsignedLong(assetValue);
} catch (RuntimeException e) {
return INCORRECT_ASSET;
}
int quantity;
try {
quantity = Integer.parseInt(quantityValue);
if (quantity <= 0 || quantity > Constants.MAX_ASSET_QUANTITY) {
return INCORRECT_QUANTITY;
}
} catch (NumberFormatException e) {
return INCORRECT_QUANTITY;
}
Account account = getAccount(req);
if (account == null) {
return UNKNOWN_ACCOUNT;
}
Integer assetBalance = account.getUnconfirmedAssetBalance(asset);
if (assetBalance == null || quantity > assetBalance) {
return NOT_ENOUGH_ASSETS;
}
Attachment attachment = new Attachment.ColoredCoinsAskOrderPlacement(asset, quantity, price);
return createTransaction(req, account, attachment);
}
}
|
aspnmy/NasCoin
|
src/java/nxt/http/PlaceAskOrder.java
|
Java
|
mit
| 2,662 |
package net.sf.esfinge.metadata.validate.minValue;
|
pedrocavalero/metadata
|
src/test/java/net/sf/esfinge/metadata/validate/minValue/package-info.java
|
Java
|
mit
| 50 |
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package cn.sharesdk.demo.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore.Images.Media;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
@TargetApi(17)
public class ScreenShotListenManager {
private static final String TAG = "ScreenShotListenManager";
private static final String[] MEDIA_PROJECTIONS = new String[]{"_data", "datetaken"};
private static final String[] MEDIA_PROJECTIONS_API_16 = new String[]{"_data", "datetaken", "width", "height"};
private static final String[] KEYWORDS = new String[]{"screenshot", "screen_shot", "screen-shot", "screen shot", "screencapture",
"screen_capture", "screen-capture", "screen capture", "screencap", "screen_cap", "screen-cap", "screen cap"};
private static Point sScreenRealSize;
private final List<String> sHasCallbackPaths = new ArrayList();
private Context context;
private OnScreenShotListener listener;
private long startListenTime;
private MediaContentObserver internalObserver;
private MediaContentObserver externalObserver;
private final Handler uiHandler = new Handler(Looper.getMainLooper());
private ScreenShotListenManager(Context context) {
if(context == null) {
throw new IllegalArgumentException("The context must not be null.");
} else {
this.context = context;
if(sScreenRealSize == null) {
sScreenRealSize = this.getRealScreenSize();
if(sScreenRealSize != null) {
Log.d("ScreenShotListenManager", "Screen Real Size: " + sScreenRealSize.x + " * " + sScreenRealSize.y);
} else {
Log.w("ScreenShotListenManager", "Get screen real size failed.");
}
}
}
}
public static ScreenShotListenManager newInstance(Context context) {
assertInMainThread();
return new ScreenShotListenManager(context);
}
public void startListen() {
assertInMainThread();
this.sHasCallbackPaths.clear();
this.startListenTime = System.currentTimeMillis();
this.internalObserver = new MediaContentObserver(Media.INTERNAL_CONTENT_URI, this.uiHandler);
this.externalObserver = new MediaContentObserver(Media.EXTERNAL_CONTENT_URI, this.uiHandler);
this.context.getContentResolver().registerContentObserver(Media.INTERNAL_CONTENT_URI, false, this.internalObserver);
this.context.getContentResolver().registerContentObserver(Media.EXTERNAL_CONTENT_URI, false, this.externalObserver);
}
public void stopListen() {
assertInMainThread();
if(this.internalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.internalObserver);
} catch (Exception var3) {
var3.printStackTrace();
}
this.internalObserver = null;
}
if(this.externalObserver != null) {
try {
this.context.getContentResolver().unregisterContentObserver(this.externalObserver);
} catch (Exception var2) {
var2.printStackTrace();
}
this.externalObserver = null;
}
this.startListenTime = 0L;
this.sHasCallbackPaths.clear();
}
private void handleMediaContentChange(Uri contentUri) {
Cursor cursor = null;
try {
cursor = this.context.getContentResolver().query(contentUri, VERSION.SDK_INT < 16 ? MEDIA_PROJECTIONS : MEDIA_PROJECTIONS_API_16,
(String)null, (String[])null, "date_added desc limit 1");
if(cursor == null) {
Log.e("ScreenShotListenManager", "Deviant logic.");
return;
}
if(cursor.moveToFirst()) {
int e = cursor.getColumnIndex("_data");
int dateTakenIndex = cursor.getColumnIndex("datetaken");
int widthIndex = -1;
int heightIndex = -1;
if(VERSION.SDK_INT >= 16) {
widthIndex = cursor.getColumnIndex("width");
heightIndex = cursor.getColumnIndex("height");
}
String data = cursor.getString(e);
long dateTaken = cursor.getLong(dateTakenIndex);
boolean width = false;
boolean height = false;
int width1;
int height1;
if(widthIndex >= 0 && heightIndex >= 0) {
width1 = cursor.getInt(widthIndex);
height1 = cursor.getInt(heightIndex);
} else {
Point size = this.getImageSize(data);
width1 = size.x;
height1 = size.y;
}
this.handleMediaRowData(data, dateTaken, width1, height1);
return;
}
Log.d("ScreenShotListenManager", "Cursor no data.");
} catch (Exception var16) {
var16.printStackTrace();
return;
} finally {
if(cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
private Point getImageSize(String imagePath) {
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
return new Point(options.outWidth, options.outHeight);
}
private void handleMediaRowData(String data, long dateTaken, int width, int height) {
if(this.checkScreenShot(data, dateTaken, width, height)) {
Log.d("ScreenShotListenManager", "ScreenShot: path = " + data + "; size = " + width + " * " + height + "; date = " + dateTaken);
if(this.listener != null && !this.checkCallback(data)) {
this.listener.onShot(data);
}
} else {
Log.w("ScreenShotListenManager", "Media content changed, but not screenshot: path = " + data + "; size = " + width + " * "
+ height + "; date = " + dateTaken);
}
}
private boolean checkScreenShot(String data, long dateTaken, int width, int height) {
long currentTime = System.currentTimeMillis() - dateTaken;
if(dateTaken >= this.startListenTime && currentTime <= 20000L) {
if(sScreenRealSize == null || width <= sScreenRealSize.x && height <= sScreenRealSize.y || height <= sScreenRealSize.x
&& width <= sScreenRealSize.y) {
if(TextUtils.isEmpty(data)) {
return false;
} else {
data = data.toLowerCase();
String[] var11 = KEYWORDS;
int var10 = KEYWORDS.length;
for(int var9 = 0; var9 < var10; var9++) {
String keyWork = var11[var9];
if(data.contains(keyWork)) {
return true;
}
}
return false;
}
} else {
return false;
}
} else {
return false;
}
}
private boolean checkCallback(String imagePath) {
if(this.sHasCallbackPaths.contains(imagePath)) {
return true;
} else {
if(this.sHasCallbackPaths.size() >= 20) {
for(int i = 0; i < 5; i++) {
this.sHasCallbackPaths.remove(0);
}
}
this.sHasCallbackPaths.add(imagePath);
return false;
}
}
private Point getRealScreenSize() {
Point screenSize = null;
try {
screenSize = new Point();
WindowManager e = (WindowManager)this.context.getSystemService("window");
Display defaultDisplay = e.getDefaultDisplay();
if(VERSION.SDK_INT >= 17) {
defaultDisplay.getRealSize(screenSize);
} else {
try {
Method e1 = Display.class.getMethod("getRawWidth", new Class[0]);
Method getRawH = Display.class.getMethod("getRawHeight", new Class[0]);
screenSize.set(((Integer)e1.invoke(defaultDisplay, new Object[0])).intValue(),
((Integer)getRawH.invoke(defaultDisplay, new Object[0])).intValue());
} catch (Exception var6) {
screenSize.set(defaultDisplay.getWidth(), defaultDisplay.getHeight());
var6.printStackTrace();
}
}
} catch (Exception var7) {
var7.printStackTrace();
}
return screenSize;
}
public void setListener(ScreenShotListenManager.OnScreenShotListener listener) {
this.listener = listener;
}
private static void assertInMainThread() {
if(Looper.myLooper() != Looper.getMainLooper()) {
StackTraceElement[] elements = Thread.currentThread().getStackTrace();
String methodMsg = null;
if(elements != null && elements.length >= 4) {
methodMsg = elements[3].toString();
}
throw new IllegalStateException("Call the method must be in main thread: " + methodMsg);
}
}
private class MediaContentObserver extends ContentObserver {
private Uri contentUri;
public MediaContentObserver(Uri contentUri, Handler handler) {
super(handler);
this.contentUri = contentUri;
}
public void onChange(boolean selfChange) {
super.onChange(selfChange);
handleMediaContentChange(this.contentUri);
}
}
public interface OnScreenShotListener {
void onShot(String var1);
}
}
|
ShareSDKPlatform/ShareSDK-for-Android
|
SampleFresh/app/src/main/java/cn/sharesdk/demo/utils/ScreenShotListenManager.java
|
Java
|
mit
| 8,651 |
package velir.intellij.cq5.util;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import java.util.ArrayList;
import java.util.List;
/**
* Utility class for helping work with Repository objects.
*/
public class RepositoryUtils {
/**
* Hide default constructor for true static class.
*/
private RepositoryUtils() {
}
public static List<String> getAllNodeTypeNames(Session session) throws RepositoryException {
//get our child nodeTypes from our root
NodeIterator nodeTypes = getAllNodeTypes(session);
//go through each node type and pull out the name
List<String> nodeTypeNames = new ArrayList<String>();
while (nodeTypes.hasNext()) {
Node node = nodeTypes.nextNode();
nodeTypeNames.add(node.getName());
}
//return our node type names
return nodeTypeNames;
}
/**
* Will get all the nodes that represent the different node types.
*
* @param session Repository session to use for pulling out this information.
* @return
* @throws RepositoryException
*/
public static NodeIterator getAllNodeTypes(Session session) throws RepositoryException {
//get our node types root
Node nodeTypesRoot = session.getNode("/jcr:system/jcr:nodeTypes");
//get our child nodeTypes from our root
return nodeTypesRoot.getNodes();
}
}
|
tmowad/intellij-jcr-plugin
|
source/src/velir/intellij/cq5/util/RepositoryUtils.java
|
Java
|
mit
| 1,342 |
package queue;
/**
* Queue server metadata manager.
*
* @author Thanh Nguyen <btnguyen2k@gmail.com>
* @since 0.1.0
*/
public interface IQsMetadataManager {
}
|
kangkot/queue-server
|
app/queue/IQsMetadataManager.java
|
Java
|
mit
| 166 |
class Test {
public static int[] test() {
return null;
}
public static void main(String[] args) {
int [] arr = test();
System.out.println(arr);
}
|
parin2092/cook
|
Test.java
|
Java
|
mit
| 154 |
package com.example.exampleeureka;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class ExampleEurekaApplicationTests {
@Test
public void contextLoads() {
}
}
|
ko-sasaki/springboot-example
|
springboot-eureka-server/src/test/java/com/example/exampleeureka/ExampleEurekaApplicationTests.java
|
Java
|
mit
| 349 |
package com.github.bachelorpraktikum.visualisierbar.model;
import com.github.bachelorpraktikum.visualisierbar.model.Element.State;
import com.github.bachelorpraktikum.visualisierbar.model.Element.Type;
public class ElementShapeableTest extends ShapeableImplementationTest {
@Override
protected Shapeable<?> getShapeable() {
Context context = new Context();
Node node = Node.in(context).create("node", new Coordinates(0, 0));
return Element.in(context).create("element", Type.HauptSignal, node, State.FAHRT);
}
}
|
Bachelorpraktikum/VisualisierbaR
|
src/test/java/com/github/bachelorpraktikum/visualisierbar/model/ElementShapeableTest.java
|
Java
|
mit
| 551 |
/**
* The MIT License
*
* Copyright (c) 2019, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jeasy.random;
import static org.jeasy.random.FieldPredicates.*;
import static org.assertj.core.api.Assertions.assertThat;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import org.jeasy.random.api.ContextAwareRandomizer;
import org.jeasy.random.api.RandomizerContext;
import org.jeasy.random.beans.*;
import org.jeasy.random.beans.exclusion.A;
import org.jeasy.random.beans.exclusion.B;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.jeasy.random.beans.exclusion.C;
@ExtendWith(MockitoExtension.class)
class FieldExclusionTest {
private EasyRandom easyRandom;
@BeforeEach
void setUp() {
easyRandom = new EasyRandom();
}
@Test
void excludedFieldsShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("name"));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
//then
assertThat(person).isNotNull();
assertThat(person.getName()).isNull();
}
@Test
void excludedFieldsUsingSkipRandomizerShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("name").and(ofType(String.class)).and(inClass(Human.class)));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getName()).isNull();
}
@Test
void excludedFieldsUsingFieldDefinitionShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(named("name"));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getAddress()).isNotNull();
assertThat(person.getAddress().getStreet()).isNotNull();
// person.name and street.name should be null
assertThat(person.getName()).isNull();
assertThat(person.getAddress().getStreet().getName()).isNull();
}
@Test
void excludedDottedFieldsShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("name").and(inClass(Street.class)));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getAddress()).isNotNull();
assertThat(person.getAddress().getStreet()).isNotNull();
assertThat(person.getAddress().getStreet().getName()).isNull();
}
@Test
void fieldsExcludedWithAnnotationShouldNotBePopulated() {
Person person = easyRandom.nextObject(Person.class);
assertThat(person).isNotNull();
assertThat(person.getExcluded()).isNull();
}
@Test
@SuppressWarnings("deprecation")
void fieldsExcludedWithAnnotationViaFieldDefinitionShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(isAnnotatedWith(Deprecated.class));
easyRandom = new EasyRandom(parameters);
// when
Website website = easyRandom.nextObject(Website.class);
// then
assertThat(website).isNotNull();
assertThat(website.getProvider()).isNull();
}
@Test
void fieldsExcludedFromTypeViaFieldDefinitionShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(inClass(Address.class));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getAddress()).isNotNull();
// all fields declared in class Address must be null
assertThat(person.getAddress().getCity()).isNull();
assertThat(person.getAddress().getStreet()).isNull();
assertThat(person.getAddress().getZipCode()).isNull();
assertThat(person.getAddress().getCountry()).isNull();
}
@Test
void testFirstLevelExclusion() {
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("b2").and(inClass(C.class)));
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// B2 must be null
assertThat(c.getB2()).isNull();
}
@Test
void testSecondLevelExclusion() { // goal: exclude only b2.a2
EasyRandomParameters parameters = new EasyRandomParameters()
.randomize(ofType(A.class).and(inClass(B.class)), new ContextAwareRandomizer<A>() {
private RandomizerContext context;
@Override
public void setRandomizerContext(RandomizerContext context) {
this.context = context;
}
@Override
public A getRandomValue() {
if (context.getCurrentField().equals("b2.a2")) {
return null;
}
return new EasyRandom().nextObject(A.class);
}
});
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// Only B2.A2 must be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2()).isNull();
}
@Test
void testThirdLevelExclusion() { // goal: exclude only b2.a2.s2
EasyRandomParameters parameters = new EasyRandomParameters()
.randomize(FieldPredicates.named("s2").and(inClass(A.class)), new ContextAwareRandomizer<String>() {
private RandomizerContext context;
@Override
public void setRandomizerContext(RandomizerContext context) {
this.context = context;
}
@Override
public String getRandomValue() {
if (context.getCurrentField().equals("b2.a2.s2")) {
return null;
}
return new EasyRandom().nextObject(String.class);
}
});
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// Only B2.A2.S2 must be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2().getS1()).isNotNull();
assertThat(c.getB2().getA2().getS2()).isNull();
}
@Test
void testFirstLevelCollectionExclusion() {
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(FieldPredicates.named("b3").and(inClass(C.class)));
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2()).isNotNull();
assertThat(c.getB2().getA2().getS1()).isNotNull();
assertThat(c.getB2().getA2().getS2()).isNotNull();
// B3 must be null
assertThat(c.getB3()).isNull();
}
@Test
void testSecondLevelCollectionExclusion() { // b3.a2 does not make sense, should be ignored
EasyRandomParameters parameters = new EasyRandomParameters()
.randomize(FieldPredicates.named("a2").and(inClass(B.class)), new ContextAwareRandomizer<A>() {
private RandomizerContext context;
@Override
public void setRandomizerContext(RandomizerContext context) {
this.context = context;
}
@Override
public A getRandomValue() {
if (context.getCurrentField().equals("b3.a2")) {
return null;
}
return new EasyRandom().nextObject(A.class);
}
});
easyRandom = new EasyRandom(parameters);
C c = easyRandom.nextObject(C.class);
assertThat(c).isNotNull();
// B1 and its "children" must not be null
assertThat(c.getB1()).isNotNull();
assertThat(c.getB1().getA1()).isNotNull();
assertThat(c.getB1().getA1().getS1()).isNotNull();
assertThat(c.getB1().getA1().getS2()).isNotNull();
assertThat(c.getB1().getA2()).isNotNull();
assertThat(c.getB1().getA2().getS1()).isNotNull();
assertThat(c.getB1().getA2().getS2()).isNotNull();
// B2 and its "children" must not be null
assertThat(c.getB2()).isNotNull();
assertThat(c.getB2().getA1()).isNotNull();
assertThat(c.getB2().getA1().getS1()).isNotNull();
assertThat(c.getB2().getA1().getS2()).isNotNull();
assertThat(c.getB2().getA2()).isNotNull();
assertThat(c.getB2().getA2().getS1()).isNotNull();
assertThat(c.getB2().getA2().getS2()).isNotNull();
// B3 must not be null
assertThat(c.getB3()).isNotNull();
}
@Test
void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBean.class)));
easyRandom = new EasyRandom(parameters);
// when
InlineInitializationBean bean = easyRandom.nextObject(InlineInitializationBean.class);
// then
assertThat(bean).isNotNull();
assertThat(bean.getMyList()).isEmpty();
}
@Test
void whenFieldIsExcluded_thenItsInlineInitializationShouldBeUsedAsIs_EvenIfBeanHasNoPublicConstructor() {
// given
EasyRandomParameters parameters = new EasyRandomParameters()
.excludeField(named("myList").and(ofType(List.class)).and(inClass(InlineInitializationBeanPrivateConstructor.class)));
easyRandom = new EasyRandom(parameters);
// when
InlineInitializationBeanPrivateConstructor bean = easyRandom.nextObject(InlineInitializationBeanPrivateConstructor.class);
// then
assertThat(bean.getMyList()).isEmpty();
}
@Test
void fieldsExcludedWithOneModifierShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getEmail()).isNull();
}
@Test
void fieldsExcludedWithTwoModifiersShouldNotBePopulated() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PROTECTED));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getEmail()).isNull();
}
@Test
void fieldsExcludedWithTwoModifiersShouldBePopulatedIfOneModifierIsNotFit() {
// given
EasyRandomParameters parameters = new EasyRandomParameters().excludeField(hasModifiers(Modifier.TRANSIENT | Modifier.PUBLIC));
easyRandom = new EasyRandom(parameters);
// when
Person person = easyRandom.nextObject(Person.class);
// then
assertThat(person).isNotNull();
assertThat(person.getEmail()).isNotNull();
}
public static class InlineInitializationBean {
private List<String> myList = new ArrayList<>();
public List<String> getMyList() {
return myList;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
}
public static class InlineInitializationBeanPrivateConstructor {
private List<String> myList = new ArrayList<>();
public List<String> getMyList() {
return myList;
}
private InlineInitializationBeanPrivateConstructor() {}
}
}
|
benas/jPopulator
|
easy-random-core/src/test/java/org/jeasy/random/FieldExclusionTest.java
|
Java
|
mit
| 16,362 |
package logbook.server.proxy;
/**
* 動作に必要なデータのみ取得するためのフィルターです。
*
*/
public class Filter {
/** フィルターするContent-Type */
public static final String CONTENT_TYPE_FILTER = "text/plain";
/** キャプチャーするリクエストのバイトサイズ上限 */
public static final int MAX_POST_FIELD_SIZE = 1024 * 1024;
/** setAttribute用のキー(Response) */
public static final String RESPONSE_BODY = "res-body";
/** setAttribute用のキー(Request) */
public static final String REQUEST_BODY = "req-body";
private static String serverName;
/**
* 鎮守府サーバー名を設定する
* @param name 鎮守府サーバー名
*/
public static void setServerName(String name) {
serverName = name;
}
/**
* 鎮守府サーバー名を取得する
* @param name 鎮守府サーバー名
*/
public static String getServerName() {
return serverName;
}
/**
* 鎮守府サーバー名を検出した場合true
*
* @return 鎮守府サーバー名を検出した場合true
*/
public static boolean isServerDetected() {
return serverName != null;
}
/**
* <p>
* 取得が必要なデータかを調べます<br>
* 鎮守府サーバーが検出された場合はサーバー名から必要かどうかを判別します<br>
* 鎮守府サーバーが検出できていない場合は常にtrue<br>
*
* @param name サーバー名
* @return 取得が必要なデータか
*/
public static boolean isNeed(String name) {
if ((!isServerDetected() || (isServerDetected() && serverName.equals(name)))) {
return true;
}
return false;
}
/**
* <p>
* 取得が必要なデータかを調べます<br>
* 鎮守府サーバーが検出された場合はサーバー名とContent-Typeから必要かどうかを判別します<br>
* 鎮守府サーバーが検出できていない場合はContent-Typeから必要かどうかを判別します<br>
*
* @param name サーバー名
* @param contentType Content-Type
* @return 取得が必要なデータか
*/
public static boolean isNeed(String name, String contentType) {
if ((!isServerDetected() || serverName.equals(name))
&& CONTENT_TYPE_FILTER.equals(contentType)) {
return true;
}
return false;
}
}
|
silfumus/logbook-EN
|
main/logbook/server/proxy/Filter.java
|
Java
|
mit
| 2,555 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ForwardDocumentEvent.proto
package Diadoc.Api.Proto;
public final class ForwardDocumentEventProtos {
private ForwardDocumentEventProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface ForwardDocumentEventOrBuilder extends
// @@protoc_insertion_point(interface_extends:Diadoc.Api.Proto.ForwardDocumentEvent)
com.google.protobuf.MessageOrBuilder {
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
boolean hasTimestamp();
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp();
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder();
/**
* <code>optional string ToBoxId = 2;</code>
*/
boolean hasToBoxId();
/**
* <code>optional string ToBoxId = 2;</code>
*/
java.lang.String getToBoxId();
/**
* <code>optional string ToBoxId = 2;</code>
*/
com.google.protobuf.ByteString
getToBoxIdBytes();
}
/**
* Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent}
*/
public static final class ForwardDocumentEvent extends
com.google.protobuf.GeneratedMessage implements
// @@protoc_insertion_point(message_implements:Diadoc.Api.Proto.ForwardDocumentEvent)
ForwardDocumentEventOrBuilder {
// Use ForwardDocumentEvent.newBuilder() to construct.
private ForwardDocumentEvent(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private ForwardDocumentEvent(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final ForwardDocumentEvent defaultInstance;
public static ForwardDocumentEvent getDefaultInstance() {
return defaultInstance;
}
public ForwardDocumentEvent getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private ForwardDocumentEvent(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder subBuilder = null;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
subBuilder = timestamp_.toBuilder();
}
timestamp_ = input.readMessage(Diadoc.Api.Proto.TimestampProtos.Timestamp.PARSER, extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(timestamp_);
timestamp_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000001;
break;
}
case 18: {
com.google.protobuf.ByteString bs = input.readBytes();
bitField0_ |= 0x00000002;
toBoxId_ = bs;
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class);
}
public static com.google.protobuf.Parser<ForwardDocumentEvent> PARSER =
new com.google.protobuf.AbstractParser<ForwardDocumentEvent>() {
public ForwardDocumentEvent parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ForwardDocumentEvent(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<ForwardDocumentEvent> getParserForType() {
return PARSER;
}
private int bitField0_;
public static final int TIMESTAMP_FIELD_NUMBER = 1;
private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_;
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public boolean hasTimestamp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() {
return timestamp_;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() {
return timestamp_;
}
public static final int TOBOXID_FIELD_NUMBER = 2;
private java.lang.Object toBoxId_;
/**
* <code>optional string ToBoxId = 2;</code>
*/
public boolean hasToBoxId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public java.lang.String getToBoxId() {
java.lang.Object ref = toBoxId_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
toBoxId_ = s;
}
return s;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public com.google.protobuf.ByteString
getToBoxIdBytes() {
java.lang.Object ref = toBoxId_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
toBoxId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private void initFields() {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
toBoxId_ = "";
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
if (hasTimestamp()) {
if (!getTimestamp().isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeMessage(1, timestamp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, getToBoxIdBytes());
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, timestamp_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, getToBoxIdBytes());
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code Diadoc.Api.Proto.ForwardDocumentEvent}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Diadoc.Api.Proto.ForwardDocumentEvent)
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEventOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable
.ensureFieldAccessorsInitialized(
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.class, Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.Builder.class);
}
// Construct using Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getTimestampFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (timestampBuilder_ == null) {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
} else {
timestampBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
toBoxId_ = "";
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent getDefaultInstanceForType() {
return Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance();
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent build() {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent buildPartial() {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent result = new Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
if (timestampBuilder_ == null) {
result.timestamp_ = timestamp_;
} else {
result.timestamp_ = timestampBuilder_.build();
}
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.toBoxId_ = toBoxId_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) {
return mergeFrom((Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent other) {
if (other == Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent.getDefaultInstance()) return this;
if (other.hasTimestamp()) {
mergeTimestamp(other.getTimestamp());
}
if (other.hasToBoxId()) {
bitField0_ |= 0x00000002;
toBoxId_ = other.toBoxId_;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (hasTimestamp()) {
if (!getTimestamp().isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Diadoc.Api.Proto.ForwardDocumentEventProtos.ForwardDocumentEvent) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private Diadoc.Api.Proto.TimestampProtos.Timestamp timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder> timestampBuilder_;
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public boolean hasTimestamp() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp getTimestamp() {
if (timestampBuilder_ == null) {
return timestamp_;
} else {
return timestampBuilder_.getMessage();
}
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder setTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) {
if (timestampBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
timestamp_ = value;
onChanged();
} else {
timestampBuilder_.setMessage(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder setTimestamp(
Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder builderForValue) {
if (timestampBuilder_ == null) {
timestamp_ = builderForValue.build();
onChanged();
} else {
timestampBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder mergeTimestamp(Diadoc.Api.Proto.TimestampProtos.Timestamp value) {
if (timestampBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001) &&
timestamp_ != Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance()) {
timestamp_ =
Diadoc.Api.Proto.TimestampProtos.Timestamp.newBuilder(timestamp_).mergeFrom(value).buildPartial();
} else {
timestamp_ = value;
}
onChanged();
} else {
timestampBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000001;
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Builder clearTimestamp() {
if (timestampBuilder_ == null) {
timestamp_ = Diadoc.Api.Proto.TimestampProtos.Timestamp.getDefaultInstance();
onChanged();
} else {
timestampBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000001);
return this;
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder getTimestampBuilder() {
bitField0_ |= 0x00000001;
onChanged();
return getTimestampFieldBuilder().getBuilder();
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
public Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder getTimestampOrBuilder() {
if (timestampBuilder_ != null) {
return timestampBuilder_.getMessageOrBuilder();
} else {
return timestamp_;
}
}
/**
* <code>optional .Diadoc.Api.Proto.Timestamp Timestamp = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>
getTimestampFieldBuilder() {
if (timestampBuilder_ == null) {
timestampBuilder_ = new com.google.protobuf.SingleFieldBuilder<
Diadoc.Api.Proto.TimestampProtos.Timestamp, Diadoc.Api.Proto.TimestampProtos.Timestamp.Builder, Diadoc.Api.Proto.TimestampProtos.TimestampOrBuilder>(
getTimestamp(),
getParentForChildren(),
isClean());
timestamp_ = null;
}
return timestampBuilder_;
}
private java.lang.Object toBoxId_ = "";
/**
* <code>optional string ToBoxId = 2;</code>
*/
public boolean hasToBoxId() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public java.lang.String getToBoxId() {
java.lang.Object ref = toBoxId_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
if (bs.isValidUtf8()) {
toBoxId_ = s;
}
return s;
} else {
return (java.lang.String) ref;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public com.google.protobuf.ByteString
getToBoxIdBytes() {
java.lang.Object ref = toBoxId_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8(
(java.lang.String) ref);
toBoxId_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder setToBoxId(
java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
toBoxId_ = value;
onChanged();
return this;
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder clearToBoxId() {
bitField0_ = (bitField0_ & ~0x00000002);
toBoxId_ = getDefaultInstance().getToBoxId();
onChanged();
return this;
}
/**
* <code>optional string ToBoxId = 2;</code>
*/
public Builder setToBoxIdBytes(
com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
toBoxId_ = value;
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:Diadoc.Api.Proto.ForwardDocumentEvent)
}
static {
defaultInstance = new ForwardDocumentEvent(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:Diadoc.Api.Proto.ForwardDocumentEvent)
}
private static final com.google.protobuf.Descriptors.Descriptor
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\032ForwardDocumentEvent.proto\022\020Diadoc.Api" +
".Proto\032\017Timestamp.proto\"W\n\024ForwardDocume" +
"ntEvent\022.\n\tTimestamp\030\001 \001(\0132\033.Diadoc.Api." +
"Proto.Timestamp\022\017\n\007ToBoxId\030\002 \001(\tB\034B\032Forw" +
"ardDocumentEventProtos"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
Diadoc.Api.Proto.TimestampProtos.getDescriptor(),
}, assigner);
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_Diadoc_Api_Proto_ForwardDocumentEvent_descriptor,
new java.lang.String[] { "Timestamp", "ToBoxId", });
Diadoc.Api.Proto.TimestampProtos.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
|
halex2005/diadocsdk-java
|
src/main/java/Diadoc/Api/Proto/ForwardDocumentEventProtos.java
|
Java
|
mit
| 27,479 |
package saberapplications.pawpads.databinding;
import android.databinding.BaseObservable;
import android.databinding.BindingAdapter;
import android.databinding.BindingConversion;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import saberapplications.pawpads.R;
/**
* Created by Stanislav Volnjanskij on 25.08.16.
*/
public class BindableDouble extends BaseObservable {
private Double value;
private String format="%f";
public Double get() {
return value;
}
public void set(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
notifyChange();
}
}
public void setSilent(double value) {
if (this.value == null || !this.value.equals(value)) {
this.value = value;
}
}
public BindableDouble(double value) {
super();
this.value = value;
}
public BindableDouble() {
super();
}
@BindingConversion
public static String convertIntegerToString(BindableDouble value) {
if (value != null && value.get()!=null)
return String.format(value.getFormat(), value.get());
else {
return null;
}
}
@BindingAdapter({"binding2way"})
public static void bindEditText(EditText view,
final BindableDouble bindableDouble) {
if (view.getTag(R.id.BIND_ID) == null) {
view.setTag(R.id.BIND_ID, true);
view.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
try {
bindableDouble.setSilent(Double.parseDouble(s.toString()));
} catch (Exception e) {
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
//initial value
if (bindableDouble == null) return;
Double newValue = bindableDouble.get();
if (newValue == null) return;
String strValue= String.format(bindableDouble.getFormat(),newValue);
if (!view.getText().toString().equals(strValue) ) {
view.setText(strValue);
}
}
/**
* Number format to display in text field
* @return
*/
public String getFormat() {
return format;
}
/**
*Set number format to display in text field
* @param format
*/
public void setFormat(String format) {
this.format = format;
}
}
|
castaway2000/Pawpads
|
app/src/main/java/saberapplications/pawpads/databinding/BindableDouble.java
|
Java
|
mit
| 2,887 |
/*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.core.entity;
import com.google.j2objc.annotations.Property;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import im.actor.core.api.ApiAvatar;
import im.actor.core.api.ApiBotCommand;
import im.actor.core.api.ApiContactRecord;
import im.actor.core.api.ApiContactType;
import im.actor.core.api.ApiFullUser;
import im.actor.core.api.ApiInt32Value;
import im.actor.core.api.ApiMapValue;
import im.actor.core.api.ApiMapValueItem;
import im.actor.core.api.ApiUser;
import im.actor.runtime.bser.BserCreator;
import im.actor.runtime.bser.BserValues;
import im.actor.runtime.bser.BserWriter;
import im.actor.runtime.storage.KeyValueItem;
// Disabling Bounds checks for speeding up calculations
/*-[
#define J2OBJC_DISABLE_ARRAY_BOUND_CHECKS 1
]-*/
public class User extends WrapperExtEntity<ApiFullUser, ApiUser> implements KeyValueItem {
private static final int RECORD_ID = 10;
private static final int RECORD_FULL_ID = 20;
public static BserCreator<User> CREATOR = User::new;
@Property("readonly, nonatomic")
private int uid;
@Property("readonly, nonatomic")
private long accessHash;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private String name;
@Nullable
@Property("readonly, nonatomic")
private String localName;
@Nullable
@Property("readonly, nonatomic")
private String username;
@Nullable
@Property("readonly, nonatomic")
private String about;
@Nullable
@Property("readonly, nonatomic")
private Avatar avatar;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private Sex sex;
@Property("readonly, nonatomic")
private boolean isBot;
@NotNull
@Property("readonly, nonatomic")
@SuppressWarnings("NullableProblems")
private List<ContactRecord> records;
@Property("readonly, nonatomic")
private boolean isBlocked;
@Nullable
@Property("readonly, nonatomic")
private String timeZone;
@Property("readonly, nonatomic")
private boolean isVerified;
@Property("readonly, nonatomic")
private List<BotCommand> commands;
@NotNull
@Property("readonly, nonatomic")
private boolean haveExtension;
public User(@NotNull ApiUser wrappedUser, @Nullable ApiFullUser ext) {
super(RECORD_ID, RECORD_FULL_ID, wrappedUser, ext);
}
public User(@NotNull byte[] data) throws IOException {
super(RECORD_ID, RECORD_FULL_ID, data);
}
private User() {
super(RECORD_ID, RECORD_FULL_ID);
}
@NotNull
public Peer peer() {
return new Peer(PeerType.PRIVATE, uid);
}
public int getUid() {
return uid;
}
public long getAccessHash() {
return accessHash;
}
@NotNull
public String getServerName() {
return name;
}
@Nullable
public String getLocalName() {
return localName;
}
@NotNull
public String getName() {
if (localName == null) {
return name;
} else {
return localName;
}
}
@Nullable
public String getNick() {
return username;
}
@Nullable
public String getAbout() {
return about;
}
@Nullable
public Avatar getAvatar() {
return avatar;
}
@NotNull
public Sex getSex() {
return sex;
}
public boolean isHaveExtension() {
return haveExtension;
}
@NotNull
public List<ContactRecord> getRecords() {
return records;
}
public boolean isBot() {
return isBot;
}
public List<BotCommand> getCommands() {
return commands;
}
public boolean isBlocked() {
return isBlocked;
}
@Nullable
public String getTimeZone() {
return timeZone;
}
public boolean isVerified() {
return isVerified;
}
public User editName(@NotNull String name) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
name,
w.getLocalName(),
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editLocalName(@NotNull String localName) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
localName,
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editNick(@Nullable String nick) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
nick,
w.getSex(),
w.getAvatar(),
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editExt(@Nullable ApiMapValue ext) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
w.getNick(),
w.getSex(),
w.getAvatar(),
w.isBot(),
ext);
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User editAvatar(@Nullable ApiAvatar avatar) {
ApiUser w = getWrapped();
ApiUser res = new ApiUser(
w.getId(),
w.getAccessHash(),
w.getName(),
w.getLocalName(),
w.getNick(),
w.getSex(),
avatar,
w.isBot(),
w.getExt());
res.setUnmappedObjects(w.getUnmappedObjects());
return new User(res, getWrappedExt());
}
public User updateExt(@Nullable ApiFullUser ext) {
return new User(getWrapped(), ext);
}
public User editAbout(@Nullable String about) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
about,
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editPreferredLanguages(List<String> preferredLanguages) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
preferredLanguages,
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editTimeZone(String timeZone) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
timeZone,
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editContacts(List<ApiContactRecord> contacts) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
contacts,
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editBotCommands(List<ApiBotCommand> commands) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
commands,
ext.getExt(),
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editFullExt(ApiMapValue extv) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
extv,
ext.isBlocked()
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
public User editBlocked(boolean isBlocked) {
ApiFullUser ext = getWrappedExt();
if (ext != null) {
ApiFullUser upd = new ApiFullUser(
ext.getId(),
ext.getContactInfo(),
ext.getAbout(),
ext.getPreferredLanguages(),
ext.getTimeZone(),
ext.getBotCommands(),
ext.getExt(),
isBlocked
);
return new User(getWrapped(), upd);
} else {
return this;
}
}
@Override
protected void applyWrapped(@NotNull ApiUser wrapped, @Nullable ApiFullUser ext) {
this.uid = wrapped.getId();
this.accessHash = wrapped.getAccessHash();
this.name = wrapped.getName();
this.localName = wrapped.getLocalName();
if (wrapped.getNick() != null && wrapped.getNick().length() > 0) {
this.username = wrapped.getNick();
} else {
this.username = null;
}
if (wrapped.getAvatar() != null) {
this.avatar = new Avatar(wrapped.getAvatar());
}
this.isBot = false;
if (wrapped.isBot() != null) {
this.isBot = wrapped.isBot();
}
this.sex = Sex.UNKNOWN;
if (wrapped.getSex() != null) {
switch (wrapped.getSex()) {
case FEMALE:
this.sex = Sex.FEMALE;
break;
case MALE:
this.sex = Sex.MALE;
break;
}
}
if (wrapped.getExt() != null) {
this.isVerified = true;
for (ApiMapValueItem i : wrapped.getExt().getItems()) {
if ("is_verified".equals(i.getKey())) {
if (i.getValue() instanceof ApiInt32Value) {
this.isVerified = ((ApiInt32Value) i.getValue()).getValue() > 0;
}
}
}
}
// Extension
if (ext != null) {
this.haveExtension = true;
this.records = new ArrayList<>();
this.commands = new ArrayList<BotCommand>();
if (ext.isBlocked() != null) {
this.isBlocked = ext.isBlocked();
} else {
this.isBlocked = false;
}
this.timeZone = ext.getTimeZone();
for (ApiContactRecord record : ext.getContactInfo()) {
if (record.getType() == ApiContactType.PHONE) {
this.records.add(new ContactRecord(ContactRecordType.PHONE, record.getTypeSpec(), "" + record.getLongValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.EMAIL) {
this.records.add(new ContactRecord(ContactRecordType.EMAIL, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.WEB) {
this.records.add(new ContactRecord(ContactRecordType.WEB, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
} else if (record.getType() == ApiContactType.SOCIAL) {
this.records.add(new ContactRecord(ContactRecordType.SOCIAL, record.getTypeSpec(), record.getStringValue(),
record.getTitle(), record.getSubtitle()));
}
}
//Bot commands
for (ApiBotCommand command : ext.getBotCommands()) {
commands.add(new BotCommand(command.getSlashCommand(), command.getDescription(), command.getLocKey()));
}
this.about = ext.getAbout();
} else {
this.isBlocked = false;
this.haveExtension = false;
this.records = new ArrayList<>();
this.commands = new ArrayList<BotCommand>();
this.about = null;
this.timeZone = null;
}
}
@Override
public void parse(BserValues values) throws IOException {
// Is Wrapper Layout
if (values.getBool(8, false)) {
// Parse wrapper layout
super.parse(values);
} else {
// Convert old layout
throw new IOException("Unsupported obsolete format");
}
}
@Override
public void serialize(BserWriter writer) throws IOException {
// Mark as wrapper layout
writer.writeBool(8, true);
// Serialize wrapper layout
super.serialize(writer);
}
@Override
public long getEngineId() {
return getUid();
}
@Override
@NotNull
protected ApiUser createInstance() {
return new ApiUser();
}
@Override
protected ApiFullUser createExtInstance() {
return new ApiFullUser();
}
}
|
ljshj/actor-platform
|
actor-sdk/sdk-core/core/core-shared/src/main/java/im/actor/core/entity/User.java
|
Java
|
mit
| 15,291 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.monitor;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Part of MultiTenantDiagnosticSettings. Specifies the settings for a
* particular log.
*/
public class LogSettings {
/**
* Name of a Diagnostic Log category for a resource type this setting is
* applied to. To obtain the list of Diagnostic Log categories for a
* resource, first perform a GET diagnostic settings operation.
*/
@JsonProperty(value = "category")
private String category;
/**
* a value indicating whether this log is enabled.
*/
@JsonProperty(value = "enabled", required = true)
private boolean enabled;
/**
* the retention policy for this log.
*/
@JsonProperty(value = "retentionPolicy")
private RetentionPolicy retentionPolicy;
/**
* Get the category value.
*
* @return the category value
*/
public String category() {
return this.category;
}
/**
* Set the category value.
*
* @param category the category value to set
* @return the LogSettings object itself.
*/
public LogSettings withCategory(String category) {
this.category = category;
return this;
}
/**
* Get the enabled value.
*
* @return the enabled value
*/
public boolean enabled() {
return this.enabled;
}
/**
* Set the enabled value.
*
* @param enabled the enabled value to set
* @return the LogSettings object itself.
*/
public LogSettings withEnabled(boolean enabled) {
this.enabled = enabled;
return this;
}
/**
* Get the retentionPolicy value.
*
* @return the retentionPolicy value
*/
public RetentionPolicy retentionPolicy() {
return this.retentionPolicy;
}
/**
* Set the retentionPolicy value.
*
* @param retentionPolicy the retentionPolicy value to set
* @return the LogSettings object itself.
*/
public LogSettings withRetentionPolicy(RetentionPolicy retentionPolicy) {
this.retentionPolicy = retentionPolicy;
return this;
}
}
|
martinsawicki/azure-sdk-for-java
|
azure-mgmt-monitor/src/main/java/com/microsoft/azure/management/monitor/LogSettings.java
|
Java
|
mit
| 2,421 |
package com.xeiam.xchange.lakebtc.marketdata;
import static org.fest.assertions.api.Assertions.assertThat;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCOrderBook;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTicker;
import com.xeiam.xchange.lakebtc.dto.marketdata.LakeBTCTickers;
public class LakeBTCMarketDataJsonTest {
@Test
public void testDeserializeTicker() throws IOException {
// Read in the JSON from the example resources
InputStream is = LakeBTCMarketDataJsonTest.class.getResourceAsStream("/marketdata/example-ticker-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
LakeBTCTickers tickers = mapper.readValue(is, LakeBTCTickers.class);
LakeBTCTicker cnyTicker = tickers.getCny();
assertThat(cnyTicker.getAsk()).isEqualTo("3524.07");
assertThat(cnyTicker.getBid()).isEqualTo("3517.13");
assertThat(cnyTicker.getLast()).isEqualTo("3524.07");
assertThat(cnyTicker.getHigh()).isEqualTo("3584.97");
assertThat(cnyTicker.getLow()).isEqualTo("3480.07");
assertThat(cnyTicker.getVolume()).isEqualTo("5964.7677");
LakeBTCTicker usdTicker = tickers.getUsd();
assertThat(usdTicker.getAsk()).isEqualTo("564.63");
assertThat(usdTicker.getBid()).isEqualTo("564.63");
assertThat(usdTicker.getLast()).isEqualTo("564.4");
assertThat(usdTicker.getHigh()).isEqualTo("573.83");
assertThat(usdTicker.getLow()).isEqualTo("557.7");
assertThat(usdTicker.getVolume()).isEqualTo("3521.2782");
}
@Test
public void testDeserializeOrderBook() throws IOException {
// Read in the JSON from the example resources
InputStream is = LakeBTCMarketDataJsonTest.class.getResourceAsStream("/marketdata/example-orderbook-data.json");
// Use Jackson to parse it
ObjectMapper mapper = new ObjectMapper();
LakeBTCOrderBook orderBook = mapper.readValue(is, LakeBTCOrderBook.class);
BigDecimal[][] asks = orderBook.getAsks();
assertThat(asks).hasSize(3);
assertThat(asks[0][0]).isEqualTo("564.87");
assertThat(asks[0][1]).isEqualTo("22.371");
BigDecimal[][] bids = orderBook.getBids();
assertThat(bids).hasSize(3);
assertThat(bids[2][0]).isEqualTo("558.08");
assertThat(bids[2][1]).isEqualTo("0.9878");
}
}
|
coingecko/XChange
|
xchange-lakebtc/src/test/java/com/xeiam/xchange/lakebtc/marketdata/LakeBTCMarketDataJsonTest.java
|
Java
|
mit
| 2,443 |
package org.magcruise.gaming.executor.api.message;
import org.magcruise.gaming.lang.Message;
import org.magcruise.gaming.lang.SConstructor;
public interface RequestToGameExecutor extends Message {
@Override
public SConstructor<? extends RequestToGameExecutor> toConstructor(ToExpressionStyle style);
@Override
public default SConstructor<? extends RequestToGameExecutor> toConstructor() {
return toConstructor(ToExpressionStyle.DEFAULT);
}
}
|
MAGCruise/magcruise-core
|
src/main/java/org/magcruise/gaming/executor/api/message/RequestToGameExecutor.java
|
Java
|
mit
| 454 |
/*
* 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.
*/
package com.amazonaws.auth;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Simple implementation AWSCredentials that reads in AWS access keys from a
* properties file. The AWS access key is expected to be in the "accessKey"
* property and the AWS secret key id is expected to be in the "secretKey"
* property.
*/
public class PropertiesCredentials implements AWSCredentials {
private final String accessKey;
private final String secretAccessKey;
/**
* Reads the specified file as a Java properties file and extracts the
* AWS access key from the "accessKey" property and AWS secret access
* key from the "secretKey" property. If the specified file doesn't
* contain the AWS access keys an IOException will be thrown.
*
* @param file
* The file from which to read the AWS credentials
* properties.
*
* @throws FileNotFoundException
* If the specified file isn't found.
* @throws IOException
* If any problems are encountered reading the AWS access
* keys from the specified file.
* @throws IllegalArgumentException
* If the specified properties file does not contain the
* required keys.
*/
public PropertiesCredentials(File file) throws FileNotFoundException, IOException, IllegalArgumentException {
if (!file.exists()) {
throw new FileNotFoundException("File doesn't exist: "
+ file.getAbsolutePath());
}
FileInputStream stream = new FileInputStream(file);
try {
Properties accountProperties = new Properties();
accountProperties.load(stream);
if (accountProperties.getProperty("accessKey") == null ||
accountProperties.getProperty("secretKey") == null) {
throw new IllegalArgumentException(
"The specified file (" + file.getAbsolutePath()
+ ") doesn't contain the expected properties 'accessKey' "
+ "and 'secretKey'."
);
}
accessKey = accountProperties.getProperty("accessKey");
secretAccessKey = accountProperties.getProperty("secretKey");
} finally {
try {
stream.close();
} catch (IOException e) {
}
}
}
/**
* Reads the specified input stream as a stream of Java properties file
* content and extracts the AWS access key ID and secret access key from the
* properties.
*
* @param inputStream
* The input stream containing the AWS credential properties.
*
* @throws IOException
* If any problems occur while reading from the input stream.
*/
public PropertiesCredentials(InputStream inputStream) throws IOException {
Properties accountProperties = new Properties();
try {
accountProperties.load(inputStream);
} finally {
try {inputStream.close();} catch (Exception e) {}
}
if (accountProperties.getProperty("accessKey") == null ||
accountProperties.getProperty("secretKey") == null) {
throw new IllegalArgumentException("The specified properties data " +
"doesn't contain the expected properties 'accessKey' and 'secretKey'.");
}
accessKey = accountProperties.getProperty("accessKey");
secretAccessKey = accountProperties.getProperty("secretKey");
}
/* (non-Javadoc)
* @see com.amazonaws.auth.AWSCredentials#getAWSAccessKeyId()
*/
public String getAWSAccessKeyId() {
return accessKey;
}
/* (non-Javadoc)
* @see com.amazonaws.auth.AWSCredentials#getAWSSecretKey()
*/
public String getAWSSecretKey() {
return secretAccessKey;
}
}
|
loremipsumdolor/CastFast
|
src/com/amazonaws/auth/PropertiesCredentials.java
|
Java
|
mit
| 4,679 |
/*
* 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.
*/
package com.amazonaws.services.s3.transfer;
import java.io.File;
import com.amazonaws.services.s3.model.ObjectMetadata;
/**
* This is the callback interface which is used by TransferManager.uploadDirectory and
* TransferManager.uploadFileList. The callback is invoked for each file that is uploaded by
* <code>TransferManager</code> and given an opportunity to specify the metadata for each file.
*/
public interface ObjectMetadataProvider {
/*
* This method is called for every file that is uploaded by <code>TransferManager</code>
* and gives an opportunity to specify the metadata for the file.
*
* @param file
* The file being uploaded.
*
* @param metadata
* The default metadata for the file. You can modify this object to specify
* your own metadata.
*/
public void provideObjectMetadata(final File file, final ObjectMetadata metadata);
}
|
loremipsumdolor/CastFast
|
src/com/amazonaws/services/s3/transfer/ObjectMetadataProvider.java
|
Java
|
mit
| 1,511 |
package org.luban.common.plugin;
import org.luban.common.network.URL;
/**
* 服务插件接口
*
* @author hexiaofeng
* @version 1.0.0
* @since 12-12-12 下午8:47
*/
public interface ServicePlugin {
/**
* 返回类型
*
* @return
*/
String getType();
/**
* 设置URL
*
* @param url
*/
void setUrl(URL url);
}
|
krisjin/common-base
|
luban-common/src/main/java/org/luban/common/plugin/ServicePlugin.java
|
Java
|
mit
| 377 |
package nxt.http;
import nxt.Nxt;
import nxt.Transaction;
import nxt.util.Convert;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_TRANSACTION;
import static nxt.http.JSONResponses.MISSING_TRANSACTION;
import static nxt.http.JSONResponses.UNKNOWN_TRANSACTION;
public final class GetTransaction extends APIServlet.APIRequestHandler {
static final GetTransaction instance = new GetTransaction();
private GetTransaction() {
super("transaction", "hash");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) {
String transactionIdString = Convert.emptyToNull(req.getParameter("transaction"));
String transactionHash = Convert.emptyToNull(req.getParameter("hash"));
if (transactionIdString == null && transactionHash == null) {
return MISSING_TRANSACTION;
}
Long transactionId = null;
Transaction transaction;
try {
if (transactionIdString != null) {
transactionId = Convert.parseUnsignedLong(transactionIdString);
transaction = Nxt.getBlockchain().getTransaction(transactionId);
} else {
transaction = Nxt.getBlockchain().getTransaction(transactionHash);
if (transaction == null) {
return UNKNOWN_TRANSACTION;
}
}
} catch (RuntimeException e) {
return INCORRECT_TRANSACTION;
}
JSONObject response;
if (transaction == null) {
transaction = Nxt.getTransactionProcessor().getUnconfirmedTransaction(transactionId);
if (transaction == null) {
return UNKNOWN_TRANSACTION;
}
response = transaction.getJSONObject();
} else {
response = transaction.getJSONObject();
response.put("block", Convert.toUnsignedLong(transaction.getBlockId()));
response.put("confirmations", Nxt.getBlockchain().getLastBlock().getHeight() - transaction.getHeight());
response.put("blockTimestamp", transaction.getBlockTimestamp());
}
response.put("sender", Convert.toUnsignedLong(transaction.getSenderId()));
response.put("hash", transaction.getHash());
return response;
}
}
|
aspnmy/NasCoin
|
src/java/nxt/http/GetTransaction.java
|
Java
|
mit
| 2,418 |
package com.github.scribejava.apis.examples;
import com.github.scribejava.apis.EtsyApi;
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.model.OAuthRequest;
import com.github.scribejava.core.model.Response;
import com.github.scribejava.core.model.Verb;
import com.github.scribejava.core.oauth.OAuth10aService;
import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.ExecutionException;
public class EtsyExample {
private static final String PROTECTED_RESOURCE_URL = "https://openapi.etsy.com/v2/users/__SELF__";
private EtsyExample() {
}
@SuppressWarnings("PMD.SystemPrintln")
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
// Replace with your api and secret key
final OAuth10aService service = new ServiceBuilder("your api key")
.apiSecret("your secret key")
.build(EtsyApi.instance());
final Scanner in = new Scanner(System.in);
System.out.println("=== Etsy's OAuth Workflow ===");
System.out.println();
// Obtain the Request Token
System.out.println("Fetching the Request Token...");
final OAuth1RequestToken requestToken = service.getRequestToken();
System.out.println("Got the Request Token!");
System.out.println();
System.out.println("Now go and authorize ScribeJava here:");
System.out.println(service.getAuthorizationUrl(requestToken));
System.out.println("And paste the verifier here");
System.out.print(">>");
final String oauthVerifier = in.nextLine();
System.out.println();
// Trade the Request Token and Verifier for the Access Token
System.out.println("Trading the Request Token for an Access Token...");
final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, oauthVerifier);
System.out.println("Got the Access Token!");
System.out.println("(The raw response looks like this: " + accessToken.getRawResponse() + "')");
System.out.println();
// Now let's go and ask for a protected resource!
System.out.println("Now we're going to access a protected resource...");
final OAuthRequest request = new OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL);
service.signRequest(accessToken, request);
final Response response = service.execute(request);
System.out.println("Got it! Lets see what we found...");
System.out.println();
System.out.println(response.getBody());
System.out.println();
System.out.println("That's it man! Go and build something awesome with ScribeJava! :)");
}
}
|
fernandezpablo85/scribe-java
|
scribejava-apis/src/test/java/com/github/scribejava/apis/examples/EtsyExample.java
|
Java
|
mit
| 2,876 |
public class A extends B {
public A() {}
}
|
gregwym/joos-compiler-java
|
testcases/a2/Je_4_ClassExtendsCyclicClass/A.java
|
Java
|
mit
| 47 |
package easyupload.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
@Entity
public class FileUpload {
public FileUpload(String filename, byte[] file, String mimeType) {
this.file = file;
this.filename = filename;
this.mimeType = mimeType;
}
public FileUpload() {
// Default Constructor
}
@Id
private String filename;
@Lob
private byte[] file;
private String mimeType;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public byte[] getFile() {
return file;
}
public void setFile(byte[] file) {
this.file = file;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
}
|
vberbenetz/EasyUpload
|
Backend/src/main/java/easyupload/entity/FileUpload.java
|
Java
|
mit
| 936 |
/*****************************************************************************
* This file is part of the Prolog Development Tool (PDT)
*
* Author: Lukas Degener (among others)
* WWW: http://sewiki.iai.uni-bonn.de/research/pdt/start
* Mail: pdt@lists.iai.uni-bonn.de
* Copyright (C): 2004-2012, CS Dept. III, University of Bonn
*
* All rights reserved. This program is made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
****************************************************************************/
package org.cs3.prolog.connector.cterm;
import org.cs3.prolog.connector.internal.cterm.parser.ASTNode;
/**
* Represents a Prolog string.
*/
public class CString extends CTerm {
public CString(ASTNode node) {
super(node);
}
}
|
TeamSPoon/logicmoo_base
|
prolog/logicmoo/pdt_server/prolog.connector/src/org/cs3/prolog/connector/cterm/CString.java
|
Java
|
mit
| 870 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.