hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
3d18f624f9e0d2e582e92d0c518925cdff018211 | 3,452 | package org.firstglobal.FgCommon;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.Gamepad;
import com.qualcomm.robotcore.hardware.Servo;
/**
* Operation to assist with operating a servo from a gamepad button
*/
public class GamePadServo extends OpModeComponent {
// use the Y and A buttons for up and down and the X and B buttons for left and right
public static enum Control {
Y_A,
X_B
}
private Control currentControl;
// amount to change the servo position by
private double servoDelta = 0.01;
private ServoComponent servoComponent;
private CRServo crServo;
private Gamepad gamepad;
/**
* Constructor for operation
* Telemetry enabled by default.
* @param opMode
* @param gamepad Gamepad
* @param servo Servo
* @param control use the Y and A buttons for up and down and the X and B buttons for left and right
*/
public GamePadServo(FGOpMode opMode, Gamepad gamepad, Servo servo, Control control, double initialPosition) {
this(opMode,gamepad, servo,control,initialPosition,false);
}
/**
* Constructor for operation
* @param opMode
* @param gamepad Gamepad
* @param servo Servo
* @param control use the Y and A buttons for up and down and the X and B buttons for left and right
* @param initialPosition must set the initial position of the servo before working with it
* @param reverseOrientation true if the servo is install in the reverse orientation
*/
public GamePadServo(FGOpMode opMode, Gamepad gamepad, Servo servo, Control control, double initialPosition,boolean reverseOrientation) {
super(opMode);
this.servoComponent = new ServoComponent(opMode, servo, initialPosition , reverseOrientation);
this.gamepad = gamepad;
this.currentControl = control;
}
/**
* Constructor for operation
* Telemetry enabled by default.
* @param opMode
* @param gamepad Gamepad
* @param crServo CRServo
* @param control use the Y and A buttons for up and down and the X and B buttons for left and right
*/
public GamePadServo(FGOpMode opMode, Gamepad gamepad, CRServo crServo, Control control ) {
super(opMode);
this.crServo = crServo;
this.gamepad = gamepad;
this.currentControl = control;
}
/**
* Update motors with latest gamepad state
*/
public void update() {
boolean rightVal = currentControl == Control.Y_A ? gamepad.y : gamepad.b;
boolean leftVal = currentControl == Control.Y_A ? gamepad.a : gamepad.x;
getOpMode().telemetry.addData("rightVal", rightVal); ;
getOpMode().telemetry.addData("leftVal", leftVal);
if (servoComponent != null) {
// update the position of the servo
if (rightVal) {
servoComponent.incrementServoTargetPosition(servoDelta);
}
if (leftVal) {
servoComponent.incrementServoTargetPosition(-servoDelta);
}
}
else {
// update the position of the servo
if (rightVal) {
crServo.setPower(1);
}
else if (leftVal) {
crServo.setPower(-1);
}
else {
crServo.setPower(0);
}
}
}
}
| 30.017391 | 140 | 0.631518 |
70d4f997b9538258ee03b634ce90143a9ea849b2 | 652 | package stream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author zhangyupeng
* @date 2018/8/26
*/
public class StreamDemo {
/**
* 两个数字列表,返回所有数对
*/
public static void main(String[] args) {
List<Integer> num1 = Arrays.asList(1, 2, 3);
List<Integer> num2 = Arrays.asList(3, 4);
List<int[]> listArray = num1.stream()
.flatMap(i -> num2.stream().map(j -> new int[]{i, j}))
.collect(Collectors.toList());
listArray.forEach(ints -> System.out.print(Arrays.toString(ints)));
}
} | 26.08 | 90 | 0.555215 |
18d55451da32a6bae3dcc33e69ba6e661de8a1bc | 2,852 | /*
* This file is part of fabric-loom, licensed under the MIT License (MIT).
*
* Copyright (c) 2019-2021 FabricMC
*
* 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 net.fabricmc.loom.decompilers.fernflower;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import org.jetbrains.java.decompiler.main.Fernflower;
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences;
import org.jetbrains.java.decompiler.main.extern.IResultSaver;
import net.fabricmc.fernflower.api.IFabricJavadocProvider;
import net.fabricmc.loom.api.decompilers.DecompilationMetadata;
import net.fabricmc.loom.api.decompilers.LoomDecompiler;
public final class FabricFernFlowerDecompiler implements LoomDecompiler {
@Override
public void decompile(Path compiledJar, Path sourcesDestination, Path linemapDestination, DecompilationMetadata metaData) {
final Map<String, Object> options = new HashMap<>(
Map.of(
IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES, "1",
IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1",
IFernflowerPreferences.REMOVE_SYNTHETIC, "1",
IFernflowerPreferences.LOG_LEVEL, "trace",
IFernflowerPreferences.THREADS, String.valueOf(metaData.numberOfThreads()),
IFernflowerPreferences.INDENT_STRING, "\t",
IFabricJavadocProvider.PROPERTY_NAME, new TinyJavadocProvider(metaData.javaDocs().toFile())
)
);
options.putAll(metaData.options());
IResultSaver saver = new ThreadSafeResultSaver(sourcesDestination::toFile, linemapDestination::toFile);
Fernflower ff = new Fernflower(FernFlowerUtils::getBytecode, saver, options, new FernflowerLogger(metaData.logger()));
for (Path library : metaData.libraries()) {
ff.addLibrary(library.toFile());
}
ff.addSource(compiledJar.toFile());
ff.decompileContext();
}
}
| 42.567164 | 124 | 0.778401 |
a8822ae94efdf12ca71888aaa31a4a889eb05f32 | 2,893 | package nanoj.pumpControl.java.sequentialProtocol.tabs;
import nanoj.pumpControl.java.sequentialProtocol.GUI;
import javax.swing.*;
import java.awt.*;
class PumpConnectionsLayout extends GroupLayout {
PumpConnectionsLayout(Container host) {
super(host);
PumpConnections panel = (PumpConnections) host;
setAutoCreateGaps(true);
setAutoCreateContainerGaps(true);
setVerticalGroup(
createSequentialGroup()
.addGroup(createParallelGroup()
.addComponent(panel.pumpListLabel)
.addComponent(panel.availablePumpsList, GroupLayout.PREFERRED_SIZE, GUI.rowHeight, GroupLayout.PREFERRED_SIZE)
)
.addGroup(createParallelGroup()
.addComponent(panel.connectLabel)
.addComponent(panel.portsList, GroupLayout.PREFERRED_SIZE, GUI.rowHeight, GroupLayout.PREFERRED_SIZE)
.addComponent(panel.connectButton)
.addComponent(panel.disconnectButton)
)
.addGroup(createParallelGroup().addComponent(panel.connectedPumpsLabel))
.addGroup(createParallelGroup().addComponent(panel.connectedPumpsListPane))
.addGroup(createParallelGroup().addComponent(panel.version))
);
setHorizontalGroup(
createParallelGroup()
.addGroup(createSequentialGroup()
.addGroup(createParallelGroup()
.addComponent(panel.pumpListLabel, GroupLayout.Alignment.TRAILING)
.addComponent(panel.connectLabel, GroupLayout.Alignment.TRAILING)
)
.addGroup(createParallelGroup()
.addComponent(panel.availablePumpsList, GroupLayout.PREFERRED_SIZE, GUI.sizeSecondColumn, GroupLayout.PREFERRED_SIZE)
.addComponent(panel.portsList, GroupLayout.PREFERRED_SIZE, GUI.sizeSecondColumn, GroupLayout.PREFERRED_SIZE)
)
.addGroup(createSequentialGroup()
.addComponent(panel.connectButton)
.addComponent(panel.disconnectButton)
)
)
.addGroup(createParallelGroup().addComponent(panel.connectedPumpsLabel))
.addGroup(createParallelGroup().addComponent(panel.connectedPumpsListPane))
.addGroup(createParallelGroup().addComponent(panel.version))
);
}
}
| 52.6 | 157 | 0.54822 |
586c0c97aa6894d8e0ba4efad4ff018d6a738c21 | 3,987 | import com.intellij.diff.DiffContentFactory;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.DiffManager;
import com.intellij.diff.DiffRequestFactory;
import com.intellij.diff.actions.BlankDiffWindowUtil;
import com.intellij.diff.actions.impl.MutableDiffRequestChain;
import com.intellij.diff.chains.DiffRequestChain;
import com.intellij.diff.contents.DiffContent;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/*
* Copied implementation from Jetbrains BaseShowDiffAction
*/
public abstract class BaseShowDiffAction extends DumbAwareAction {
BaseShowDiffAction() {
setEnabledInModalContext(true);
}
@Override
public void update(@NotNull AnActionEvent e) {
Presentation presentation = e.getPresentation();
boolean canShow = isAvailable(e);
presentation.setEnabled(canShow);
if (ActionPlaces.isPopupPlace(e.getPlace())) {
presentation.setVisible(canShow);
}
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
Project project = e.getProject();
DiffRequestChain chain = getDiffRequestChain(e);
if (chain == null) return;
DiffManager.getInstance().showDiff(project, chain, DiffDialogHints.DEFAULT);
}
protected abstract boolean isAvailable(@NotNull AnActionEvent e);
protected static boolean hasContent(@NotNull VirtualFile file) {
return !DiffUtil.isFileWithoutContent(file);
}
@Nullable
protected abstract DiffRequestChain getDiffRequestChain(@NotNull AnActionEvent e);
@NotNull
protected static MutableDiffRequestChain createMutableChainFromFiles(@Nullable Project project,
@NotNull VirtualFile file1,
@NotNull VirtualFile file2) {
return createMutableChainFromFiles(project, file1, file2, null);
}
@NotNull
protected static MutableDiffRequestChain createMutableChainFromFiles(@Nullable Project project,
@NotNull VirtualFile file1,
@NotNull VirtualFile file2,
@Nullable VirtualFile baseFile) {
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DiffRequestFactory requestFactory = DiffRequestFactory.getInstance();
DiffContent content1 = contentFactory.create(project, file1);
DiffContent content2 = contentFactory.create(project, file2);
DiffContent baseContent = baseFile != null ? contentFactory.create(project, baseFile) : null;
MutableDiffRequestChain chain;
if (content1 instanceof DocumentContent && content2 instanceof DocumentContent &&
(baseContent == null || baseContent instanceof DocumentContent)) {
chain = BlankDiffWindowUtil.createBlankDiffRequestChain((DocumentContent)content1,
(DocumentContent)content2,
(DocumentContent)baseContent);
}
else {
chain = new MutableDiffRequestChain(content1, baseContent, content2);
}
if (baseFile != null) {
chain.setWindowTitle(requestFactory.getTitle(baseFile));
}
else {
chain.setWindowTitle(requestFactory.getTitle(file1, file2));
}
return chain;
}
}
| 41.103093 | 106 | 0.666416 |
93c0b85af78ae173fd3d68a5240bbe1a59592c06 | 2,247 | package com.edwinmindcraft.originsexpansion.api.dfu;
import com.mojang.datafixers.util.Pair;
import com.mojang.serialization.*;
import java.util.function.Function;
/**
* If you are wondering what this is, for the sake of your sanity please don't.
* This just allows codecs to be flattened.
* @param <E> The serialized type
* @param <A> The type providing the codec.
*/
public class InlineCodec<E, A> implements Codec<E> {
private final String key;
private final String value = "value";
private final Codec<A> type;
private final Function<? super E, ? extends A> from;
private final Function<? super A, ? extends Codec<? extends E>> child;
public InlineCodec(String key, Codec<A> type, final Function<? super E, ? extends A> from, final Function<? super A, ? extends Codec<? extends E>> child) {
this.key = key;
this.type = type;
this.from = from;
this.child = child;
}
@Override
public <T> DataResult<Pair<E, T>> decode(DynamicOps<T> ops, T input) {
DataResult<Pair<A, T>> key = ops.get(input, this.key).flatMap(x -> this.type.decode(ops, x));
DataResult<? extends Codec<? extends E>> codec = key.map(Pair::getFirst).map(this.child);
if (codec.error().isPresent())
return DataResult.error(codec.error().get().message(), Pair.of(null, input));
Codec<E> codecAccess = codec.result().map(x -> (Codec<E>) x).get();
DataResult<Pair<E, T>> target = ops.get(input, this.value).flatMap(x -> codecAccess.decode(ops, x));
if (target.error().isPresent() && ops instanceof InlineOps && !ops.compressMaps())
target = codecAccess.decode(ops, input);
return target;
}
@Override
public <T> DataResult<T> encode(E input, DynamicOps<T> ops, T prefix) {
A res = this.from.apply(input);
Codec<E> apply = (Codec<E>) this.child.apply(res);
RecordBuilder<T> builder = ops.mapBuilder();
builder.add(this.key, this.type.encode(res, ops, prefix));
if (ops instanceof InlineOps && !ops.compressMaps()) {
DataResult<T> result = builder.build(prefix).flatMap(x -> apply.encode(input, ops, x));
if (result.result().isPresent())
return result;
}
builder.add(this.key, this.type.encode(res, ops, prefix));
builder.add(this.value, apply.encode(input, ops, prefix));
return builder.build(prefix);
}
} | 39.421053 | 156 | 0.693369 |
3d969d8dfdc1f68ba63b2cccda413b6298a5e840 | 1,435 | /*
package org.firstinspires.ftc.teamcode.OldOpmodes;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
public class VideoStream extends Activity {
public void runOpMode(){}
private static final int CAMERA_REQUEST = 1888;
View relativeLayout;
public VideoStream(View relativeLayout){
this.relativeLayout = relativeLayout;
}
public void stream(){
relativeLayout.post(new Runnable() {
public void run() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
Drawable background = new BitmapDrawable(getResources(), photo);
relativeLayout.setBackground(background);
}
}
Runnable streamVideo = new Runnable() {
public void run() {
stream();
}
};
public void start() {
Thread videoStream = new Thread(streamVideo);
videoStream.setDaemon(true);
videoStream.start();
}
}*/
| 28.137255 | 99 | 0.655052 |
9bdb0a66a3c03ec6aa7a4823cf53eeff0aebe9dc | 10,514 | /**
*/
package de.fhdo.ddmm.service.impl;
import de.fhdo.ddmm.service.*;
import java.util.Map;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class ServiceFactoryImpl extends EFactoryImpl implements ServiceFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static ServiceFactory init() {
try {
ServiceFactory theServiceFactory = (ServiceFactory)EPackage.Registry.INSTANCE.getEFactory(ServicePackage.eNS_URI);
if (theServiceFactory != null) {
return theServiceFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new ServiceFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ServiceFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case ServicePackage.SERVICE_MODEL: return createServiceModel();
case ServicePackage.IMPORT: return createImport();
case ServicePackage.MICROSERVICE: return createMicroservice();
case ServicePackage.INTERFACE: return createInterface();
case ServicePackage.OPERATION: return createOperation();
case ServicePackage.REFERRED_OPERATION: return createReferredOperation();
case ServicePackage.PARAMETER: return createParameter();
case ServicePackage.POSSIBLY_IMPORTED_MICROSERVICE: return createPossiblyImportedMicroservice();
case ServicePackage.POSSIBLY_IMPORTED_INTERFACE: return createPossiblyImportedInterface();
case ServicePackage.POSSIBLY_IMPORTED_OPERATION: return createPossiblyImportedOperation();
case ServicePackage.IMPORTED_TYPE: return createImportedType();
case ServicePackage.IMPORTED_PROTOCOL_AND_DATA_FORMAT: return createImportedProtocolAndDataFormat();
case ServicePackage.PROTOCOL_SPECIFICATION: return createProtocolSpecification();
case ServicePackage.ENDPOINT: return createEndpoint();
case ServicePackage.IMPORTED_SERVICE_ASPECT: return createImportedServiceAspect();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object createFromString(EDataType eDataType, String initialValue) {
switch (eDataType.getClassifierID()) {
case ServicePackage.IMPORT_TYPE:
return createImportTypeFromString(eDataType, initialValue);
case ServicePackage.MICROSERVICE_TYPE:
return createMicroserviceTypeFromString(eDataType, initialValue);
case ServicePackage.VISIBILITY:
return createVisibilityFromString(eDataType, initialValue);
case ServicePackage.MICROSERVICE_IMPORT_MAP:
return createMicroserviceImportMapFromString(eDataType, initialValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String convertToString(EDataType eDataType, Object instanceValue) {
switch (eDataType.getClassifierID()) {
case ServicePackage.IMPORT_TYPE:
return convertImportTypeToString(eDataType, instanceValue);
case ServicePackage.MICROSERVICE_TYPE:
return convertMicroserviceTypeToString(eDataType, instanceValue);
case ServicePackage.VISIBILITY:
return convertVisibilityToString(eDataType, instanceValue);
case ServicePackage.MICROSERVICE_IMPORT_MAP:
return convertMicroserviceImportMapToString(eDataType, instanceValue);
default:
throw new IllegalArgumentException("The datatype '" + eDataType.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ServiceModel createServiceModel() {
ServiceModelImpl serviceModel = new ServiceModelImpl();
return serviceModel;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Import createImport() {
ImportImpl import_ = new ImportImpl();
return import_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Microservice createMicroservice() {
MicroserviceImpl microservice = new MicroserviceImpl();
return microservice;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Interface createInterface() {
InterfaceImpl interface_ = new InterfaceImpl();
return interface_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Operation createOperation() {
OperationImpl operation = new OperationImpl();
return operation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ReferredOperation createReferredOperation() {
ReferredOperationImpl referredOperation = new ReferredOperationImpl();
return referredOperation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Parameter createParameter() {
ParameterImpl parameter = new ParameterImpl();
return parameter;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PossiblyImportedMicroservice createPossiblyImportedMicroservice() {
PossiblyImportedMicroserviceImpl possiblyImportedMicroservice = new PossiblyImportedMicroserviceImpl();
return possiblyImportedMicroservice;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PossiblyImportedInterface createPossiblyImportedInterface() {
PossiblyImportedInterfaceImpl possiblyImportedInterface = new PossiblyImportedInterfaceImpl();
return possiblyImportedInterface;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PossiblyImportedOperation createPossiblyImportedOperation() {
PossiblyImportedOperationImpl possiblyImportedOperation = new PossiblyImportedOperationImpl();
return possiblyImportedOperation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImportedType createImportedType() {
ImportedTypeImpl importedType = new ImportedTypeImpl();
return importedType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImportedProtocolAndDataFormat createImportedProtocolAndDataFormat() {
ImportedProtocolAndDataFormatImpl importedProtocolAndDataFormat = new ImportedProtocolAndDataFormatImpl();
return importedProtocolAndDataFormat;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ProtocolSpecification createProtocolSpecification() {
ProtocolSpecificationImpl protocolSpecification = new ProtocolSpecificationImpl();
return protocolSpecification;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Endpoint createEndpoint() {
EndpointImpl endpoint = new EndpointImpl();
return endpoint;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImportedServiceAspect createImportedServiceAspect() {
ImportedServiceAspectImpl importedServiceAspect = new ImportedServiceAspectImpl();
return importedServiceAspect;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ImportType createImportTypeFromString(EDataType eDataType, String initialValue) {
ImportType result = ImportType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertImportTypeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MicroserviceType createMicroserviceTypeFromString(EDataType eDataType, String initialValue) {
MicroserviceType result = MicroserviceType.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertMicroserviceTypeToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Visibility createVisibilityFromString(EDataType eDataType, String initialValue) {
Visibility result = Visibility.get(initialValue);
if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '" + eDataType.getName() + "'");
return result;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertVisibilityToString(EDataType eDataType, Object instanceValue) {
return instanceValue == null ? null : instanceValue.toString();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
public Map<Microservice, Import> createMicroserviceImportMapFromString(EDataType eDataType, String initialValue) {
return (Map<Microservice, Import>)super.createFromString(initialValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String convertMicroserviceImportMapToString(EDataType eDataType, Object instanceValue) {
return super.convertToString(instanceValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ServicePackage getServicePackage() {
return (ServicePackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static ServicePackage getPackage() {
return ServicePackage.eINSTANCE;
}
} //ServiceFactoryImpl
| 28.112299 | 152 | 0.701541 |
f6e29751490368e85f1aa20419e8f1648c77bc25 | 2,837 | //package io.github.icodegarden.beecomb.master.controller;
//
//import java.util.List;
//
//import javax.validation.constraints.Max;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.validation.annotation.Validated;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.PathVariable;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import com.github.pagehelper.Page;
//
//import io.github.icodegarden.beecomb.master.pojo.query.JobRecoveryRecordQuery;
//import io.github.icodegarden.beecomb.master.pojo.query.JobRecoveryRecordWith;
//import io.github.icodegarden.beecomb.master.pojo.query.JobRecoveryRecordWith.JobMain;
//import io.github.icodegarden.beecomb.master.pojo.view.JobRecoveryRecordVO;
//import io.github.icodegarden.beecomb.master.security.SecurityUtils;
//import io.github.icodegarden.beecomb.master.service.JobRecoveryRecordService;
//import io.github.icodegarden.commons.springboot.web.util.WebUtils;
//
///**
// *
// * @author Fangfang.Xu
// *
// */
//@Validated
//@RestController
//public class JobRecoveryRecordController {
//
// @Autowired
// private JobRecoveryRecordService jobRecoveryRecordService;
//
// @GetMapping("api/v1/jobRecoveryRecords")
// public ResponseEntity<List<JobRecoveryRecordVO>> pageJobRecoveryRecords(
// @RequestParam(required = false) Boolean success,
// @RequestParam(defaultValue = "0") @Max(WebUtils.MAX_TOTAL_PAGES) int page,
// @RequestParam(defaultValue = "10") @Max(WebUtils.MAX_PAGE_SIZE) int size) {
// String username = SecurityUtils.getUsername();
//
// JobRecoveryRecordQuery query = JobRecoveryRecordQuery.builder().success(success).jobCreatedBy(username)
// .with(JobRecoveryRecordWith.builder().jobMain(JobMain.builder().build()).build()).page(page).size(size)
// .sort("order by a.created_at desc").build();
//
// Page<JobRecoveryRecordVO> p = jobRecoveryRecordService.page(query);
// return new ResponseEntity<List<JobRecoveryRecordVO>>(p.getResult(),
// WebUtils.pageHeaders(p.getPages(), p.getTotal()), HttpStatus.OK);
// }
//
// @GetMapping("api/v1/jobRecoveryRecords/jobs/{jobId}")
// public ResponseEntity<JobRecoveryRecordVO> findJobRecoveryRecord(@PathVariable Long jobId) {
// JobRecoveryRecordVO vo = jobRecoveryRecordService.findOne(jobId, JobRecoveryRecordWith.WITH_MOST);
//
// if (vo.getJob() != null) {
// /**
// * 校验归属权
// */
// if (!SecurityUtils.getUsername().equals(vo.getJob().getCreatedBy())) {
// return (ResponseEntity) ResponseEntity.status(404).body("Not Found, Ownership");
// }
// }
//
// return ResponseEntity.ok(vo);
// }
//}
| 40.528571 | 109 | 0.759605 |
097c35ca05367f3e7f6ff97f7054546941d1f3df | 783 | package org.loed.framework.common.query;
import lombok.Data;
/**
* @author Thomason
* @version 1.0
* @since 2020/10/31 16:44
*/
@Data
public class PageRequest {
private int pageNo = 1;
private int pageSize = 10;
private boolean paging = true;
private boolean counting = true;
public static PageRequest of(int pageNumber, int pageSize) {
PageRequest pageRequest = new PageRequest();
pageRequest.setPageNo(pageNumber);
pageRequest.setPageSize(pageSize);
return pageRequest;
}
public static PageRequest of(int pageNumber) {
PageRequest pageRequest = new PageRequest();
pageRequest.setPageNo(pageNumber);
return pageRequest;
}
public long getOffset() {
return (this.pageNo - 1) * pageSize;
}
public int getLimit() {
return this.getPageSize();
}
}
| 20.605263 | 61 | 0.725415 |
bf20970e105b5dd11cb74bb7b7c18c2a987ad46c | 1,026 | package com.ohmybug.test;
import com.ohmybug.dao.LocationDao;
import com.ohmybug.dao.impl.LocationDaoImpl;
import com.ohmybug.pojo.Location;
import org.junit.Test;
import static org.junit.Assert.*;
public class LocationDaoImplTest {
private LocationDao locationDao = new LocationDaoImpl();
@Test
public void addLocation() {
locationDao.addLocation(new Location(null, "汇文楼"));
locationDao.addLocation(new Location(null, "汇紫楼"));
locationDao.addLocation(new Location(null, "汇星楼"));
locationDao.addLocation(new Location(null, "汇智楼"));
}
@Test
public void deleteLocationById() {
locationDao.deleteLocationById(5);
}
@Test
public void updateLocation() {
locationDao.updateLocation(new Location(4, "汇紫楼"));
}
@Test
public void queryLocationById() {
System.out.println(locationDao.queryLocationById(1));
}
@Test
public void queryLocations() {
System.out.println(locationDao.queryLocations());
}
} | 25.02439 | 61 | 0.680312 |
1c185638d2243c7ab30ae2460680c1de946e4d05 | 1,281 | package basic;
import java.sql.Connection;
import org.junit.Test;
import pm.pride.DatabaseFactory;
/*******************************************************************************
* Copyright (c) 2001-2005 The PriDE team and MATHEMA Software GmbH
* All rights reserved. This toolkit and the accompanying materials
* are made available under the terms of the GNU Lesser General Public
* License (LGPL) which accompanies this distribution, and is available
* at http://pride.sourceforge.net/LGPL.html
*
* Contributors:
* Jan Lessner, MATHEMA Software GmbH - JUnit test suite
*******************************************************************************/
/**
* JUnit test class performing some basic tests of PriDE's simple
* resource and transaction management in non-managed environments
*/
public class PrideResourceTest extends AbstractPrideTest {
@Test
public void testReconnect() throws Exception {
Connection con = DatabaseFactory.getDatabase().getConnection();
con.close();
// Following (senseless) statement must not fail though this thread's
// connection was closed in the line above.
DatabaseFactory.getDatabase().sqlUpdate("update " + AbstractPrideTest.TEST_TABLE + " set id = 5 where 1=0");
}
}
| 35.583333 | 111 | 0.640125 |
b3fcf25cd14d8727e93bbe5d14377900fb334040 | 223 |
import java.util.function.Function;
class MyTest {
static <T, R, F extends Function<T, R>> F from(F fun1) {
return fun1;
}
void test2() {
Function<Object, Integer> ext = from(x -> 1);
}
} | 17.153846 | 60 | 0.565022 |
23a7a20524117cde0f714a18d05be22a456c24b6 | 12,034 | package view.special;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Side;
import javafx.scene.chart.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.scene.text.TextFlow;
import model.Doctor;
import model.Person;
import network.api.DashboardAPI;
import network.api.DoctorAPI;
import network.api.PatientsAPI;
import ui.UITableView;
import ui.UIView;
import utils.AutoSignIn;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.ResourceBundle;
import java.util.function.Predicate;
/**
* Created By Tony on 28/07/2018
*/
public class DashboardView extends UIView {
@FXML
private TextFlow query13;
@FXML
private TextFlow doctorsLabel;
@FXML
private PieChart query2;
@FXML
private PieChart query8;
@FXML
private TextFlow unknown1;
@FXML
private VBox query5_vbox;
@FXML
private StackedBarChart<String,Integer> query9;
@FXML
NumberAxis xAxis;
@FXML
CategoryAxis yAxis;
@FXML
private TextFlow query14;
@FXML
private TextFlow query15;
@FXML
private AreaChart query18;
@FXML
private PieChart query19;
@FXML
NumberAxis x16Axis;
@FXML
CategoryAxis y16Axis;
UITableView<Person> personTableView;
public DashboardView() {
super("/resources/xml/view_dashboard3.fxml");
}
@Override
public void layoutSubviews(ResourceBundle bundle) {
super.layoutSubviews(bundle);
new DoctorAPI().readAll((response, items) -> {
items.removeIf(doctor -> !AutoSignIn.HOSPITAL_ID.equals(doctor.getHospitalID()));
Text text1=new Text("Doctors");
text1.setStyle("-fx-font-weight: regular");
Text text2=new Text("\n"+items.size());
text2.setStyle("-fx-font-weight: bold; -fx-font-size: 24px");
doctorsLabel.getChildren().addAll(text1, text2);
//doctorsLabel.setText("Number Of Doctors\n"+items.size());
});
new DashboardAPI().getData((response, data) -> {
if(data == null || !data.has("data"))
return;
data = data.get("data").getAsJsonObject();
//========================================================================
JsonArray query6result = data.get("query6_result").getAsJsonArray();
ObservableList<PieChart.Data> query6data = FXCollections.observableArrayList();
int totalAmount = 0;
for (JsonElement element : query6result) {
String depName = element
.getAsJsonObject()
.get("object_b")
.getAsJsonObject()
.get("departmentName")
.getAsString();
int amount = element
.getAsJsonObject()
.get("amount")
.getAsInt();
totalAmount += amount;
query6data.add(new PieChart.Data(depName,amount));
}
query2.setData(query6data);
query2.setLegendSide(Side.RIGHT);
query2.setTitle("Income from departments");
Text totalAmountLabel = new Text("Total Income");
totalAmountLabel.setStyle("-fx-font-weight: regular");
Text totalAmountValue =new Text("\n$" +totalAmount + ".00");
totalAmountValue.setStyle("-fx-font-weight: bold; -fx-font-size: 24px");
query14.getChildren().addAll(totalAmountLabel,totalAmountValue);
//========================================================================
JsonArray query9result = data.get("query9_result").getAsJsonArray();
query9.setAnimated(false);
for (JsonElement element : query9result) {
String depName = element
.getAsJsonObject()
.get("object_b")
.getAsJsonObject()
.get("departmentName")
.getAsString();
int amount = element
.getAsJsonObject()
.get("freeBedsInDepartment")
.getAsInt();
XYChart.Series<String,Integer> series1 = new XYChart.Series<>();
series1.getData().add(new XYChart.Data<>(depName,amount));
query9.getData().add(series1);
}
query9.setCategoryGap(5);
query9.setLegendVisible(false);
query9.setTitle("Empty Beds In Departments");
//=========================================================================
personTableView = new UITableView<Person>() {
List<Person> people;
@Override
public void layoutSubviews(ResourceBundle bundle) {
super.layoutSubviews(bundle);
people = new ArrayList<>();
new PatientsAPI().readAll((response1, items) -> {
if(response.isOK())
people.addAll(items);
reloadData();
});
}
@Override
public int numberOfColumns() {
return 4;
}
@Override
public Collection<? extends Person> dataSource() {
return people;
}
@Override
public String bundleIdForIndex(int index) {
switch (index){
case 0:
return "ID";
case 1:
return "First Name";
case 2:
return "Sur Name";
case 3:
return "Birth Date";
}
return null;
}
@Override
public TableColumnValue<Person> cellValueForColumnAt(int index) {
switch (index){
case 0:
return Person::getID;
case 1:
return Person::getFirstName;
case 2:
return Person::getSurName;
case 3:
return Person::getDateOfBirth;
}
return null;
}
};
query5_vbox.getChildren().addAll(personTableView);
// =====================================================
JsonArray query8result = data.get("query8_result").getAsJsonArray();
ObservableList<PieChart.Data> query8data = FXCollections.observableArrayList();
String[] stringTypes = new String[]{"A", "B", "AB", "O"};
int typeA = 0;
int typeB = 0;
int typeAB = 0;
int typeO = 0;
for (JsonElement element : query8result) {
switch (element.getAsJsonObject().get("bloodType").getAsString()){
case "A":
typeA++;
case "B":
typeB++;
case "AB":
typeAB++;
case "O":
typeO++;
default:
break;
}
}
for (String type : stringTypes) {
switch (type) {
case "A":
query8data.add(new PieChart.Data(type + " (" + typeA + ")",typeA));
break;
case "B":
query8data.add(new PieChart.Data(type + " (" + typeB + ")",typeB));
break;
case "AB":
query8data.add(new PieChart.Data(type + " (" + typeAB + ")",typeAB));
break;
case "O":
query8data.add(new PieChart.Data(type + " (" + typeO + ")",typeO));
break;
default:
break;
}
}
query8.setData(query8data);
query8.setLegendVisible(false);
query8.setTitle("Potential Donors");
// ====================================================================================
JsonArray query13result = data.get("query13_result").getAsJsonArray();
Text text1=new Text("Patients");
text1.setStyle("-fx-font-weight: regular");
Text text2=new Text("\n"+query13result.get(0).getAsJsonObject().get("number_of_patients").getAsInt());
text2.setStyle("-fx-font-weight: bold; -fx-font-size: 24px");
query13.getChildren().addAll(text1, text2);
// ====================================================================================
JsonArray query14result = data.get("query14_result").getAsJsonArray();
ObservableList<PieChart.Data> query19data = FXCollections.observableArrayList();
String mostPopularCity = "";
int maxPeopleInCity = 0;
for (JsonElement element : query14result) {
String cityName = element
.getAsJsonObject()
.get("object_a")
.getAsJsonObject()
.get("city")
.getAsString();
int amount = element
.getAsJsonObject()
.get("number_of_patients")
.getAsInt();
if(maxPeopleInCity < amount){
maxPeopleInCity = amount;
mostPopularCity = cityName;
}
query19data.add(new PieChart.Data(cityName,amount));
}
query19.setTitle("City Distribution");
query19.setData(query19data);
// ====================================================================================
Text popluarCityLabel = new Text("Most Popular City");
popluarCityLabel.setStyle("-fx-font-weight: regular");
Text popularCityValue = new Text("\n" + mostPopularCity);
popularCityValue.setStyle("-fx-font-weight: bold; -fx-font-size: 24px");
query15.getChildren().addAll(popluarCityLabel, popularCityValue);
// ===================================================================================
JsonArray query16result = data.get("query15_result").getAsJsonArray();
final CategoryAxis x16Axis = new CategoryAxis();
final NumberAxis y16Axis = new NumberAxis();
y16Axis.setLabel("Patients");
x16Axis.setLabel("Month");
query18.setAnimated(false);
XYChart.Series<String,Integer> series1 = new XYChart.Series<>();
for (JsonElement element : query16result) {
String month = String.valueOf(element
.getAsJsonObject()
.get("month")
.getAsInt());
int amount = element
.getAsJsonObject()
.get("patients")
.getAsInt();
series1.getData().add(new XYChart.Data<>(month,amount));
}
query18.getData().add(series1);
query18.setLegendVisible(false);
query18.setTitle("Patients In Hospital Every Month");
});
}
}
| 31.835979 | 114 | 0.469088 |
ba18bd6153156f0c2c89d225fccfc95ef2c09f2c | 4,177 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.utils.servlet;
import java.io.IOException;
import javax.annotation.Priority;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.dspace.kernel.DSpaceKernel;
import org.dspace.kernel.DSpaceKernelManager;
import org.dspace.services.RequestService;
/**
* This servlet filter will handle the hookup and setup for DSpace
* requests. It should be applied to any webapp that is using the
* DSpace core.
* <p>
* It will also do anything necessary to the requests that are coming
* into a DSpace web application and the responses on their way out.
*
* @author Aaron Zeckoski (azeckoski @ gmail.com)
*/
@Priority(1)
public final class DSpaceWebappServletFilter implements Filter {
/* (non-Javadoc)
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// ensure the kernel is running, if not then we have to die here
try {
getKernel();
} catch (IllegalStateException e) {
// no kernel so we die
String message = "Could not start up DSpaceWebappServletFilter because the DSpace Kernel is unavailable or not running: " + e.getMessage();
System.err.println(message);
throw new ServletException(message, e);
}
}
/* (non-Javadoc)
* @see javax.servlet.Filter#destroy()
*/
public void destroy() {
// clean up the logger for this webapp
// No longer using commons-logging (JCL), use slf4j instead
//LogFactory.release(Thread.currentThread().getContextClassLoader());
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// now do some DSpace stuff
//try {
DSpaceKernel kernel = getKernel();
// establish the request service startup
RequestService requestService = kernel.getServiceManager().getServiceByName(RequestService.class.getName(), RequestService.class);
if (requestService == null) {
throw new IllegalStateException("Could not get the DSpace RequestService to start the request transaction");
}
// establish a request related to the current session
requestService.startRequest(request, response); // will trigger the various request listeners
try {
// invoke the next filter
chain.doFilter(request, response);
// ensure we close out the request (happy request)
requestService.endRequest(null);
} catch (Exception e) {
// failure occurred in the request so we destroy it
requestService.endRequest(e);
throw new ServletException(e); // rethrow the exception
}
/*
} catch (Exception e) {
String message = "Failure in the DSpaceWebappServletFilter: " + e.getMessage();
System.err.println(message);
if (res != null) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
} else {
throw new ServletException(message, e);
}*/
//}
}
/**
* @return the current DSpace kernel or fail
*/
public DSpaceKernel getKernel() {
DSpaceKernel kernel = new DSpaceKernelManager().getKernel();
if (! kernel.isRunning()) {
throw new IllegalStateException("The DSpace kernel is not running: " + kernel);
}
return kernel;
}
}
| 36.964602 | 151 | 0.652382 |
d8711b01732ab86584fc2938e4c23122c7e64974 | 1,241 | package io.github.swagger2markup.adoc.converter.internal;
import org.apache.commons.lang3.StringUtils;
import org.asciidoctor.ast.ContentNode;
public class BlockImageNode extends NodeAttributes {
final private String target;
public BlockImageNode(ContentNode node) {
super(node.getAttributes());
target = pop("target").replaceAll("\\s", "{sp}");
}
public String getTarget() {
return target;
}
@Override
public void processPositionalAttributes() {
String attr1 = pop("1", "alt");
if (StringUtils.isNotBlank(attr1)) {
attrs.add(attr1);
}
String attr2 = pop("2", "width");
if (StringUtils.isNotBlank(attr2)) {
attrs.add(attr2);
}
String attr3 = pop("3", "height");
if (StringUtils.isNotBlank(attr3)) {
attrs.add(attr3);
}
}
@Override
void processAttributes() {
attributes.forEach((k, v) -> {
if (!k.equals("role") && null != v) {
attrs.add(k + "=" + v);
}
});
}
@Override
public String processAsciiDocContent() {
return "image::" + target + '[' + String.join(",", attrs) + ']';
}
}
| 24.333333 | 72 | 0.553586 |
1ac112de32912996366c83c66c2249f56add1c55 | 580 | package com.xuzp.insuredxmltool.core.tool.script.warlock.statement;
import com.xuzp.insuredxmltool.core.tool.formula.Factors;
import com.xuzp.insuredxmltool.core.tool.script.warlock.Code;
import com.xuzp.insuredxmltool.core.tool.script.warlock.Interrupt;
import com.xuzp.insuredxmltool.core.tool.script.warlock.analyse.Words;
public class StatementContinue implements Code
{
public StatementContinue(Words ws)
{
}
public Object run(Factors factors)
{
return Interrupt.interruptOf(Interrupt.CONTINUE);
}
public String toText(String space)
{
return "CONTINUE";
}
}
| 24.166667 | 70 | 0.798276 |
1be761ae6de5fc145b95d2f6f503ef07ad7ba10f | 577 | package burlap.shell.command.reserved;
import burlap.shell.BurlapShell;
import burlap.shell.command.ShellCommand;
import java.io.PrintStream;
import java.util.Scanner;
/**
* A reserved {@link burlap.shell.command.ShellCommand} for displaying the general shell help information.
* @author James MacGlashan.
*/
public class HelpCommand implements ShellCommand {
@Override
public String commandName() {
return "help";
}
@Override
public int call(BurlapShell shell, String argString, Scanner is, PrintStream os) {
os.println(shell.getHelpText());
return 0;
}
}
| 22.192308 | 106 | 0.760832 |
bf76047e73f5ddbdbc3ed180599416f7dc17039e | 3,848 | // Copyright 2016 The Sawdust Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package array;
import java.util.NoSuchElementException;
import java.util.Scanner;
/**
* @see <a
* href="https://www.hackerrank.com/contests/citrix-code-master/challenges/server-grid-failure-problem">hacker
* rank</a>
*/
public class HackerrankServerGridFailureProblem {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int rows = s.nextInt();
int cols = s.nextInt();
String[] errs = new String[rows * cols];
int size = 0;
String err = null;
try {
s.nextLine();
} catch (NoSuchElementException e) {
// input may be no error server input
// care used for hackr rank
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
System.out.println(String.format("server [%s,%s]", i, j)); // care: need (); it is i here
}
}
return; // care
}
while (true) { // care
try {
err = s.nextLine();
} catch (NoSuchElementException e) {
break; // care used for hackr rank
}
if (err.length() == 0) { //care
break; // used in my laptop
}
errs[size++] = err;
}
int[] candidator = new int[rows * cols + 1];
int maxWeight = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
String ei = errs[i];
String r = ei.substring(ei.indexOf("[") + 1, ei.indexOf(","));
String c = ei.substring(ei.indexOf(",") + 1, ei.indexOf("]"));
int row = Integer.valueOf(r);
int col = Integer.valueOf(c);
int key;
if (row - 1 >= 1 && col - 1 >= 1) {
key = (row - 1 - 1) * rows + col - 1;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (row - 1 >= 1) {
key = (row - 1 - 1) * rows + col;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (row - 1 >= 1 && col + 1 <= cols) {
key = (row - 1 - 1) * rows + col + 1;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (col - 1 >= 1) {
key = (row - 1) * rows + col - 1;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (col + 1 <= cols) {
key = (row - 1) * rows + col + 1;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (row + 1 <= rows && col - 1 >= 1) {
key = (row) * rows + col - 1;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (row + 1 <= rows) {
key = (row) * rows + col;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
if (row + 1 <= rows && col + 1 <= cols) {
key = (row) * rows + col + 1;
candidator[key]++;
maxWeight = Math.max(maxWeight, candidator[key]);
}
}
for (int i = 0; i < candidator.length; i++) {
if (candidator[i] == maxWeight) {
System.out.println(
String.format(
"server [%s,%s]",
i / rows + 1,
i % rows)); // care: need () if not using String.format() ; it is i here
}
}
}
}
| 29.829457 | 114 | 0.537682 |
a7b2fbc088947eb7bed433aebb5f6f2a01dcaf6a | 816 | package org.madrona.web.model;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "user-access")
public class UserAccess {
@Field
private String username;
@Field
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserAccess{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
} | 20.923077 | 62 | 0.601716 |
e69bfc97e43a26e30945570b6a777ebd86c30171 | 1,011 |
/*
* Copyright 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 software.amazon.awssdk.crt.android;
import software.amazon.awssdk.crt.BuildConfig;
import software.amazon.awssdk.crt.CrtPlatform;
import software.amazon.awssdk.crt.utils.PackageInfo;
public class CrtPlatformImpl extends CrtPlatform {
public String getOSIdentifier() {
return "android";
}
public PackageInfo.Version getVersion() {
return new PackageInfo.Version(BuildConfig.VERSION_NAME);
}
} | 32.612903 | 76 | 0.742829 |
735e509af87da7a9a183bfaaa50c91f9d923555f | 285 | package com.amazon.alexa.auto.setup.workflow.model;
public enum LocationConsent {
ENABLED("ENABLED"),
DISABLED("DISABLED");
String value;
LocationConsent(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
| 16.764706 | 51 | 0.631579 |
5bb85eeb38386d3e4b4144b0b0386ab81086bb0e | 2,436 |
package com.moringaschool.gymsmart;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.parceler.Parcel;
@Parcel
public class Result {
@SerializedName("name")
@Expose
private String name;
@SerializedName("category")
@Expose
private Category category;
@SerializedName("description")
@Expose
private String description;
@SerializedName("muscles")
@Expose
private List<Muscle> muscles = null;
@SerializedName("muscles_secondary")
@Expose
private List<MusclesSecondary> musclesSecondary = null;
@SerializedName("equipment")
@Expose
private List<Equipment> equipment = null;
/**
* No args constructor for use in serialization
*
*/
public Result() {
}
/**
*
* @param musclesSecondary
* @param muscles
* @param name
* @param description
* @param equipment
* @param category
*/
public Result(String name, Category category, String description, List<Muscle> muscles, List<MusclesSecondary> musclesSecondary, List<Equipment> equipment) {
super();
this.name = name;
this.category = category;
this.description = description;
this.muscles = muscles;
this.musclesSecondary = musclesSecondary;
this.equipment = equipment;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Muscle> getMuscles() {
return muscles;
}
public void setMuscles(List<Muscle> muscles) {
this.muscles = muscles;
}
public List<MusclesSecondary> getMusclesSecondary() {
return musclesSecondary;
}
public void setMusclesSecondary(List<MusclesSecondary> musclesSecondary) {
this.musclesSecondary = musclesSecondary;
}
public List<Equipment> getEquipment() {
return equipment;
}
public void setEquipment(List<Equipment> equipment) {
this.equipment = equipment;
}
}
| 22.766355 | 161 | 0.646552 |
98435e4357e3138d65b354ec8b7ef3d534f0a35c | 178 | package com.grafixartist.gallery.retrogram.model;
public class LocationResponse {
private Location data;
public Location getLocation() {
return data;
}
}
| 14.833333 | 49 | 0.696629 |
593d73865458b724c5f386549c85d426fb83efdc | 5,581 | /*
* Copyright (C) 2016 Mkhytar Mkhoian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.justplay1.shoppist.models.mappers;
import com.justplay1.shoppist.models.CategoryModel;
import com.justplay1.shoppist.models.CategoryViewModel;
import com.justplay1.shoppist.models.ProductModel;
import com.justplay1.shoppist.models.ProductViewModel;
import com.justplay1.shoppist.models.UnitModel;
import com.justplay1.shoppist.models.UnitViewModel;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static com.justplay1.shoppist.ViewModelUtil.FAKE_CREATE_BY_USER;
import static com.justplay1.shoppist.ViewModelUtil.FAKE_ID;
import static com.justplay1.shoppist.ViewModelUtil.FAKE_NAME;
import static com.justplay1.shoppist.ViewModelUtil.FAKE_TIME_CREATED;
import static com.justplay1.shoppist.ViewModelUtil.createFakeCategoryModel;
import static com.justplay1.shoppist.ViewModelUtil.createFakeCategoryViewModel;
import static com.justplay1.shoppist.ViewModelUtil.createFakeProductModel;
import static com.justplay1.shoppist.ViewModelUtil.createFakeProductViewModel;
import static com.justplay1.shoppist.ViewModelUtil.createFakeUnitModel;
import static com.justplay1.shoppist.ViewModelUtil.createFakeUnitViewModel;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
/**
* Created by Mkhytar Mkhoian.
*/
public class GoodsModelDataMapperTest {
private UnitsViewModelMapper unitsMapper;
private CategoryViewModelMapper categoryMapper;
private GoodsViewModelMapper mapper;
@Before
public void setUp() throws Exception {
unitsMapper = new UnitsViewModelMapper();
categoryMapper = new CategoryViewModelMapper();
mapper = new GoodsViewModelMapper(unitsMapper, categoryMapper);
}
@Test
public void transformGoodsViewModel() {
CategoryViewModel categoryViewModel = createFakeCategoryViewModel();
CategoryModel categoryModel = categoryMapper.transform(categoryViewModel);
UnitViewModel unitViewModel = createFakeUnitViewModel();
UnitModel unitModel = unitsMapper.transform(unitViewModel);
ProductViewModel productViewModel = createFakeProductViewModel(categoryViewModel, unitViewModel);
ProductModel productModel = mapper.transform(productViewModel);
assertThat(productModel, is(instanceOf(ProductModel.class)));
assertThat(productModel.getId(), is(FAKE_ID));
assertThat(productModel.getName(), is(FAKE_NAME));
assertThat(productModel.getTimeCreated(), is(FAKE_TIME_CREATED));
assertThat(productModel.isCreateByUser(), is(FAKE_CREATE_BY_USER));
assertThat(productModel.getCategory(), is(categoryModel));
assertThat(productModel.getUnit(), is(unitModel));
}
@Test
public void transformGoodsViewModelCollection() {
ProductViewModel mockDAOOne = mock(ProductViewModel.class);
ProductViewModel mockDAOTwo = mock(ProductViewModel.class);
List<ProductViewModel> list = new ArrayList<>(5);
list.add(mockDAOOne);
list.add(mockDAOTwo);
Collection<ProductModel> collection = mapper.transform(list);
assertThat(collection.toArray()[0], is(instanceOf(ProductModel.class)));
assertThat(collection.toArray()[1], is(instanceOf(ProductModel.class)));
assertThat(collection.size(), is(2));
}
@Test
public void transformGoodsModel() {
CategoryModel categoryModel = createFakeCategoryModel();
CategoryViewModel categoryDAO = categoryMapper.transformToViewModel(categoryModel);
UnitModel unitModel = createFakeUnitModel();
UnitViewModel unitDAO = unitsMapper.transformToViewModel(unitModel);
ProductModel productModel = createFakeProductModel(unitModel, categoryModel);
ProductViewModel dao = mapper.transformToViewModel(productModel);
assertThat(dao, is(instanceOf(ProductViewModel.class)));
assertThat(dao.getId(), is(FAKE_ID));
assertThat(dao.getName(), is(FAKE_NAME));
assertThat(dao.getTimeCreated(), is(FAKE_TIME_CREATED));
assertThat(dao.isCreateByUser(), is(FAKE_CREATE_BY_USER));
assertThat(dao.getCategory(), is(categoryDAO));
assertThat(dao.getUnit(), is(unitDAO));
}
@Test
public void transformGoodsModelCollection() {
ProductModel mockModelOne = mock(ProductModel.class);
ProductModel mockModelTwo = mock(ProductModel.class);
List<ProductModel> list = new ArrayList<>(5);
list.add(mockModelOne);
list.add(mockModelTwo);
Collection<ProductViewModel> collection = mapper.transformToViewModel(list);
assertThat(collection.toArray()[0], is(instanceOf(ProductViewModel.class)));
assertThat(collection.toArray()[1], is(instanceOf(ProductViewModel.class)));
assertThat(collection.size(), is(2));
}
} | 40.442029 | 105 | 0.752016 |
33a4c6ae46705fb45e60c8ec1ef39e3897eef081 | 4,259 | package org.opencds.cqf.tooling.modelinfo.qicore;
import java.util.Map;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.opencds.cqf.tooling.modelinfo.ClassInfoBuilder;
public class QICoreClassInfoBuilder extends ClassInfoBuilder {
public QICoreClassInfoBuilder(Map<String, StructureDefinition> structureDefinitions) {
super(new QICoreClassInfoSettings(), structureDefinitions);
}
@Override
protected void innerBuild() {
this.buildFor("QICore", "qicore-adverseevent");
this.buildFor("QICore", "qicore-allergyintolerance");
this.buildFor("QICore", "qicore-bodystructure");
this.buildFor("QICore", "qicore-claim");
this.buildFor("QICore", "qicore-careplan");
this.buildFor("QICore", "qicore-careteam");
this.buildFor("QICore", "qicore-communication");
this.buildFor("QICore", "qicore-communicationnotdone");
this.buildFor("QICore", "qicore-communicationrequest");
this.buildFor("QICore", "qicore-condition");
this.buildFor("QICore", "qicore-coverage");
this.buildFor("QICore", "qicore-device");
this.buildFor("QICore", "qicore-devicenotrequested");
this.buildFor("QICore", "qicore-devicerequest");
this.buildFor("QICore", "qicore-deviceusestatement");
this.buildFor("QICore", "qicore-diagnosticreport-lab");
this.buildFor("QICore", "qicore-diagnosticreport-note");
this.buildFor("QICore", "qicore-encounter");
this.buildFor("QICore", "qicore-familymemberhistory");
this.buildFor("QICore", "qicore-flag");
this.buildFor("QICore", "qicore-goal");
this.buildFor("QICore", "qicore-imagingstudy");
this.buildFor("QICore", "qicore-immunization");
this.buildFor("QICore", "qicore-immunizationevaluation");
this.buildFor("QICore", "qicore-immunizationnotdone");
this.buildFor("QICore", "qicore-immunizationrec");
this.buildFor("QICore", "us-core-implantable-device");
this.buildFor("QICore", "qicore-location");
this.buildFor("QICore", "qicore-medication");
this.buildFor("QICore", "qicore-medicationadministration");
this.buildFor("QICore", "qicore-mednotadministered");
this.buildFor("QICore", "qicore-medicationdispense");
this.buildFor("QICore", "qicore-mednotdispensed");
this.buildFor("QICore", "qicore-mednotrequested");
this.buildFor("QICore", "qicore-medicationrequest");
this.buildFor("QICore", "qicore-medicationstatement");
this.buildFor("QICore", "qicore-observation");
this.buildFor("QICore", "qicore-observationnotdone");
this.buildFor("QICore", "vitalspanel");
this.buildFor("QICore", "resprate");
this.buildFor("QICore", "heartrate");
this.buildFor("QICore", "oxygensat");
this.buildFor("QICore", "bodytemp");
this.buildFor("QICore", "bodyheight");
this.buildFor("QICore", "headcircum");
this.buildFor("QICore", "bodyweight");
this.buildFor("QICore", "bmi");
this.buildFor("QICore", "bp");
this.buildFor("QICore", "us-core-smokingstatus");
this.buildFor("QICore", "us-core-pulse-oximetry");
this.buildFor("QICore", "us-core-observation-lab");
this.buildFor("QICore", "pediatric-bmi-for-age");
this.buildFor("QICore", "pediatric-weight-for-height");
this.buildFor("QICore", "qicore-organization");
this.buildFor("QICore", "qicore-patient");
this.buildFor("QICore", "qicore-practitioner");
this.buildFor("QICore", "qicore-practitionerrole");
this.buildFor("QICore", "qicore-procedure");
this.buildFor("QICore", "qicore-procedurenotdone");
this.buildFor("QICore", "qicore-relatedperson");
this.buildFor("QICore", "qicore-servicerequest");
this.buildFor("QICore", "qicore-servicenotrequested");
this.buildFor("QICore", "qicore-specimen");
this.buildFor("QICore", "qicore-substance");
this.buildFor("QICore", "qicore-task");
this.buildFor("QICore", "qicore-tasknotdone");
this.buildFor("QICore", "Questionnaire");
this.buildFor("QICore", "QuestionnaireResponse");
}
} | 49.523256 | 90 | 0.656023 |
e665452ad50b1ff9fecd32fe2093569ad77c1581 | 1,963 | package cla.edg.project.optical.gen.graphquery;
import java.util.Map;
import cla.edg.modelbean.*;
public class ShoppingCartItem extends BaseModelBean {
public String getFullClassName() {
return "com.doublechaintech.optical.shoppingcartitem.ShoppingCartItem";
}
// 枚举对象
// 引用的对象
public ShoppingCart shoppingCart() {
ShoppingCart member = new ShoppingCart();
member.setModelTypeName("shopping_cart");
member.setName("shopping_cart");
member.setMemberName("shoppingCart");
member.setReferDirection(true);
member.setRelationName("shoppingCart");
append(member);
return member;
}
public LineItem lineItem() {
LineItem member = new LineItem();
member.setModelTypeName("line_item");
member.setName("line_item");
member.setMemberName("lineItem");
member.setReferDirection(true);
member.setRelationName("lineItem");
append(member);
return member;
}
// 被引用的对象
// 普通属性
public StringAttribute id() {
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
// member.setName("id");
member.setName("id");
useMember(member);
return member;
}
public DateTimeAttribute createTime() {
DateTimeAttribute member = new DateTimeAttribute();
member.setModelTypeName("date_time_create");
// member.setName("createTime");
member.setName("create_time");
useMember(member);
return member;
}
public DateTimeAttribute lastUpdateTime() {
DateTimeAttribute member = new DateTimeAttribute();
member.setModelTypeName("date_time_update");
// member.setName("lastUpdateTime");
member.setName("last_update_time");
useMember(member);
return member;
}
public NumberAttribute version() {
NumberAttribute member = new NumberAttribute();
member.setModelTypeName("int");
// member.setName("version");
member.setName("version");
useMember(member);
return member;
}
}
| 25.493506 | 75 | 0.700968 |
714c72b1a46a3acf3cd6c7f6c5ff14f18fbc6460 | 1,180 | package org.j6toj8.fileio.files;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;
public class Files_CreateDirectories {
public static void main(String[] args) {
// tag::code[]
String userHome = System.getProperty("user.home");
System.out.println("User home: " + userHome);
// Using a random directory name, just for example to run countless times without problems
String randomName1 = "file" + new Random().nextInt();
String randomName2 = "file" + new Random().nextInt();
String randomName3 = "file" + new Random().nextInt();
Path path = Paths.get(userHome, randomName1, randomName2, randomName3);
System.out.println("Path: " + path);
try {
Files.createDirectory(path); // WRONG METHOD, THROWS EXCEPTION
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println("Path exist? " + Files.exists(path));
Files.createDirectories(path);
System.out.println("Path exist? " + Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}
// end::code[]
}
}
| 28.780488 | 94 | 0.658475 |
2bef5bdcc53604861a7e19be8046824883aaf442 | 4,052 | package org.bndly.schema.impl.persistence;
/*-
* #%L
* Schema Impl
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* 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.
* #L%
*/
import org.bndly.schema.api.AttributeMediator;
import org.bndly.schema.api.Record;
import org.bndly.schema.api.Transaction;
import org.bndly.schema.api.db.AttributeColumn;
import org.bndly.schema.api.db.UniqueConstraintTable;
import org.bndly.schema.api.exception.SchemaException;
import org.bndly.schema.api.query.Query;
import org.bndly.schema.api.query.QueryContext;
import org.bndly.schema.api.query.Update;
import org.bndly.schema.impl.AccessorImpl;
import org.bndly.schema.impl.EngineImpl;
import org.bndly.schema.model.Attribute;
import org.bndly.schema.model.NamedAttributeHolderAttribute;
import org.bndly.schema.model.UniqueConstraint;
import java.util.List;
/**
*
* @author cybercon <[email protected]>
*/
public class UniqueConstraintTableReferenceUpdate implements TransactionAppender {
public static final UniqueConstraintTableReferenceUpdate INSTANCE = new UniqueConstraintTableReferenceUpdate();
@Override
public void append(Transaction tx, Record record, EngineImpl engine) {
List<UniqueConstraint> constraints = engine.getConstraintRegistry().getUniqueConstraintsForType(record.getType());
if (constraints == null) {
return;
}
for (UniqueConstraint constraint : constraints) {
List<Attribute> affectedAttributes = constraint.getAttributes();
for (Attribute affectedAttribute : affectedAttributes) {
if (NamedAttributeHolderAttribute.class.isInstance(affectedAttribute)) {
// schedule the update of the constraint
scheduleUpdateForConstraint(constraint, tx, record, engine);
break;
}
}
}
}
private void scheduleUpdateForConstraint(UniqueConstraint constraint, Transaction tx, Record record, EngineImpl engine) {
UniqueConstraintTable table = engine.getTableRegistry().getUniqueConstraintTableByConstraint(constraint);
QueryContext qc = engine.getQueryContextFactory().buildQueryContext();
Update update = qc.update();
update.table(table.getTableName());
// update values in uniqueConstraintTable
List<AttributeColumn> columns = table.getColumns();
List<Attribute> atts = constraint.getAttributes();
boolean shouldRunQuery = false;
for (final Attribute attribute : atts) {
final AttributeMediator<Attribute> mediator = engine.getMediatorRegistry().getMediatorForAttribute(attribute);
if (mediator.isAttributePresent(record, attribute)) {
Object value = mediator.getAttributeValue(record, attribute);
AttributeColumn attributeColumn = null;
for (AttributeColumn col : columns) {
if (col.getAttribute() == attribute) {
attributeColumn = col;
}
}
if (attributeColumn == null) {
throw new SchemaException("could not find column for attribute: " + attribute.getName());
}
update.set(attributeColumn.getColumnName(), mediator.createValueProviderFor(record, attribute), mediator.columnSqlType(attribute));
shouldRunQuery = true;
}
}
if (shouldRunQuery) {
AttributeColumn col = engine.getConstraintRegistry().getJoinColumnForTypeInUniqueConstraintTable(constraint, record.getType());
String recordIdField = col.getColumnName();
update.where().expression().criteria().field(recordIdField).equal().value(AccessorImpl.createRecordIdPreparedStatementValueProvider(col, record, engine.getMediatorRegistry()));
Query q = qc.build(record.getContext());
tx.getQueryRunner().run(q);
}
}
}
| 39.72549 | 179 | 0.763327 |
fa83ad47e7e3d02ed8b1021202c370592ef78f25 | 3,593 | package io.github.rcarlosdasilva.weixin.api.op;
import io.github.rcarlosdasilva.weixin.common.dictionary.WebAuthorizeScope;
import io.github.rcarlosdasilva.weixin.model.response.certificate.WaAccessTokenResponse;
/**
* 开放平台下,代公众号的认证相关API
*
* @author <a href="mailto:[email protected]">Dean Zhao</a>
*/
public interface OpWeixinCertificateApi {
/**
* 开放平台代理公众号的网页授权获取code地址跳转.
* <p>
* 与普通公众平台的规则基本一致,多一个开放平台appid
* <p>
* 在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,
* 默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开一个微信页面,
* 该页面最终会跳转到开发者指定的页面。这里会将开发者指定的页面处理成可被微信授权的地址链接。
*
* @param licensoraAppId
* 授权方appid
* @param scope
* {@link WebAuthorizeScope} 应用授权作用域,snsapi_base
* (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo
* (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权, 也能获取其信息)
* @param redirectTo
* 授权后跳转到url
* @param param
* 重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节
* @return 授权链接
* @see <a href=
* "https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=&lang=zh_CN"
* >第一步:请求CODE</a>
*/
String webAuthorize(String licensoraAppId, WebAuthorizeScope scope, String redirectTo,
String param);
/**
* 开放平台代理公众号的网页授权获取code地址跳转.
* <p>
* 与普通公众平台的规则基本一致,多一个开放平台appid
* <p>
* 在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,
* 默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开一个微信页面,
* 该页面最终会跳转到开发者指定的页面。这里会将开发者指定的页面处理成可被微信授权的地址链接。
*
* @param licensoraAppId
* 授权方appid
* @param scope
* {@link WebAuthorizeScope} 应用授权作用域,snsapi_base
* (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo
* (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权, 也能获取其信息)
* @param redirectTo
* 授权后跳转到url
* @return 授权链接
* @see <a href=
* "https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=&lang=zh_CN"
* >第一步:请求CODE</a>
*/
String webAuthorize(String licensoraAppId, WebAuthorizeScope scope, String redirectTo);
/**
* 开放平台下,通过code换取网页授权access_token.
*
* <p>
* 这里通过code换取的是一个特殊的网页授权access_token,与基础支持中的access_token(
* 该access_token用于调用其他接口)不同。如果网页授权的作用域为snsapi_base,
* 则本步骤中获取到网页授权access_token的同时,也获取到了openid,snsapi_base式的网页授权流程即到此为止。
*
* <p>
* 首先保证通过网页授权链接(参考 {@code Weixin.with(key).url().webAuthorize()}
* ),获取微信返回的code。code作为换取access_token的票据,每次用户授权带上的code将不一样,
* code只能使用一次,5分钟未被使用自动过期。
*
* @param appId
* 授权方appid
* @param code
* code票据
* @return {@link WaAccessTokenResponse}
* @see <a href=
* "https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419318590&token=&lang=zh_CN"
* >第二步:通过code换取access_token</a>
*/
WaAccessTokenResponse askWebAuthorizeAccessToken(String appId, String code);
/**
* 开放平台下,刷新access_token.
*
* <p>
* 由于access_token拥有较短的有效期,当access_token超时后,可以使用refresh_token进行刷新,
* refresh_token拥有较长的有效期(7天、30天、60天、90天),当refresh_token失效的后, 需要用户重新授权。
*
* @param appId
* 授权方appid
* @param refreshToken
* 刷新token
* @return {@link WaAccessTokenResponse}
* @see <a href=
* "https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842&token=&lang=zh_CN"
* >第三步:刷新access_token(如果需要)</a>
*/
WaAccessTokenResponse refreshWebAuthorizeAccessToken(String appId, String refreshToken);
}
| 33.579439 | 140 | 0.689953 |
eb54fa1f87d8936a598b54baf38b415aab9d71b2 | 2,420 | package org.ebayopensource.webauthn.crypto;
import static org.junit.Assert.*;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
public class KeyUtilTest {
@Test
public void keyFromModulusAndExponent() throws InvalidKeySpecException, NoSuchAlgorithmException {
KeyUtil keyUtil = new KeyUtil();
PublicKey pubKey = keyUtil.getPubKey(
//"7vjaE_vNFz-FbQ4GNNh-OeY6K4qWyDIvLUfz0YlhjPKfpGSv3mrcatEbAL_vny_FdCgbg1Co_bb6t_p2B2iFdVjY5hr1bXkViPVA-77-F1Cx57ZozEBixNv1-6NbfEiA_OsaPR0kMdkI9iWhF7TokMleHF1RJ_2WR1vcRb-Z99x5LitYTZTmYkcjsZiQBs_YQOZ220WOYNywgg6Xd03ErqAkltucegb4XUkmVl9JxiHoDrXVAmRUj2stDSvE4b2XftNU86v1p8FMykaeQUUXz_8EcTPdt5SydUPtCcdspSFKbKJh4aP_Zp3Fv1iOyQOsF5WB8CO7FssKLBGElHEriQ"
"x15EJFoDr-8r6_ZG_XxJH5olBL6ulPJb4x3-SQHopftZoc--bd72iBq_AVu4umHwLzuMJ1hwRuLEhRzhkWNL4y1-gbiT_g4EnCx0TLu9fY0nVMtkC1QJ4foOkvhnj5WBNPFvXay-uwLu32siqEfc9bMFmyLsb5PO9OwFRw5PlEEH7PzrUyZTGfd03hiP61D3b2iFdtzHml6d-ATcSJg9BQRg5QojJTdqjhDdrB2iLdbS1enMxkgHE_L8lSYZOHeIthWVLhlDSC6TsFd6NHgwnNqk4oVkfwydobK9RhG0hJwCyR2GoEy4s3VIHYzCaSoFnd9HYROssQn6CZwW_tzx-w"
, "AQAB"
);
assertNotNull(pubKey);
String pem = Base64.encodeBase64String(pubKey.getEncoded());
System.out.println (pem);
assertTrue(pem.equals("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx15EJFoDr+8r6/ZG/XxJH5olBL6ulPJb4x3+SQHopftZoc++bd72iBq/AVu4umHwLzuMJ1hwRuLEhRzhkWNL4y1+gbiT/g4EnCx0TLu9fY0nVMtkC1QJ4foOkvhnj5WBNPFvXay+uwLu32siqEfc9bMFmyLsb5PO9OwFRw5PlEEH7PzrUyZTGfd03hiP61D3b2iFdtzHml6d+ATcSJg9BQRg5QojJTdqjhDdrB2iLdbS1enMxkgHE/L8lSYZOHeIthWVLhlDSC6TsFd6NHgwnNqk4oVkfwydobK9RhG0hJwCyR2GoEy4s3VIHYzCaSoFnd9HYROssQn6CZwW/tzx+wIDAQAB"));
}
@Test
public void keyFromPEM () throws InvalidKeySpecException, NoSuchAlgorithmException{
KeyUtil keyUtil = new KeyUtil();
String pemB64 =
"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx15EJFoDr+8r6/ZG/XxJH5olBL6ulPJb4x3+SQHopftZoc++bd72iBq/AVu4umHwLzuMJ1hwRuLEhRzhkWNL4y1+gbiT/g4EnCx0TLu9fY0nVMtkC1QJ4foOkvhnj5WBNPFvXay+uwLu32siqEfc9bMFmyLsb5PO9OwFRw5PlEEH7PzrUyZTGfd03hiP61D3b2iFdtzHml6d+ATcSJg9BQRg5QojJTdqjhDdrB2iLdbS1enMxkgHE/L8lSYZOHeIthWVLhlDSC6TsFd6NHgwnNqk4oVkfwydobK9RhG0hJwCyR2GoEy4s3VIHYzCaSoFnd9HYROssQn6CZwW/tzx+wIDAQAB";
PublicKey pubKey = keyUtil.getPubKey(pemB64);
String format = pubKey.getFormat();
assertNotNull(pubKey);
}
}
| 60.5 | 421 | 0.882645 |
4b744d0fe6b9f689edead85ba4b0c30139cf5443 | 3,002 | /*
* SPDX-License-Identifier: Apache-2.0
* Copyright 2018-2019 The Feast Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package feast.store.serving.redis;
import feast.core.FeatureSetProto.EntitySpec;
import feast.core.FeatureSetProto.FeatureSet;
import feast.storage.RedisProto.RedisKey;
import feast.storage.RedisProto.RedisKey.Builder;
import feast.store.serving.redis.RedisCustomIO.Method;
import feast.store.serving.redis.RedisCustomIO.RedisMutation;
import feast.types.FeatureRowProto.FeatureRow;
import feast.types.FieldProto.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.beam.sdk.transforms.DoFn;
import org.slf4j.Logger;
public class FeatureRowToRedisMutationDoFn extends DoFn<FeatureRow, RedisMutation> {
private static final Logger log =
org.slf4j.LoggerFactory.getLogger(FeatureRowToRedisMutationDoFn.class);
private Map<String, FeatureSet> featureSets;
public FeatureRowToRedisMutationDoFn(Map<String, FeatureSet> featureSets) {
this.featureSets = featureSets;
}
private RedisKey getKey(FeatureRow featureRow) {
FeatureSet featureSet = featureSets.get(featureRow.getFeatureSet());
List<String> entityNames =
featureSet.getSpec().getEntitiesList().stream()
.map(EntitySpec::getName)
.sorted()
.collect(Collectors.toList());
Map<String, Field> entityFields = new HashMap<>();
Builder redisKeyBuilder = RedisKey.newBuilder().setFeatureSet(featureRow.getFeatureSet());
for (Field field : featureRow.getFieldsList()) {
if (entityNames.contains(field.getName())) {
entityFields.putIfAbsent(
field.getName(),
Field.newBuilder().setName(field.getName()).setValue(field.getValue()).build());
}
}
for (String entityName : entityNames) {
redisKeyBuilder.addEntities(entityFields.get(entityName));
}
return redisKeyBuilder.build();
}
/** Output a redis mutation object for every feature in the feature row. */
@ProcessElement
public void processElement(ProcessContext context) {
FeatureRow featureRow = context.element();
try {
RedisKey key = getKey(featureRow);
RedisMutation redisMutation =
new RedisMutation(Method.SET, key.toByteArray(), featureRow.toByteArray(), null, null);
context.output(redisMutation);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
| 37.061728 | 97 | 0.731845 |
d650793990984223a655128f5478257e64a90183 | 3,817 | package vc.inreach.aws.request;
import com.google.common.base.*;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import com.google.common.io.ByteStreams;
import org.apache.http.*;
import org.apache.http.client.methods.HttpRequestWrapper;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.stream.Collectors;
import java.nio.charset.StandardCharsets;
import java.net.URLDecoder;
public class AWSSigningRequestInterceptor implements HttpRequestInterceptor {
private static final Splitter SPLITTER = Splitter.on('&').trimResults().omitEmptyStrings();
private final AWSSigner signer;
public AWSSigningRequestInterceptor(AWSSigner signer) {
this.signer = signer;
}
@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
request.setHeaders(headers(signer.getSignedHeaders(
path(request),
request.getRequestLine().getMethod(),
params(request),
headers(request),
body(request))
));
}
private Multimap<String, String> params(HttpRequest request) throws IOException {
final String rawQuery = ((HttpRequestWrapper) request).getURI().getRawQuery();
if (Strings.isNullOrEmpty(rawQuery))
return ImmutableListMultimap.of();
return params(URLDecoder.decode(rawQuery, StandardCharsets.UTF_8.name()));
}
private Multimap<String, String> params(String query) {
final ImmutableListMultimap.Builder<String, String> queryParams = ImmutableListMultimap.builder();
if (! Strings.isNullOrEmpty(query)) {
for (String pair : SPLITTER.split(query)) {
final int index = pair.indexOf('=');
if (index > 0) {
final String key = pair.substring(0, index);
final String value = pair.substring(index + 1);
queryParams.put(key, value);
} else {
queryParams.put(pair, "");
}
}
}
return queryParams.build();
}
private String path(HttpRequest request) {
return ((HttpRequestWrapper) request).getURI().getRawPath();
}
private Map<String, Object> headers(HttpRequest request) {
final ImmutableMap.Builder<String, Object> headers = ImmutableMap.builder();
for (Header header : request.getAllHeaders()) {
headers.put(header.getName(), header.getValue());
}
return headers.build();
}
private Optional<byte[]> body(HttpRequest request) throws IOException {
final HttpRequest original = ((HttpRequestWrapper) request).getOriginal();
if (! HttpEntityEnclosingRequest.class.isAssignableFrom(original.getClass())) {
return Optional.absent();
}
return Optional.fromNullable(((HttpEntityEnclosingRequest) original).getEntity()).transform(TO_BYTE_ARRAY);
}
private Header[] headers(Map<String, Object> from) {
return from.entrySet().stream()
.map(entry -> new BasicHeader(entry.getKey(), entry.getValue().toString()))
.collect(Collectors.toList())
.toArray(new Header[from.size()]);
}
private static final Function<HttpEntity, byte[]> TO_BYTE_ARRAY = entity -> {
try {
return ByteStreams.toByteArray(entity.getContent());
} catch (IOException e) {
throw Throwables.propagate(e);
}
};
}
| 36.352381 | 115 | 0.644747 |
9872362a6b664392a31c9165047123be4320a155 | 5,727 | package com.github.aureliano.evtbridge.output.jdbc;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.github.aureliano.evtbridge.annotation.doc.SchemaConfiguration;
import com.github.aureliano.evtbridge.annotation.doc.SchemaProperty;
import com.github.aureliano.evtbridge.annotation.validation.NotNull;
import com.github.aureliano.evtbridge.annotation.validation.Valid;
import com.github.aureliano.evtbridge.core.config.IConfigOutput;
import com.github.aureliano.evtbridge.core.config.OutputConfigTypes;
import com.github.aureliano.evtbridge.core.filter.EmptyFilter;
import com.github.aureliano.evtbridge.core.filter.IEventFielter;
import com.github.aureliano.evtbridge.core.formatter.IOutputFormatter;
import com.github.aureliano.evtbridge.core.formatter.PlainTextFormatter;
import com.github.aureliano.evtbridge.core.helper.DataHelper;
import com.github.aureliano.evtbridge.core.jdbc.JdbcConnectionModel;
import com.github.aureliano.evtbridge.core.listener.DataWritingListener;
import com.github.aureliano.evtbridge.core.parser.IParser;
import com.github.aureliano.evtbridge.core.parser.PlainTextParser;
import com.github.aureliano.evtbridge.core.register.ApiServiceRegistrator;
import com.github.aureliano.evtbridge.core.register.ServiceRegistration;
@SchemaConfiguration(
schema = "http://json-schema.org/draft-04/schema#",
title = "Output configuration for Java Database Connectivity.",
type = "object"
)
public class JdbcOutputConfig implements IConfigOutput {
static {
ServiceRegistration registration = new ServiceRegistration()
.withId(OutputConfigTypes.JDBC_OUTPUT.name())
.withAgent(JdbcDataWriter.class)
.withConfiguration(JdbcOutputConfig.class);
ApiServiceRegistrator.instance().registrate(registration);
}
private JdbcConnectionModel connection;
private IParser<?> parser;
private IEventFielter filter;
private Properties metadata;
private IOutputFormatter outputFormatter;
private List<DataWritingListener> dataWritingListeners;
public JdbcOutputConfig() {
this.metadata = new Properties();
this.dataWritingListeners = new ArrayList<DataWritingListener>();
this.parser = new PlainTextParser();
this.filter = new EmptyFilter();
this.outputFormatter = new PlainTextFormatter();
}
@Override
public JdbcOutputConfig putMetadata(String key, String value) {
this.metadata.put(key, value);
return this;
}
@Override
public String getMetadata(String key) {
return this.metadata.getProperty(key);
}
@Override
@SchemaProperty(
property = "metadata",
types = "object",
description = "A key-value pair (hash <string, string>) which provides a mechanism to exchange metadata between configurations (main, inputs and outputs).",
required = false
)
public Properties getMetadata() {
return this.metadata;
}
@Override
public String id() {
return OutputConfigTypes.JDBC_OUTPUT.name();
}
@Override
@SchemaProperty(
property = "parser",
types = "string",
description = "Fully qualified name of parser class used to convert an event into an business object.",
required = false,
defaultValue = "PlainTextParser"
)
public IParser<?> getParser() {
return this.parser;
}
@Override
public JdbcOutputConfig withParser(IParser<?> parser) {
this.parser = parser;
return this;
}
@Override
@SchemaProperty(
property = "filter",
types = "string",
description = "Fully qualified name of filter class used to filter events before writing.",
required = false,
defaultValue = "EmptyFilter"
)
public IEventFielter getFilter() {
return this.filter;
}
@Override
public JdbcOutputConfig withFilter(IEventFielter filter) {
this.filter = filter;
return this;
}
@Override
@SchemaProperty(
property = "outputFormatter",
types = "string",
description = "Fully qualified name of formatter class used to format data output.",
required = false,
defaultValue = "PlainTextFormatter"
)
public IOutputFormatter getOutputFormatter() {
return this.outputFormatter;
}
@Override
@SchemaProperty(
property = "dataWritingListeners",
types = "array",
description = "Fully qualified name of the class that will listen and fire an event before and after a log event is writen.",
required = false
)
public List<DataWritingListener> getDataWritingListeners() {
return this.dataWritingListeners;
}
@Override
public JdbcOutputConfig withDataWritingListeners(List<DataWritingListener> dataWritingListeners) {
this.dataWritingListeners = dataWritingListeners;
return this;
}
@Override
public JdbcOutputConfig addDataWritingListener(DataWritingListener listener) {
this.dataWritingListeners.add(listener);
return this;
}
@Override
public JdbcOutputConfig withOutputFormatter(IOutputFormatter outputFormatter) {
this.outputFormatter = outputFormatter;
return this;
}
@NotNull
@Valid
@SchemaProperty(
property = "connection",
types = "object",
description = "JDBC attributes.",
required = true,
reference = JdbcConnectionModel.class
)
public JdbcConnectionModel getConnection() {
return connection;
}
public JdbcOutputConfig withConnection(JdbcConnectionModel connection) {
this.connection = connection;
return this;
}
@Override
public JdbcOutputConfig clone() {
return new JdbcOutputConfig()
.withParser(this.parser)
.withFilter(this.filter)
.withOutputFormatter(this.outputFormatter)
.withDataWritingListeners(this.dataWritingListeners)
.withMetadata(DataHelper.copyProperties(this.metadata))
.withConnection((this.connection == null) ? null : this.connection.clone());
}
protected JdbcOutputConfig withMetadata(Properties properties) {
this.metadata = properties;
return this;
}
} | 29.520619 | 158 | 0.777545 |
33f84e5cc098618d7f9a58c93fb931d1fa5bb875 | 9,424 | package com.acod.play.app.Activities;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.acod.play.app.Constants;
import com.acod.play.app.Fragments.HomeFragment;
import com.acod.play.app.Models.Song;
import com.acod.play.app.R;
import com.acod.play.app.Searching.SearchMuzikApi;
import com.inscription.ChangeLogDialog;
import org.json.JSONArray;
import org.json.JSONObject;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by andrew on 12/21/14.
*/
/**
* @author Andrew Codispoti
* This is the main activtiy that will contain the vairous fragments and also do all of the searching system wide.
*/
public class HomescreenActivity extends AppCompatActivity {
//Constants
public static final String PLAY_ACTION = "com.acod.play.playmusic";
public static final String PAUSE_ACTION = "com.acod.play.pausemusic";
public static final String STOP_ACTION = "com.acod.play.stopmusic";
//To turn on and off debugging code
public static final boolean debugMode = false;
//For stageout rollouts.
public static float APP_VERSION = 1;
//Fragment manager to handle transactions
FragmentManager manager;
FragmentTransaction fragmentTransaction;
private DrawerLayout drawerLayout;
private ListView drawerList;
//The strings for the navigation drawer.
private String[] drawertitles;
//Handles the drawer icon
private ActionBarDrawerToggle toggle;
//The main fragment to hold content.
private HomeFragment frag;
public static boolean checkNetworkState(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE") || ni.getTypeName().equalsIgnoreCase("Cellular"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
@Override
protected void onStop() {
super.onStop();
}
private void handleGooglePlus() {
String communityPage = "communities/112916674490953671434";
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("com.google.android.apps.plus",
"com.google.android.apps.plus.phone.UrlGatewayActivity");
intent.putExtra("customAppUri", communityPage);
startActivity(intent);
} catch (ActivityNotFoundException e) {
// fallback if G+ app is not installed
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://plus.google.com/" + communityPage)));
}
}
public void handleTwitter() {
try {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("twitter://user?screen_name=andrewcod749"));
startActivity(intent);
} catch (Exception e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("https://twitter.com/#!/andrewcod749")));
}
}
public static Intent getOpenFacebookIntent(Context context) {
try {
context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
return new Intent(Intent.ACTION_VIEW, Uri.parse("fb://page/296814327167093"));
} catch (Exception e) {
return new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com/pages/Play/296814327167093"));
}
}
public void startEmailIntent() {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "Play (Android)");
i.putExtra(Intent.EXTRA_TEXT, "");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (ActivityNotFoundException ex) {
Toast.makeText(this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onStart() {
super.onStart();
if (!checkNetworkState(this)) {
Toast.makeText(this, "Check your internet connection", Toast.LENGTH_LONG).show();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
drawertitles = getResources().getStringArray(R.array.menutiems);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.left_drawer);
drawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, drawertitles));
drawerList.setOnItemClickListener(new DrawerItemClickListener());
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.opendrawer, R.string.app_name);
manager = getFragmentManager();
fragmentTransaction = manager.beginTransaction();
frag = new HomeFragment();
fragmentTransaction.replace(R.id.content_frame, frag).addToBackStack(null);
fragmentTransaction.commit();
drawerLayout.setDrawerListener(toggle);
drawerLayout.post(new Runnable() {
@Override
public void run() {
toggle.syncState();
}
});
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_drawer);
//setup the navigation drawer
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
toggle.setDrawerIndicatorEnabled(true);
}
@Override
public void onPostCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onPostCreate(savedInstanceState, persistentState);
toggle.syncState();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
if (!drawerLayout.isDrawerOpen(Gravity.LEFT))
drawerLayout.openDrawer(Gravity.LEFT);
else drawerLayout.closeDrawer(Gravity.LEFT);
break;
case R.id.changes:
ChangeLogDialog dialog = new ChangeLogDialog(getApplicationContext());
dialog.show();
break;
case R.id.report:
startEmailIntent();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
toggle.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_homescreen);
getFragmentManager().beginTransaction().replace(R.id.content_frame, frag).commit();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
//my songs section
startActivity(new Intent(getApplicationContext(), SavedActivity.class));
break;
case 1:
//twitter list
handleTwitter();
break;
case 2:
//facebook page
startActivity(getOpenFacebookIntent(getApplicationContext()));
break;
case 3:
//google plus community
handleGooglePlus();
break;
}
}
}
}
| 35.69697 | 125 | 0.655242 |
4b0244649251fb284faf3051e59f53c8c8d8662d | 697 | package com.wakaka.design.designs.template.one;
abstract class AbstractAction{//抽象模板
/** 定义参数 */
public static final Integer EAT = 1;
public static final Integer SLEEP = 2;
public static final Integer WORK = 3;
/** 定义动作模板 */
abstract void eat();
abstract void sleep();
abstract void work();
/** 定义名命令执行 */
public void command(Integer code){
switch (code){
case 1:{
this.eat();
}break;
case 2:{
this.sleep();
}break;
case 3:{
this.work();
}break;
default:
System.out.println("没有定义");
}
}
} | 24.892857 | 47 | 0.490674 |
795d8e7447ba549e1a39b766955397316d75913f | 1,724 | /*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package jdk.jfr;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Event annotation, specifies the default setting value for a periodic event.
*
* @since 9
*/
@MetadataDefinition
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Target(ElementType.TYPE)
public @interface Period {
/**
* Settings name {@code "period"} for configuring periodic events
*/
public final static String NAME = "period";
/**
* Returns the default setting value for a periodic setting.
* <p>
* String representation of a positive {@code Long} value followed by an empty
* space and one of the following units:<br>
* <br>
* {@code "ns"} (nanoseconds)<br>
* {@code "us"} (microseconds)<br>
* {@code "ms"} (milliseconds)<br>
* {@code "s"} (seconds)<br>
* {@code "m"} (minutes)<br>
* {@code "h"} (hours)<br>
* {@code "d"} (days)<br>
* <p>
* Example values: {@code "0 ns"}, {@code "10 ms"}, and {@code "1 s"}.
* <p>
* A period may also be <code>"everyChunk"</code> to specify that it occurs at
* least once for every recording file. The number of events that are emitted
* depends on how many times the file rotations occur when data is recorded.
*
* @return the default setting value, not {@code null}
*/
String value() default "everyChunk";
}
| 23.616438 | 82 | 0.63051 |
2b4486e2b69e7badb7b6252d4856b3c380ce732d | 39,944 | //========================================================================
//
//File: ModelMergeTests.java
//
//Copyright 2005-2014 Mentor Graphics Corporation. All rights reserved.
//
//========================================================================
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
//========================================================================
package org.xtuml.bp.model.compare.test;
import java.io.InputStream;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.PlatformUI;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.xtuml.bp.core.ActionNode_c;
import org.xtuml.bp.core.ActivityDiagramAction_c;
import org.xtuml.bp.core.ActivityEdge_c;
import org.xtuml.bp.core.ActivityNode_c;
import org.xtuml.bp.core.Association_c;
import org.xtuml.bp.core.Attribute_c;
import org.xtuml.bp.core.ClassAsAssociatedOneSide_c;
import org.xtuml.bp.core.ClassAsAssociatedOtherSide_c;
import org.xtuml.bp.core.ClassStateMachine_c;
import org.xtuml.bp.core.CorePlugin;
import org.xtuml.bp.core.ExternalEntity_c;
import org.xtuml.bp.core.InstanceStateMachine_c;
import org.xtuml.bp.core.LinkedAssociation_c;
import org.xtuml.bp.core.ModelClass_c;
import org.xtuml.bp.core.NewStateTransition_c;
import org.xtuml.bp.core.NoEventTransition_c;
import org.xtuml.bp.core.Ooaofooa;
import org.xtuml.bp.core.Operation_c;
import org.xtuml.bp.core.Package_c;
import org.xtuml.bp.core.PackageableElement_c;
import org.xtuml.bp.core.SemEvent_c;
import org.xtuml.bp.core.StateEventMatrixEntry_c;
import org.xtuml.bp.core.StateMachineEvent_c;
import org.xtuml.bp.core.StateMachineState_c;
import org.xtuml.bp.core.StateMachine_c;
import org.xtuml.bp.core.SystemModel_c;
import org.xtuml.bp.core.Transition_c;
import org.xtuml.bp.core.common.BridgePointPreferencesStore;
import org.xtuml.bp.core.common.ClassQueryInterface_c;
import org.xtuml.bp.core.common.NonRootModelElement;
import org.xtuml.bp.core.common.Transaction;
import org.xtuml.bp.core.inspector.ObjectElement;
import org.xtuml.bp.model.compare.ComparableTreeObject;
import org.xtuml.bp.model.compare.ComparePlugin;
import org.xtuml.bp.model.compare.ITreeDifferencerProvider;
import org.xtuml.bp.model.compare.TreeDifference;
import org.xtuml.bp.model.compare.TreeDifferencer;
import org.xtuml.bp.model.compare.contentmergeviewer.ModelContentMergeViewer;
import org.xtuml.bp.model.compare.contentmergeviewer.SynchronizedTreeViewer;
import org.xtuml.bp.model.compare.contentmergeviewer.TextualAttributeCompareElementType;
import org.xtuml.bp.model.compare.preferences.ModelComparePreferenceStore;
import org.xtuml.bp.model.compare.providers.ModelCompareContentProvider;
import org.xtuml.bp.model.compare.providers.ObjectElementComparable;
import org.xtuml.bp.model.compare.providers.custom.AssociationSubtypeComparable;
import org.xtuml.bp.test.TestUtil;
import org.xtuml.bp.test.common.BaseTest;
import org.xtuml.bp.test.common.CanvasTestUtils;
import org.xtuml.bp.test.common.CompareTestUtilities;
import org.xtuml.bp.test.common.GitUtil;
import org.xtuml.bp.test.common.OrderedRunner;
import org.xtuml.bp.test.common.TestingUtilities;
import org.xtuml.bp.test.common.ZipUtil;
import org.xtuml.bp.ui.canvas.Connector_c;
import org.xtuml.bp.ui.canvas.GraphicalElement_c;
import org.xtuml.bp.ui.canvas.Model_c;
import org.xtuml.bp.ui.canvas.Ooaofgraphics;
import org.xtuml.bp.ui.canvas.Shape_c;
@RunWith(OrderedRunner.class)
public class ModelMergeTests extends BaseTest {
private String test_repositories = Platform.getInstanceLocation().getURL()
.getFile()
+ "/" + "test_repositories";
@Rule public TestName name = new TestName();
@Override
public String getName(){
return name.getMethodName();
}
/*
* (non-Javadoc)
*
* @see org.xtuml.bp.test.common.BaseTest#initialSetup()
*/
public static boolean isFirstTime = true;
@Override
@Before
public void initialSetup() throws Exception {
if(!isFirstTime)
return;
isFirstTime = false;
CorePlugin
.getDefault()
.getPreferenceStore()
.setValue(
BridgePointPreferencesStore.ENABLE_ERROR_FOR_EMPTY_SYNCHRONOUS_MESSAGE,
false);
String test_repository_location = BaseTest.getTestModelRespositoryLocation();
test_repository_location = new Path(test_repository_location)
.removeLastSegments(1).toString();
ZipUtil.unzipFileContents(
test_repository_location + "/"
+ "test_repositories"
+ "/" + "204.zip",
test_repositories);
ZipUtil.unzipFileContents(
test_repository_location + "/"
+ "test_repositories"
+ "/" + "dts0101054289.zip",
test_repositories);
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
loadProject("HierarchyTestModel");
project = getProjectHandle("HierarchyTestModel");
}
@Override
@After
public void tearDown() throws Exception {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.closeAllEditors(false);
super.tearDown();
}
@Test
public void testAutomaticGraphicalMergeElementDeletion() throws Exception {
String projectName = "AutomaticGraphicalMerge";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
// copy name change
m_sys = getSystemModel(projectName);
Package_c pkg = Package_c.getOneEP_PKGOnR1401(m_sys);
ActivityDiagramAction_c an = ActivityDiagramAction_c.getOneA_GAOnR1107(
ActionNode_c.getManyA_ACTsOnR1105(ActivityNode_c
.getManyA_NsOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg))),
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ActivityDiagramAction_c) candidate).getName()
.equals("ActionOneRenamed");
}
});
CompareTestUtilities.selectElementInTree(false, an);
CompareTestUtilities.mergeSelection();
CompareTestUtilities.flushMergeEditor();
// make sure that the connection was not removed
// as the change to remove the edge was not merged
m_sys = getSystemModel(projectName);
pkg = Package_c.getOneEP_PKGOnR1401(m_sys);
an = ActivityDiagramAction_c.getOneA_GAOnR1107(ActionNode_c
.getManyA_ACTsOnR1105(ActivityNode_c
.getManyA_NsOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg))),
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ActivityDiagramAction_c) candidate).getName()
.equals("ActionOne");
}
});
assertNotNull(an);
ActivityEdge_c edge = ActivityEdge_c.getOneA_EOnR1104(ActivityNode_c
.getOneA_NOnR1105(ActionNode_c.getOneA_ACTOnR1107(an)));
assertNotNull(
"The edge was removed during merge, the test data is not valid.",
edge);
Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(an
.getModelRoot().getId());
Connector_c connector = Connector_c.ConnectorInstance(graphicsRoot);
assertNotNull(
"The graphical connector was removed even though the semantic elements was not.",
connector);
GitUtil.startMergeTool(projectName);
// now copy the semantic removal
CompareTestUtilities.selectElementInTree(true, edge);
CompareTestUtilities.mergeSelection();
CompareTestUtilities.flushMergeEditor();
m_sys = getSystemModel(projectName);
pkg = Package_c.getOneEP_PKGOnR1401(m_sys);
an = ActivityDiagramAction_c.getOneA_GAOnR1107(ActionNode_c
.getManyA_ACTsOnR1105(ActivityNode_c
.getManyA_NsOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg))),
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ActivityDiagramAction_c) candidate).getName()
.equals("ActionOneRenamed");
}
});
edge = ActivityEdge_c.getOneA_EOnR1104(ActivityNode_c
.getOneA_NOnR1105(ActionNode_c.getOneA_ACTOnR1107(an)));
assertNull(
"The edge was not removed during merge, the test data is not valid.",
edge);
connector = Connector_c.ConnectorInstance(graphicsRoot);
assertNull(
"The graphical connector was not removed even though the semantic elements was.",
connector);
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
}
@Test
public void testAutomaticGraphicalMergeElementAdded() throws Exception {
String projectName = "AutomaticGraphicalMergeAddition";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
// copy name change
m_sys = getSystemModel(projectName);
Package_c pkg = Package_c.getOneEP_PKGOnR1401(m_sys);
ActivityEdge_c edge = ActivityEdge_c.ActivityEdgeInstance(pkg
.getModelRoot());
CompareTestUtilities.selectElementInTree(true, edge);
CompareTestUtilities.mergeSelection();
CompareTestUtilities.flushMergeEditor();
// make sure that the connection was not added
// as the change to add the edge was not merged
m_sys = getSystemModel(projectName);
pkg = Package_c.getOneEP_PKGOnR1401(m_sys);
edge = ActivityEdge_c.ActivityEdgeInstance(pkg.getModelRoot());
assertNull(
"The edge was added during merge, the test data is not valid.",
edge);
Ooaofgraphics graphicsRoot = Ooaofgraphics.getInstance(pkg
.getModelRoot().getId());
Connector_c connector = Connector_c.ConnectorInstance(graphicsRoot);
assertNull(
"The graphical connector was added even though the semantic elements was not.",
connector);
GitUtil.startMergeTool(projectName);
// now copy the semantic addition
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
edge = ActivityEdge_c
.ActivityEdgeInstance(viewer.getRightCompareRoot());
CompareTestUtilities.selectElementInTree(false, edge);
CompareTestUtilities.mergeSelection();
CompareTestUtilities.flushMergeEditor();
m_sys = getSystemModel(projectName);
pkg = Package_c.getOneEP_PKGOnR1401(m_sys);
ActivityEdge_c[] edges = ActivityEdge_c.ActivityEdgeInstances(pkg
.getModelRoot());
assertTrue(
"The edge was not added during merge, the test data is not valid.",
edges.length == 2);
Connector_c[] connectors = Connector_c.ConnectorInstances(graphicsRoot);
assertTrue(
"The graphical connector was not added even though the semantic elements was.",
connectors.length == 2);
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
}
@Test
public void testAddStatesAndTransitionsNoExceptions() throws Exception {
String projectName = "dts0101009924";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
// just need to close now and make sure there
// were no exceptions
CompareTestUtilities.flushMergeEditor();
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
BaseTest.dispatchEvents();
}
@Test
public void testConnectorTextDoesNotDisappear() throws Exception {
String projectName = "dts0101039702";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// switch to slave and make sure the provision and
// requirement have a valid represents
GitUtil.switchToBranch("slave", projectName);
String modelRootId = "/" + projectName + "/" + Ooaofooa.MODELS_DIRNAME
+ "/" + projectName + "/" + "Components" + "/" + "Components"
+ "." + Ooaofooa.MODELS_EXT;
Connector_c[] connectors = Connector_c.ConnectorInstances(Ooaofgraphics
.getInstance(modelRootId));
assertTrue("Could not locate connectors in the model.",
connectors.length > 0);
for (Connector_c connector : connectors) {
GraphicalElement_c ge = GraphicalElement_c
.getOneGD_GEOnR2(connector);
NonRootModelElement nrme = (NonRootModelElement) ge.getRepresents();
assertFalse("Found an orphaned connector represents value.",
nrme.isOrphaned());
}
// switch to master and make sure the text is not
// missing
GitUtil.switchToBranch("master", projectName);
connectors = Connector_c.ConnectorInstances(Ooaofgraphics
.getInstance(modelRootId));
assertTrue("Could not locate connectors in the model.",
connectors.length > 0);
for (Connector_c connector : connectors) {
GraphicalElement_c ge = GraphicalElement_c
.getOneGD_GEOnR2(connector);
NonRootModelElement nrme = (NonRootModelElement) ge.getRepresents();
assertFalse("Found an orphaned connector represents value.",
nrme.isOrphaned());
}
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
}
@Test
public void testMergeOfTransitionNoOrphanedTransitions() throws Exception {
String projectName = "dts0101042909";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
// perform test
CompareTestUtilities.copyAllNonConflictingChangesFromRightToLeft();
CompareTestUtilities.copyConflictingChangesFromRightToLeft();
// validate
assertTrue("Found conflicting changes remaining.", CompareTestUtilities
.getConflictingChanges().size() == 0);
assertTrue("Found incoming changes remaining.", CompareTestUtilities
.getIncomingChanges().size() == 0);
// save and close
CompareTestUtilities.flushMergeEditor();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.closeAllEditors(false);
// validate
// Look for orphaned transitions
Ooaofooa[] roots = Ooaofooa.getInstancesUnderSystem(projectName);
for (Ooaofooa root : roots) {
Transition_c[] transitions = Transition_c.TransitionInstances(root);
for (Transition_c transition : transitions) {
// make sure there is a state and event associated
// unless it is a no event transition
NoEventTransition_c net = NoEventTransition_c
.getOneSM_NETXNOnR507(transition);
if (net == null) {
NewStateTransition_c nst = NewStateTransition_c
.getOneSM_NSTXNOnR507(transition);
if (nst != null) {
StateMachineState_c state = StateMachineState_c
.getOneSM_STATEOnR503(StateEventMatrixEntry_c
.getOneSM_SEMEOnR504(nst));
assertNotNull(
"Transition after merge did not have a destination state.",
state);
StateMachineEvent_c event = StateMachineEvent_c
.getOneSM_EVTOnR525(SemEvent_c
.getOneSM_SEVTOnR503(StateEventMatrixEntry_c
.getOneSM_SEMEOnR504(nst)));
assertNotNull(
"Transition after merge did not have an event assigned.",
event);
}
}
}
}
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
BaseTest.dispatchEvents(0);
}
@Test
public void testNoGraphicalElementCopiedWithoutSemanticCopy()
throws Exception {
ComparePlugin.getDefault().getPreferenceStore()
.setValue(ModelComparePreferenceStore.ENABLE_GRAPHICAL_AUTO_MERGE, true);
ComparePlugin.getDefault().getPreferenceStore()
.setValue(ModelComparePreferenceStore.ENABLE_GRAPHICAL_DIFFERENCES, false);
String projectName = "dts0101042915";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
// perform test
CompareTestUtilities.copyAllNonConflictingChangesFromRightToLeft();
// validate
assertTrue("Found conflicting changes remaining.", CompareTestUtilities
.getConflictingChanges().size() == 1);
assertTrue("Found incoming changes remaining.", CompareTestUtilities
.getIncomingChanges().size() == 0);
// save and close
CompareTestUtilities.flushMergeEditor();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.closeAllEditors(false);
// validate
BaseTest.dispatchEvents(0);
// Look for orphaned graphics
Ooaofooa[] roots = Ooaofooa.getInstancesUnderSystem(projectName);
for (Ooaofooa root : roots) {
Ooaofgraphics graphicsRoot = Ooaofgraphics
.getInstance(root.getId());
GraphicalElement_c[] elements = GraphicalElement_c
.GraphicalElementInstances(graphicsRoot);
for (GraphicalElement_c element : elements) {
// make sure no graphical elements exist that have no
// represented semantic
assertTrue(
"Found an orphaned graphical element after merging.",
element.getRepresents() != null);
}
}
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
BaseTest.dispatchEvents(0);
}
@Test
public void testGraphicalElementDifferencesOnlyCausesDirtyEditor() {
ComparePlugin.getDefault().getPreferenceStore().setValue(ModelComparePreferenceStore.ENABLE_GRAPHICAL_AUTO_MERGE, true);
ComparePlugin.getDefault().getPreferenceStore().setValue(ModelComparePreferenceStore.ENABLE_GRAPHICAL_DIFFERENCES, false);
String projectName = "dts0101054289";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
BaseTest.dispatchEvents(0);
assertTrue("Graphical changes only did not dirty the editor on open.",
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().isSaveOnCloseNeeded());
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.closeAllEditors(false);
TestUtil.deleteProject(getProjectHandle(projectName));
BaseTest.dispatchEvents(0);
}
@Test
public void testMergeWithStateMachineAddedInSeparateBranches()
throws Exception {
String projectName = "dts0101009925";
// import git repository from models repo
GitUtil.loadRepository(test_repositories
+ "/" + projectName);
// import test project
GitUtil.loadProject(projectName, projectName);
// start the merge tool
GitUtil.startMergeTool(projectName);
// perform test
CompareTestUtilities.copyAllNonConflictingChangesFromRightToLeft();
// test for github issue 244, undo then try the merge again
CompareTestUtilities.undoMerge();
// merge all changes again then validate the merge
CompareTestUtilities.copyAllNonConflictingChangesFromRightToLeft();
// (For github issue 224) Test that the slave event is before the
// master event
String[] orderedElements = new String[] { "SlaveStateA", "SlaveStateB", "MasterStateB",
"MasterStateA", "KEY_A1: slave", "KEY_A1: master" };
SystemModel_c system = getSystemModel(projectName);
Package_c pkg = Package_c.getOneEP_PKGOnR1401(system);
assertNotNull(pkg);
ClassStateMachine_c[] csms = ClassStateMachine_c
.getManySM_ASMsOnR519(ModelClass_c
.getManyO_OBJsOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg)));
// validate
assertTrue("Found conflicting changes remaining.", CompareTestUtilities
.getConflictingChanges().size() == 0);
assertTrue("Found incoming changes remaining.", CompareTestUtilities
.getIncomingChanges().size() == 0);
// save and close
CompareTestUtilities.flushMergeEditor(false);
ModelMergeTests2.verifyOrder(orderedElements, csms[0]);
// switch to next editor and copy all changes
GitUtil.switchToFile("InstanceStateMachine.xtuml");
CompareTestUtilities.copyAllNonConflictingChangesFromRightToLeft();
// validate
assertTrue("Found conflicting changes remaining.", CompareTestUtilities
.getConflictingChanges().size() == 0);
assertTrue("Found incoming changes remaining.", CompareTestUtilities
.getIncomingChanges().size() == 0);
// save and close
CompareTestUtilities.flushMergeEditor();
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage()
.closeAllEditors(false);
// validate
BaseTest.dispatchEvents(0);
// just need to account for 8 states and 4 transitions
// and as an extra check make sure there are only one ISM
// and ASM in the test package
InstanceStateMachine_c[] isms = InstanceStateMachine_c
.getManySM_ISMsOnR518(ModelClass_c
.getManyO_OBJsOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg)));
csms = ClassStateMachine_c
.getManySM_ASMsOnR519(ModelClass_c
.getManyO_OBJsOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg)));
assertTrue(
"Test data is not valid, should only be one instance state machine.",
isms.length == 1);
assertTrue(
"Test data is not valid, should only be one class state machine.",
csms.length == 1);
StateMachineState_c[] states = StateMachineState_c
.getManySM_STATEsOnR501(StateMachine_c
.getManySM_SMsOnR517(isms));
assertTrue(
"Did not find a valid number of states in the instance state machine.",
states.length == 4);
states = StateMachineState_c.getManySM_STATEsOnR501(StateMachine_c
.getManySM_SMsOnR517(csms));
assertTrue(
"Did not find a valid number of states in the class state machine.",
states.length == 4);
Transition_c[] transitions = Transition_c
.getManySM_TXNsOnR505(StateMachine_c.getManySM_SMsOnR517(isms));
assertTrue(
"Did not find a valid number of transitions in the instance state machine.",
transitions.length == 4);
transitions = Transition_c.getManySM_TXNsOnR505(StateMachine_c
.getManySM_SMsOnR517(csms));
assertTrue(
"Did not find a valid number of transitions in the class state machine.",
transitions.length == 4);
BaseTest.dispatchEvents(0);
// delete test project if no failures/errors
// and reset the repository
TestUtil.deleteProject(getProjectHandle(projectName));
BaseTest.dispatchEvents(0);
}
@Test
public void testNoGraphicalDataInCompareEditor() throws CoreException {
BaseTest.dispatchEvents(0);
TestingUtilities.createProject("testNoGraphics");
m_sys = getSystemModel("testNoGraphics");
TestUtil.executeInTransaction(m_sys, "Newpackage", new Object[0]);
Package_c testPackage = Package_c.getOneEP_PKGOnR1401(m_sys);
TestUtil.executeInTransaction(testPackage, "setName",
new Object[] { "testNoGraphics" });
modelRoot = (Ooaofooa) testPackage.getModelRoot();
TestUtil.executeInTransaction(testPackage, "Newexternalentity",
new Object[0]);
BaseTest.dispatchEvents(0);
final ExternalEntity_c ee = ExternalEntity_c
.ExternalEntityInstance(modelRoot);
GraphicalElement_c gElem = GraphicalElement_c.getOneGD_GEOnR1(Model_c
.ModelInstances(Ooaofgraphics.getInstance(modelRoot.getId())),
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((GraphicalElement_c) candidate).getRepresents() == ee;
}
});
CanvasTestUtils.openCanvasEditor(testPackage);
Point shapeCenter = CanvasTestUtils.getShapeCenter(Shape_c
.getOneGD_SHPOnR2(gElem));
CanvasTestUtils.doMousePress(shapeCenter.x, shapeCenter.y);
CanvasTestUtils.doMouseMove(shapeCenter.x + 100, shapeCenter.y + 100);
CanvasTestUtils
.doMouseRelease(shapeCenter.x + 100, shapeCenter.y + 100);
IFile file = ee.getFile();
IFileState[] history = file.getHistory(new NullProgressMonitor());
IFileState state = history[0];
InputStream contents = state.getContents();
IFile copy = file.getProject().getFile(file.getName());
copy.create(contents, true, new NullProgressMonitor());
CompareTestUtilities.compareElementWithLocalHistory(file, copy);
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
List<TreeDifference> leftDifferences = viewer.getDifferencer()
.getLeftDifferences(true);
for (TreeDifference difference : leftDifferences) {
if (!SynchronizedTreeViewer.differenceIsGraphical(difference)) {
fail("Difference found in editor when only graphical differences should be found.");
}
}
}
@Test
public void testValueModificationOfDescriptionThroughCompareDialog()
throws CoreException {
modelRoot = Ooaofooa.getInstance(Ooaofooa.createModelRootId(
getProject(), "Classes", true));
ModelClass_c clazz = ModelClass_c.ModelClassInstance(modelRoot);
Transaction transaction = startTransaction();
clazz.setDescrip("Test Description");
endTransaction(transaction);
CompareTestUtilities.openCompareEditor(clazz.getFile());
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
SynchronizedTreeViewer leftViewer = viewer.getLeftViewer();
ModelCompareContentProvider provider = new ModelCompareContentProvider();
Object[] children = provider.getChildren(clazz);
TreeItem item = SynchronizedTreeViewer.getMatchingItem(
((ITreeDifferencerProvider) leftViewer.getContentProvider())
.getComparableTreeObject(children[3]), leftViewer);
clazz = ModelClass_c.ModelClassInstance(viewer.getLeftCompareRoot());
ObjectElement objEle = (ObjectElement) ((ObjectElementComparable) item
.getData()).getRealElement();
TextualAttributeCompareElementType type = new TextualAttributeCompareElementType(
objEle, leftViewer, true, null, null);
type.setContent("".getBytes());
assertTrue(
"Textual compare dialog did not properly set the value for a class description.",
clazz.getDescrip().equals(""));
}
@Test
public void testAssociationComparable() {
modelRoot = Ooaofooa.getInstance(Ooaofooa.createModelRootId(
getProject(), "Classes", true));
Association_c association = Association_c.AssociationInstance(
modelRoot, new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((Association_c) candidate).getNumb() == 4;
}
});
association.Unformalize();
ClassAsAssociatedOneSide_c oneSide = ClassAsAssociatedOneSide_c
.getOneR_AONEOnR209(LinkedAssociation_c
.getManyR_ASSOCsOnR206(association));
ClassAsAssociatedOtherSide_c otherSide = ClassAsAssociatedOtherSide_c
.getOneR_AOTHOnR210(LinkedAssociation_c
.getManyR_ASSOCsOnR206(association));
AssociationSubtypeComparable comparable1 = new AssociationSubtypeComparable(oneSide);
AssociationSubtypeComparable comparable2 = new AssociationSubtypeComparable(otherSide);
assertTrue(
"A class as associated one side and a class as associated other side were considered identical.",
!comparable1.equals(comparable2));
}
@Test
public void testLocationDetection() throws CoreException {
modelRoot = Ooaofooa.getInstance(Ooaofooa.createModelRootId(
getProject(), "Classes", true));
ModelClass_c clazz = ModelClass_c.ModelClassInstance(modelRoot,
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ModelClass_c) candidate).getName().equals(
"Other");
}
});
Transaction transaction = startTransaction();
clazz.Newattribute();
Attribute_c one = getLastCreatedAttribute(clazz);
one.setRoot_nam("one");
clazz.Newattribute();
Attribute_c two = getLastCreatedAttribute(clazz);
two.setRoot_nam("two");
clazz.Newattribute();
Attribute_c three = getLastCreatedAttribute(clazz);
three.setRoot_nam("three");
clazz.Newoperation();
Operation_c oneOp = getLastCreatedOperation(clazz);
oneOp.setName("one");
clazz.Newoperation();
Operation_c twoOp = getLastCreatedOperation(clazz);
twoOp.setName("two");
clazz.Newoperation();
Operation_c threeOp = getLastCreatedOperation(clazz);
threeOp.setName("three");
endTransaction(transaction);
transaction = startTransaction();
two.Dispose();
twoOp.Dispose();
threeOp.Moveup();
endTransaction(transaction);
// verify all of the difference locations
CompareTestUtilities.openCompareEditor(clazz.getFile(), 0);
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
TreeDifferencer differencer = viewer.getDifferencer();
List<TreeDifference> leftDifferences = differencer.getLeftDifferences(true);
assertTrue(
"Expected four differences and found " + leftDifferences.size(),
leftDifferences.size() == 4);
validateDifference(leftDifferences.get(0));
validateDifference(leftDifferences.get(1));
validateDifference(leftDifferences.get(2));
validateDifference(leftDifferences.get(3));
viewer.setCopySelection(false);
viewer.copy(false);
while (PlatformUI.getWorkbench().getDisplay().readAndDispatch())
;
assertTrue("Not all differences were removed by the copy all button.",
viewer.getDifferencer().getLeftDifferences(true).size() == 0);
clearErrorLogView();
}
@Test
public void testIntegerValueMerge() throws Exception {
Package_c pkg = Package_c.getOneEP_PKGOnR1401(m_sys,
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((Package_c) candidate).getName().equals(
"Classes");
}
});
final Association_c assoc = Association_c
.getOneR_RELOnR8001(PackageableElement_c
.getManyPE_PEsOnR8000(pkg));
Transaction transaction = startTransaction();
assoc.setNumb(22);
endTransaction(transaction);
CompareTestUtilities.openCompareEditor(pkg.getFile());
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
TreeDifferencer differencer = viewer.getDifferencer();
assertEquals("Incorrect number of differences found", differencer
.getLeftDifferences(true).size(), 1);
viewer.setCopySelection(false);
viewer.copy(false);
while (PlatformUI.getWorkbench().getDisplay().readAndDispatch())
;
assertTrue("Not all differences were removed by the copy all button",
viewer.getDifferencer().getLeftDifferences(true).size() == 0);
Association_c compareAssoc = Association_c.AssociationInstance(
viewer.getLeftCompareRoot(), new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((Association_c) candidate).getRel_id().equals(
assoc.getRel_id());
}
});
assertTrue(
"Association number was not updated by the copy difference button.",
compareAssoc.getNumb() != 22);
}
@Test
public void testCantHappenCreationOnNewState() throws Exception {
modelRoot = Ooaofooa.getInstance(Ooaofooa.createModelRootId(
getProject(), "Classes", true));
ModelClass_c clazz = ModelClass_c.ModelClassInstance(modelRoot,
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ModelClass_c) candidate).getName().equals(
"ModelClass");
}
});
InstanceStateMachine_c ism = InstanceStateMachine_c
.getOneSM_ISMOnR518(clazz);
Transaction transaction = startTransaction();
ism.Newstate();
StateMachineState_c[] states = StateMachineState_c
.getManySM_STATEsOnR501(StateMachine_c.getManySM_SMsOnR517(ism));
StateMachineState_c state = states[states.length - 1];
endTransaction(transaction);
transaction = startTransaction();
state.Dispose();
endTransaction(transaction);
CompareTestUtilities.openCompareEditor(ism.getFile());
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
TreeDifferencer differencer = viewer.getDifferencer();
assertTrue("No differences created for state addition.", differencer
.getLeftDifferences(true).size() != 0);
ism = InstanceStateMachine_c.InstanceStateMachineInstance(viewer
.getLeftCompareRoot());
StateMachineEvent_c[] events = StateMachineEvent_c
.getManySM_EVTsOnR502(StateMachine_c.getManySM_SMsOnR517(ism));
int existingSemeCount = 0;
for (StateMachineEvent_c event : events) {
StateEventMatrixEntry_c[] semes = StateEventMatrixEntry_c
.getManySM_SEMEsOnR503(SemEvent_c
.getManySM_SEVTsOnR525(event));
existingSemeCount = existingSemeCount + semes.length;
}
viewer.setCopySelection(false);
viewer.copy(false);
int newSemeCount = 0;
for (StateMachineEvent_c event : events) {
StateEventMatrixEntry_c[] semes = StateEventMatrixEntry_c
.getManySM_SEMEsOnR503(SemEvent_c
.getManySM_SEVTsOnR525(event));
newSemeCount = newSemeCount + semes.length;
}
assertTrue(
"Event matrix entries were not added on merge of a new state.",
newSemeCount > existingSemeCount);
}
@Test
public void testCantHappenCreationOnNewEvent() throws Exception {
modelRoot = Ooaofooa.getInstance(Ooaofooa.createModelRootId(
getProject(), "Classes", true));
ModelClass_c clazz = ModelClass_c.ModelClassInstance(modelRoot,
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ModelClass_c) candidate).getName().equals(
"ModelClass");
}
});
InstanceStateMachine_c ism = InstanceStateMachine_c
.getOneSM_ISMOnR518(clazz);
Transaction transaction = startTransaction();
ism.Newevent();
StateMachineEvent_c[] events = StateMachineEvent_c
.getManySM_EVTsOnR502(StateMachine_c.getManySM_SMsOnR517(ism));
StateMachineEvent_c event = events[events.length - 1];
endTransaction(transaction);
transaction = startTransaction();
event.Dispose();
endTransaction(transaction);
CompareTestUtilities.openCompareEditor(ism.getFile());
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
TreeDifferencer differencer = viewer.getDifferencer();
assertTrue("No differences created for state addition.", differencer
.getLeftDifferences(true).size() != 0);
ism = InstanceStateMachine_c.InstanceStateMachineInstance(viewer
.getLeftCompareRoot());
StateMachineState_c[] states = StateMachineState_c
.getManySM_STATEsOnR501(StateMachine_c.getManySM_SMsOnR517(ism));
int existingSemeCount = 0;
for (StateMachineState_c state : states) {
StateEventMatrixEntry_c[] semes = StateEventMatrixEntry_c
.getManySM_SEMEsOnR503(state);
existingSemeCount = existingSemeCount + semes.length;
}
viewer.setCopySelection(false);
viewer.copy(false);
int newSemeCount = 0;
for (StateMachineState_c state : states) {
StateEventMatrixEntry_c[] semes = StateEventMatrixEntry_c
.getManySM_SEMEsOnR503(state);
newSemeCount = newSemeCount + semes.length;
}
assertTrue(
"Event matrix entries were not added on merge of a new event.",
newSemeCount > existingSemeCount);
}
@Test
public void testUnassignEventFromTransitionMerge() throws Exception {
modelRoot = Ooaofooa.getInstance(Ooaofooa.createModelRootId(
getProject(), "Classes", true));
ModelClass_c clazz = ModelClass_c.ModelClassInstance(modelRoot,
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
return ((ModelClass_c) candidate).getName().equals(
"ModelClass");
}
});
InstanceStateMachine_c ism = InstanceStateMachine_c
.getOneSM_ISMOnR518(clazz);
Transition_c transition = Transition_c.getOneSM_TXNOnR505(
StateMachine_c.getOneSM_SMOnR517(ism),
new ClassQueryInterface_c() {
@Override
public boolean evaluate(Object candidate) {
Transition_c transition = (Transition_c) candidate;
StateEventMatrixEntry_c seme = StateEventMatrixEntry_c
.getOneSM_SEMEOnR504(NewStateTransition_c
.getOneSM_NSTXNOnR507(transition));
return seme != null;
}
});
Transaction transaction = startTransaction();
transition.Removeevent();
endTransaction(transaction);
transaction = startTransaction();
transition.Addevent(
StateMachineEvent_c.getOneSM_EVTOnR502(
StateMachine_c.getOneSM_SMOnR517(ism)).getSmevt_id(),
ism.getSm_id());
endTransaction(transaction);
CompareTestUtilities.openCompareEditor(ism.getFile());
ModelContentMergeViewer viewer = ModelContentMergeViewer
.getInstance(null);
TreeDifferencer differencer = viewer.getDifferencer();
assertTrue("No differences created for event addition.", differencer
.getLeftDifferences(true).size() != 0);
viewer.setCopySelection(false);
viewer.copy(false);
while (PlatformUI.getWorkbench().getDisplay().readAndDispatch())
;
assertTrue(
"Differences were not removed on copy for unassigning an event from a transition",
viewer.getDifferencer().getLeftDifferences(true).size() == 0);
}
@Test
public void testAutocrlfOption() throws Exception {
}
private void validateDifference(TreeDifference difference) {
NonRootModelElement realElement = getRealElement((ComparableTreeObject) difference
.getMatchingDifference().getElement());
if (difference.getElement() == null
&& realElement.getName().equals("two")) {
if (realElement instanceof Attribute_c) {
assertTrue(
"Location was not correctly determined for attribute removal.",
difference.getLocation() == 6);
} else {
assertTrue(
"Location was not correctly deterined for operation removal",
difference.getLocation() == 8);
}
}
}
private NonRootModelElement getRealElement(ComparableTreeObject element) {
return (NonRootModelElement) ((ComparableTreeObject) element)
.getRealElement();
}
private Operation_c getLastCreatedOperation(ModelClass_c clazz) {
Operation_c[] ops = Operation_c.getManyO_TFRsOnR115(clazz);
return ops[ops.length - 1];
}
private Attribute_c getLastCreatedAttribute(ModelClass_c clazz) {
Attribute_c[] attrs = Attribute_c.getManyO_ATTRsOnR102(clazz);
return attrs[attrs.length - 1];
}
}
| 40.064193 | 125 | 0.736957 |
43dd77a283b61717a6ee3dd19cc975aa600bdf0e | 1,797 | /**
*
*/
package com.zimbra.qa.selenium.projects.mobile.ui;
import com.zimbra.qa.selenium.framework.ui.*;
import com.zimbra.qa.selenium.framework.util.HarnessException;
import com.zimbra.qa.selenium.framework.util.ZimbraAccount;
/**
* @author Matt Rhoades
*
*/
public class AppMobileClient extends AbsApplication {
public PageLogin zPageLogin = null;
public PageMain zPageMain = null;
public PageMail zPageMail = null;
public PageContacts zPageContacts = null;
public AppMobileClient() {
super();
logger.info("new " + AppMobileClient.class.getCanonicalName());
// Login page
zPageLogin = new PageLogin(this);
pages.put(zPageLogin.myPageName(), zPageLogin);
// Main page
zPageMain = new PageMain(this);
pages.put(zPageMain.myPageName(), zPageMain);
zPageMail = new PageMail(this);
pages.put(zPageMail.myPageName(), zPageMail);
zPageContacts = new PageContacts(this);
pages.put(zPageContacts.myPageName(), zPageContacts);
// Configure the localization strings
getL10N().zAddBundlename(I18N.Catalog.I18nMsg);
getL10N().zAddBundlename(I18N.Catalog.AjxMsg);
getL10N().zAddBundlename(I18N.Catalog.ZMsg);
getL10N().zAddBundlename(I18N.Catalog.ZsMsg);
getL10N().zAddBundlename(I18N.Catalog.ZmMsg);
}
/* (non-Javadoc)
* @see projects.admin.ui.AbsApplication#isLoaded()
*/
@Override
public boolean zIsLoaded() throws HarnessException {
// TODO: Need to define this method
return (true);
}
/* (non-Javadoc)
* @see projects.admin.ui.AbsApplication#myApplicationName()
*/
@Override
public String myApplicationName() {
return ("Mobile Client");
}
protected ZimbraAccount zSetActiveAcount(ZimbraAccount account) throws HarnessException {
return (super.zSetActiveAcount(account));
}
}
| 24.283784 | 90 | 0.723984 |
9ad9f1271a443853e13eeaae51b52d2b6eb9eceb | 3,247 | package com.dhc.android.testdemoforwzw;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
public class TestSelfView extends android.support.v7.widget.AppCompatTextView {
private Paint mPaint1;
private Paint mPaint2;
private int mViewWidth = 0;
private Paint mPaint;
private LinearGradient mLinearGradient;
private Matrix mGradientMatrix;
private int mTranslate;
public TestSelfView(Context context) {
this(context, null, 0);
}
public TestSelfView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TestSelfView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint1 = new Paint();
mPaint1.setColor(getResources().getColor(android.R.color.holo_blue_light));
mPaint1.setStyle(Paint.Style.FILL);
mPaint2 = new Paint();
mPaint2.setColor(Color.YELLOW);
mPaint2.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint1);
canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, mPaint2);
canvas.save();
canvas.translate(10, 0);
super.onDraw(canvas);
canvas.restore();
if (mGradientMatrix != null) {
mTranslate += mViewWidth / 5;
if (mTranslate > 2 * mViewWidth) {
mTranslate = -mViewWidth;
}
mGradientMatrix.setTranslate(mTranslate,0);
mLinearGradient.setLocalMatrix(mGradientMatrix);
postInvalidateDelayed(100);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(measureWidth(widthMeasureSpec), measureWidth(heightMeasureSpec));
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mViewWidth == 0) {
mViewWidth = getMeasuredWidth();
if (mViewWidth > 0) {
mPaint = getPaint();
mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0, new int[]{Color.BLUE, 0xFFFFFFFF, Color.BLUE}, null, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();
}
}
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = 200;
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
}
| 32.79798 | 150 | 0.640283 |
1c216d8dba7c7101f1bd2921a48b720ef26921e0 | 8,185 | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.jdbc;
import org.elasticsearch.xpack.sql.client.ConnectionConfiguration;
import org.elasticsearch.xpack.sql.client.StringUtils;
import org.elasticsearch.xpack.sql.client.Version;
import java.net.URI;
import java.sql.DriverPropertyInfo;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static org.elasticsearch.xpack.sql.client.UriUtils.parseURI;
import static org.elasticsearch.xpack.sql.client.UriUtils.removeQuery;
/**
/ Supports the following syntax
/
/ jdbc:es://[host|ip]
/ jdbc:es://[host|ip]:port/(prefix)
/ jdbc:es://[host|ip]:port/(prefix)(?options=value&)
/
/ Additional properties can be specified either through the Properties object or in the URL. In case of duplicates, the URL wins.
*/
//TODO: beef this up for Security/SSL
class JdbcConfiguration extends ConnectionConfiguration {
static final String URL_PREFIX = "jdbc:es://";
public static URI DEFAULT_URI = URI.create("http://localhost:9200/");
static final String DEBUG = "debug";
static final String DEBUG_DEFAULT = "false";
static final String DEBUG_OUTPUT = "debug.output";
// can be out/err/url
static final String DEBUG_OUTPUT_DEFAULT = "err";
static final String TIME_ZONE = "timezone";
// follow the JDBC spec and use the JVM default...
// to avoid inconsistency, the default is picked up once at startup and reused across connections
// to cater to the principle of least surprise
// really, the way to move forward is to specify a calendar or the timezone manually
static final String TIME_ZONE_DEFAULT = TimeZone.getDefault().getID();
static final String FIELD_MULTI_VALUE_LENIENCY = "field.multi.value.leniency";
static final String FIELD_MULTI_VALUE_LENIENCY_DEFAULT = "true";
static final String INDEX_INCLUDE_FROZEN = "index.include.frozen";
static final String INDEX_INCLUDE_FROZEN_DEFAULT = "false";
// options that don't change at runtime
private static final Set<String> OPTION_NAMES = new LinkedHashSet<>(
Arrays.asList(TIME_ZONE, FIELD_MULTI_VALUE_LENIENCY, INDEX_INCLUDE_FROZEN, DEBUG, DEBUG_OUTPUT));
static {
// trigger version initialization
// typically this should have already happened but in case the
// EsDriver/EsDataSource are not used and the impl. classes used directly
// this covers that case
Version.CURRENT.toString();
}
// immutable properties
private final boolean debug;
private final String debugOut;
// mutable ones
private ZoneId zoneId;
private boolean fieldMultiValueLeniency;
private boolean includeFrozen;
public static JdbcConfiguration create(String u, Properties props, int loginTimeoutSeconds) throws JdbcSQLException {
URI uri = parseUrl(u);
Properties urlProps = parseProperties(uri, u);
uri = removeQuery(uri, u, DEFAULT_URI);
// override properties set in the URL with the ones specified programmatically
if (props != null) {
urlProps.putAll(props);
}
if (loginTimeoutSeconds > 0) {
urlProps.setProperty(CONNECT_TIMEOUT, Long.toString(TimeUnit.SECONDS.toMillis(loginTimeoutSeconds)));
}
try {
return new JdbcConfiguration(uri, u, urlProps);
} catch (JdbcSQLException e) {
throw e;
} catch (Exception ex) {
throw new JdbcSQLException(ex, ex.getMessage());
}
}
private static URI parseUrl(String u) throws JdbcSQLException {
String url = u;
String format = "jdbc:es://[http|https]?[host[:port]]*/[prefix]*[?[option=value]&]*";
if (!canAccept(u)) {
throw new JdbcSQLException("Expected [" + URL_PREFIX + "] url, received [" + u + "]");
}
try {
return parseURI(removeJdbcPrefix(u), DEFAULT_URI);
} catch (IllegalArgumentException ex) {
throw new JdbcSQLException(ex, "Invalid URL [" + url + "], format should be [" + format + "]");
}
}
private static String removeJdbcPrefix(String connectionString) throws JdbcSQLException {
if (connectionString.startsWith(URL_PREFIX)) {
return connectionString.substring(URL_PREFIX.length());
} else {
throw new JdbcSQLException("Expected [" + URL_PREFIX + "] url, received [" + connectionString + "]");
}
}
private static Properties parseProperties(URI uri, String u) throws JdbcSQLException {
Properties props = new Properties();
try {
if (uri.getRawQuery() != null) {
// parse properties
List<String> prms = StringUtils.tokenize(uri.getRawQuery(), "&");
for (String param : prms) {
List<String> args = StringUtils.tokenize(param, "=");
if (args.size() != 2) {
throw new JdbcSQLException("Invalid parameter [" + param + "], format needs to be key=value");
}
// further validation happens in the constructor (since extra properties might be specified either way)
props.setProperty(args.get(0).trim(), args.get(1).trim());
}
}
} catch (JdbcSQLException e) {
throw e;
} catch (Exception e) {
// Add the url to unexpected exceptions
throw new IllegalArgumentException("Failed to parse acceptable jdbc url [" + u + "]", e);
}
return props;
}
// constructor is private to force the use of a factory in order to catch and convert any validation exception
// and also do input processing as oppose to handling this from the constructor (which is tricky or impossible)
private JdbcConfiguration(URI baseURI, String u, Properties props) throws JdbcSQLException {
super(baseURI, u, props);
this.debug = parseValue(DEBUG, props.getProperty(DEBUG, DEBUG_DEFAULT), Boolean::parseBoolean);
this.debugOut = props.getProperty(DEBUG_OUTPUT, DEBUG_OUTPUT_DEFAULT);
this.zoneId = parseValue(TIME_ZONE, props.getProperty(TIME_ZONE, TIME_ZONE_DEFAULT),
s -> TimeZone.getTimeZone(s).toZoneId().normalized());
this.fieldMultiValueLeniency = parseValue(FIELD_MULTI_VALUE_LENIENCY,
props.getProperty(FIELD_MULTI_VALUE_LENIENCY, FIELD_MULTI_VALUE_LENIENCY_DEFAULT), Boolean::parseBoolean);
this.includeFrozen = parseValue(INDEX_INCLUDE_FROZEN, props.getProperty(INDEX_INCLUDE_FROZEN, INDEX_INCLUDE_FROZEN_DEFAULT),
Boolean::parseBoolean);
}
@Override
protected Collection<String> extraOptions() {
return OPTION_NAMES;
}
ZoneId zoneId() {
return zoneId;
}
public boolean debug() {
return debug;
}
public String debugOut() {
return debugOut;
}
public TimeZone timeZone() {
return zoneId != null ? TimeZone.getTimeZone(zoneId) : null;
}
public boolean fieldMultiValueLeniency() {
return fieldMultiValueLeniency;
}
public boolean indexIncludeFrozen() {
return includeFrozen;
}
public static boolean canAccept(String url) {
return (StringUtils.hasText(url) && url.trim().startsWith(JdbcConfiguration.URL_PREFIX));
}
public DriverPropertyInfo[] driverPropertyInfo() {
List<DriverPropertyInfo> info = new ArrayList<>();
for (String option : optionNames()) {
DriverPropertyInfo prop = new DriverPropertyInfo(option, null);
info.add(prop);
}
return info.toArray(new DriverPropertyInfo[info.size()]);
}
}
| 38.42723 | 132 | 0.666585 |
009999ee2192daafb1a8d6fea60fe1f65cffce9f | 862 | package Screens;
import org.jsfml.graphics.RenderWindow;
import org.jsfml.graphics.Sprite;
import org.jsfml.graphics.Texture;
import java.io.IOException;
import java.nio.file.Paths;
/**
* Created by coco on 14-10-11.
*/
public class cScreen {
public int Run(RenderWindow App){ return 0;}
protected Sprite loadViseur(RenderWindow App){
App.setMouseCursorVisible(false);
Sprite viseur = new Sprite();
Texture texViseur = new Texture();
try {
texViseur.loadFromFile(Paths.get("rsc/img/viseur.png")); // on charge la texture qui se trouve dans notre dossier assets
} catch (IOException e) {
e.printStackTrace();
}
viseur.setTexture(texViseur);
viseur.setOrigin(viseur.getLocalBounds().width/2,viseur.getGlobalBounds().height/2);
return viseur;
}
}
| 26.121212 | 132 | 0.667053 |
d13d61299048c04e24cdbd263dfa46f8a6973470 | 1,790 | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* ____ _ _____ _
* / ___| _ __ _ __(_)_ __ __ |_ _| _ _ __| |__ ___
* \___ \| '_ \| '__| | '_ \ / _` || || | | | '__| '_ \ / _ \
* ___) | |_) | | | | | | | (_| || || |_| | | | |_) | (_) |
* |____/| .__/|_| |_|_| |_|\__, ||_| \__,_|_| |_.__/ \___/
* |_| |___/ https://github.com/yingzhuo/spring-turbo
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
@NonNullApi
@NonNullFields
package spring.turbo.bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.format.FormatterRegistry;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
import org.springframework.lang.Nullable;
import spring.turbo.format.*;
/**
* @author 应卓
* @since 1.0.0
*/
@AutoConfiguration
class SpringBootAutoConfiguration {
@Autowired(required = false)
public SpringBootAutoConfiguration(@Nullable FormatterRegistry registry) {
if (registry != null) {
registry.addConverter(new ResourceOptionConverter());
registry.addConverter(new StringToBooleanConverter());
registry.addConverter(new StringToNumberConverter());
registry.addConverter(new StringToNumberPairConverter());
registry.addConverter(new StringToDatePairConverter());
registry.addConverter(new StringToDayRangeConverter());
registry.addFormatterForFieldAnnotation(new DatePairAnnotationFormatterFactory());
}
}
}
| 42.619048 | 121 | 0.551397 |
d4c9603299d01860720ec535784a5a4ea859cf8d | 2,295 | package com.zemikolon.readingcalculator;
public class ReadingMeter {
public static final int READ_SPEED_SLOW = 100;
public static final int READ_SPEED_AVERAGE = 130;
public static final int READ_SPEED_FAST = 160;
int readSpeed;
int wordCount;
String readContent;
boolean secondsEnable = false;
public ReadingMeter setSpeed(int speed) {
readSpeed = speed;
return this;
}
public ReadingMeter setSecondsEnable(boolean enable) {
secondsEnable = enable;
return this;
}
public ReadingMeter withReadingContent(String content) {
readContent = content;
wordCount = getWordCount(content);
return this;
}
public ReadingMeter withWordCount(int count) {
wordCount = count;
return this;
}
public ReadingMeter withWordCount(long count) {
wordCount = (int) count;
return this;
}
public static int getWordCount(String content) {
int count = 0;
if (null != content && !content.isEmpty()) {
String[] wordArray = content.trim().split("\\s+");
count = wordArray.length;
}
return count;
}
private int getCalculateReadingTime() {
int milliseconds = 0;
if (wordCount > -1) {
float time = (float) wordCount / (float) readSpeed;
milliseconds = (int)(time * 3600);
}
return milliseconds;
}
public long inMilliSeconds() {
return getCalculateReadingTime();
}
public String inString() {
String inString = " ~ min";
int milliseconds = getCalculateReadingTime();
if(milliseconds > 0) {
int seconds = milliseconds / 60;
int minute = seconds / 60;
seconds = seconds % 60;
inString = minute + ":" + String.format("%02d", seconds) + " mins";
if(!secondsEnable) {
if (seconds > 30) {
inString = minute+1 + ":00" + " mins";
}
}
if (minute == 0 && !secondsEnable) {
inString = "1:00 min";
if(seconds <= 30) {
inString = "0:30 min";
}
}
}
return inString;
}
} | 27.321429 | 79 | 0.545534 |
93447533ec69bee1d26af9127e19e7c35d4960ed | 1,556 | package hino.dao.converter;
import hino.common.PokemonAbility;
import java.util.stream.Stream;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class PokemonAbilityConverter implements AttributeConverter<PokemonAbility, String> {
/**
* Converts the value stored in the entity attribute into the data representation to be stored in the database.
*
* @param attribute the entity attribute value to be converted
* @return the converted data to be stored in the database column
*/
@Override
public String convertToDatabaseColumn(PokemonAbility attribute) {
if (attribute == null) {
return null;
}
return attribute.getAbility();
}
/**
* Converts the data stored in the database column into the value to be stored in the entity attribute. Note that it is the responsibility of the
* converter writer to specify the correct <code>dbData</code> type for the corresponding column for use by the JDBC driver: i.e., persistence
* providers are not expected to do such type conversion.
*
* @param dbData the data from the database column to be converted
* @return the converted value to be stored in the entity attribute
*/
@Override
public PokemonAbility convertToEntityAttribute(String dbData) {
if (dbData == null) {
return null;
}
return Stream.of(PokemonAbility.values())
.filter(c -> c.getAbility().equals(dbData))
.findFirst()
.orElseThrow(IllegalArgumentException::new);
}
}
| 34.577778 | 147 | 0.729434 |
1139b152f668fc7db8623dd7bcaa06f46120d291 | 2,838 | /*
Copyright 2019 Samsung SDS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.samsung.sds.brightics.common.core.util;
import org.apache.commons.lang3.StringUtils;
public class FunctionVersion {
public static final FunctionVersion NO_VERSION = new FunctionVersion(0, 0);
public final int major;
public final int minor;
private FunctionVersion(int major, int minor) {
this.major = major;
this.minor = minor;
}
public static FunctionVersion getVersion(String version) {
return parseVersionString(version);
}
public boolean isPreviousThan(String target) {
FunctionVersion targetVersion = parseVersionString(target);
return isPreviousThan(targetVersion);
}
public boolean isPreviousThan(FunctionVersion target) {
if (this.major < target.major) return true;
if (this.major == target.major && this.minor < target.minor) return true;
return false;
}
public boolean isSameWith(String target) {
FunctionVersion targetVersion = parseVersionString(target);
return isSameWith(targetVersion);
}
public boolean isSameWith(FunctionVersion target) {
return this.major == target.major && this.minor == target.minor;
}
public boolean isLaterThan(String target) {
FunctionVersion targetVersion = parseVersionString(target);
return isLaterThan(targetVersion);
}
public boolean isLaterThan(FunctionVersion target) {
if (this.major > target.major) return true;
if (this.major == target.major && this.minor > target.minor) return true;
return false;
}
private static FunctionVersion parseVersionString(String version) {
String[] versionSplit = StringUtils.split(version, ".");
try {
int major = Integer.parseInt(versionSplit[0]);
int minor = versionSplit.length > 1 ? Integer.parseInt(versionSplit[1]) : 0;
return new FunctionVersion(major, minor);
} catch (Exception e) {
return NO_VERSION;
}
}
@Override
public String toString() {
return "FunctionVersion [Major: " + this.major + ", Minor: " + this.minor + "]";
}
}
| 32.62069 | 89 | 0.655743 |
39de739b9a2581899bf57a7f44f541e7bdb0b1f4 | 10,508 | package com.robert.image.compose.demo;
import android.app.Activity;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.com.robert.image.demonew.Config;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.QRCode;
import com.qrcode.r.sdk.QRCodeGenerator;
import com.qrcode.r.sdk.QRCodeOptionsInterface;
import com.qrcode.r.sdk.QRCodePixelOptions;
/**
* Created by michael on 13-12-18.
*/
public class PixelActivity extends Activity {
private ImageView mInImageView;
private ImageView mOutImageView;
private ImageView mInImageView1;
private ImageView mOutImageView1;
private Bitmap mQRCodeBt;
private Bitmap mQRCodeBt1;
private ViewPager mViewPager;
private Handler mHandler = new Handler(Looper.myLooper());
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pixel_activity);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(new PagerAdapter() {
@Override
public int getCount() {
return 2;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
@Override
public Object instantiateItem(View arg0, int pos) {
View ret = getLayoutInflater().inflate(R.layout.pixel_one, null);
switch (pos) {
case 0:
mOutImageView = (ImageView) ret.findViewById(R.id.out);
mInImageView = (ImageView) ret.findViewById(R.id.in);
break;
case 1:
mOutImageView1 = (ImageView) ret.findViewById(R.id.out);
mInImageView1 = (ImageView) ret.findViewById(R.id.in);
break;
}
((ViewPager) arg0).addView(ret);
return ret;
}
});
mInImageView = (ImageView) findViewById(R.id.in);
mOutImageView = (ImageView) findViewById(R.id.out);
asyncLoadImage(Environment.getExternalStorageDirectory() + "/test/test.jpg");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.pixedl, menu);
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
// File outPath = new File("/sdcard/qrcode_image/");
// if (!outPath.exists()) {
// outPath.mkdir();
// }
// Utils.saveBitmapToFile(mQRCodeBt, outPath.getAbsolutePath() + "/pixel.jpg");
new Thread(new Utils.SaveRunnable(getApplicationContext(), mQRCodeBt)).start();
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_LONG).show();
break;
}
return true;
}
private void asyncLoadImage(final String path) {
new Thread(new Runnable() {
@Override
public void run() {
// final Bitmap org = BitmapFactory.decodeFile(path);
final Bitmap org = (Bitmap) ((BitmapDrawable) (getResources().getDrawable(R.drawable.hehua))).getBitmap();
if (org != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
long begin = System.currentTimeMillis();
Log.d("asyncLoadImage", "[[PixelActivity::asyncLoadImage]] BEGIN current time : " + begin);
// Bitmap pixel = QRCodeUtils.mosaic(org, 100);
long end = System.currentTimeMillis();
Log.d("asyncLoadImage", "[[PixelActivity::asyncLoadImage]] END current time : " + end);
Log.d("asyncLoadImage", "[[PixelActivity::asyncLoadImage]] cost : (" + (end - begin) / 1000 + ")s");
mInImageView.setImageBitmap(org);
QRCodePixelOptions opt = new QRCodePixelOptions();
opt.backgroundBitmap = org;
opt.qrCodeRelaeseEffect = QRCodeOptionsInterface.QRCodePixelReleaseEffect.PIXEL;
opt.qrContent = Config.QRCODE_CONTENT;
opt.defaultQRSize = Config.QRCODE_DEFAULT_SIZE;
// opt.errorLevel = ErrorCorrectionLevel;
opt.maskBitmap = (Bitmap) ((BitmapDrawable) (getResources().getDrawable(R.drawable.aaa))).getBitmap();
opt.maskRectCount = 3;
// opt.frontBitmap = (Bitmap) ((BitmapDrawable) (getResources().getDrawable(R.drawable.pre_f_1))).getBitmap();
QRCodeGenerator.createQRCode(opt);
mQRCodeBt = QRCodeGenerator.createQRCode(opt);
mOutImageView.setImageBitmap(mQRCodeBt);
QRCodePixelOptions opt1 = new QRCodePixelOptions();
opt1.backgroundBitmap = org;
opt1.qrCodeRelaeseEffect = QRCodeOptionsInterface.QRCodePixelReleaseEffect.PIXEL_Border;
opt1.qrContent = Config.QRCODE_CONTENT;
opt1.defaultQRSize = Config.QRCODE_DEFAULT_SIZE;
opt1.errorLevel = ErrorCorrectionLevel.M;
// opt1.maskBackground = true;
QRCodeGenerator.createQRCode(opt1);
mQRCodeBt1 = QRCodeGenerator.createQRCode(opt1);
// QRCodePixelOptions opt1 = new QRCodePixelOptions();
// opt1.backgroundBitmap = org;
// opt1.qrCodeRelaeseEffect = QRCodeOptionsInterface.QRCodePixelRelaeseEffect.PIXEL;
// opt1.qrContent = Config.QRCODE_CONTENT;
// opt1.defaultQRSize = Config.QRCODE_DEFAULT_SIZE;
// opt1.preBt = (Bitmap) ((BitmapDrawable) (getResources().getDrawable(R.drawable.pre3))).getBitmap();
// opt1.preSize = 3;
// opt1.preF = (Bitmap) ((BitmapDrawable) (getResources().getDrawable(R.drawable.pre_f))).getBitmap();
mOutImageView1.setImageBitmap(mQRCodeBt1);
mInImageView1.setImageBitmap(org);
}
});
}
}
}).start();
}
private Bitmap makePixelQRCode(String qrContent, Bitmap background, int defaultQRCodeSize) {
//preview bt
Bitmap pre = ((BitmapDrawable) getResources().getDrawable(R.drawable.pre)).getBitmap();
QRCode qrCode = QRCodeUtils.encodeQrcode(qrContent);
ByteMatrix input = qrCode.getMatrix();
if (input == null) {
throw new IllegalStateException();
}
int inputWidth = input.getWidth();
int inputHeight = input.getHeight();
int qrWidth = inputWidth;
int qrHeight = inputHeight;
int outputWidth = Math.max(defaultQRCodeSize, qrWidth);
int outputHeight = Math.max(defaultQRCodeSize, qrHeight);
int multiple = Math.min(outputWidth / qrWidth, outputHeight / qrHeight);
//四周各空两个点整
int realWidth = multiple * (inputWidth + 4);
int realHeight = multiple * (inputHeight + 4);
int leftPadding = multiple * 2;
int topPadding = multiple * 2;
Bitmap pixelBt = QRCodeUtils.mosaic(background, realWidth, realHeight, multiple);
pixelBt.setHasAlpha(true);
Bitmap out = Bitmap.createBitmap(realWidth, realHeight, Bitmap.Config.ARGB_8888);
out.setHasAlpha(true);
Canvas canvas = new Canvas(out);
canvas.drawARGB(200, 255, 255, 255);
Paint paint = new Paint();
paint.setDither(true);
paint.setAntiAlias(true);
paint.setAlpha(150);
ColorMatrix allMatrix = new ColorMatrix();
ColorMatrix colorMatrix = new ColorMatrix();
// //饱和度
colorMatrix.setSaturation(6);
allMatrix.postConcat(colorMatrix);
//对比度
float contrast = (float) (140 / 128.0);
ColorMatrix cMatrix = new ColorMatrix();
cMatrix.set(new float[]{contrast, 0, 0, 0, 0, 0,
contrast, 0, 0, 0,// 改变对比度
0, 0, contrast, 0, 0, 0, 0, 0, 1, 0});
allMatrix.postConcat(cMatrix);
//
paint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
canvas.drawBitmap(pixelBt, 0, 0, paint);
// paint.setAlpha(100);
// Rect preRect = new Rect(0, 0, pre.getWidth(), pre.getHeight());
// canvas.drawBitmap(pre, preRect, new Rect(0, 0, realWidth, realHeight), paint);
paint.setColorFilter(null);
paint.setAlpha(160);
Rect box = new Rect();
for (int inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {
for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {
box.left = outputX;
box.right = outputX + multiple;
box.top = outputY;
box.bottom = outputY + multiple;
if (input.get(inputX, inputY) == 1) {
canvas.drawRect(new Rect(outputX, outputY, outputX + multiple, outputY + multiple), paint);
}
}
}
return out;
}
} | 41.370079 | 137 | 0.568614 |
755d9bd7f75aeb0bb8ecf9483dce992ec85ff741 | 2,260 | package org.treeleaf.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 缓存配置
* <p>
* Created by yaoshuhong on 2015/6/3.
*/
public class CacheConfig {
private static Logger log = LoggerFactory.getLogger(CacheConfig.class);
/**
* 最大等待时间
*/
private int maxWaitmillis;
/**
* 缓存服务器地址
*/
private String host;
/**
* 缓存服务器端口
*/
private int port;
/**
* 缓存服务器密码
*/
private String password;
/**
* 连接池最大数量
*/
private int maxTotal = 8;
/**
* 连接池最大空闲
*/
private int maxIdle = 8;
/**
* 默认采用的cache实现, 0为redis, 1为本地内存
*/
private int type = 0;
/**
* 超时时间,默认10秒
*/
private int timeout = 10000;
private static CacheConfig cacheConfig;
/**
* 初始化方法
*/
public synchronized void init() {
cacheConfig = this;
}
public static CacheConfig getInstance() {
if (cacheConfig == null) {
//到这一步还未初始化就抛错
throw new CacheException("CacheConfig未初始化");
}
return cacheConfig;
}
public int getMaxWaitmillis() {
return maxWaitmillis;
}
public void setMaxWaitmillis(int maxWaitmillis) {
this.maxWaitmillis = maxWaitmillis;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
}
| 16.376812 | 75 | 0.553982 |
b9fcbfb8b2d755303b58858e67b83c4ae4968011 | 1,711 | package com.haiyang.spring.server;/**
* @Author: HaiYang
* @Date: 2020/4/26 15:05
*/
import com.haiyang.spring.init.ServerChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
/**
* @author: Administrator
* @Date: 2020/4/26 15:05
* @Description:
*/
@Slf4j
public class NettyServer {
public void start(InetSocketAddress socketAddress){
//new 一个主线程组
NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
//new 一个工作线程组
NioEventLoopGroup workGroup = new NioEventLoopGroup(200);
ServerBootstrap bootstrap = new ServerBootstrap()
.group(boosGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ServerChannelInitializer())
.localAddress(socketAddress)
//设置队列大小
.option(ChannelOption.SO_BACKLOG, 1024)
// 两小时内没有数据的通信时,TCP会自动发送一个活动探测数据报文
.childOption(ChannelOption.SO_KEEPALIVE, true);
//绑定端口,开始接收进来的连接
try {
ChannelFuture future = bootstrap.bind(socketAddress).sync();
log.info("server start at {}:{}",socketAddress.getAddress(),socketAddress.getPort());
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
| 32.283019 | 97 | 0.655757 |
b11290c31b578a7f1db66a5fee5ad1b1f5c99004 | 1,484 | package com.atguigu.gmall.manage.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.gmall.bean.BaseCatalog1;
import com.atguigu.gmall.bean.BaseCatalog2;
import com.atguigu.gmall.bean.BaseCatalog3;
import com.atguigu.gmall.manage.mapper.BaseCatalog1Mapper;
import com.atguigu.gmall.manage.mapper.BaseCatalog2Mapper;
import com.atguigu.gmall.manage.mapper.BaseCatalog3Mapper;
import com.atguigu.gmall.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
@Service
public class CatalogServiceImpl implements CatalogService {
@Autowired
BaseCatalog1Mapper baseCatalog1Mapper;
@Autowired
BaseCatalog2Mapper baseCatalog2Mapper;
@Autowired
BaseCatalog3Mapper baseCatalog3Mapper;
@Override
public List<BaseCatalog1> getCatalog1() {
List<BaseCatalog1> list = baseCatalog1Mapper.selectAll();
return list;
}
@Override
public List<BaseCatalog2> getCatalog2(String id) {
BaseCatalog2 baseCatalog2 = new BaseCatalog2();
baseCatalog2.setCatalog1Id(id);
List<BaseCatalog2> list = baseCatalog2Mapper.select(baseCatalog2);
return list;
}
@Override
public List<BaseCatalog3> getCatalog3(String id) {
BaseCatalog3 baseCatalog3 = new BaseCatalog3();
baseCatalog3.setCatalog2Id(id);
List<BaseCatalog3> list = baseCatalog3Mapper.select(baseCatalog3);
return list;
}
}
| 30.285714 | 74 | 0.752695 |
445b0a5b731866c9b3b7a7adfa3ce90423caeb2f | 1,127 | package com.example.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class CoolWeatherOpenHelper extends SQLiteOpenHelper{
public CoolWeatherOpenHelper(Context context, String name, CursorFactory factory,
int version){
super (context, name, factory, version);
}
public static final String CREATE_PROVINCE = "create table Province("
+"id integer prinary key autoincrement,"
+"province_name text,"
+"province_code text)";
public static final String CREATE_CITY = "create table Province("
+"id integer prinary key autoincrement,"
+"city_name text,"
+"city_code text)";
public static final String CREATE_COUNTY = "create table Province("
+"id integer prinary key autoincrement,"
+"county_name text,"
+"county_code text)";
@Override
public void onCreate(SQLiteDatabase db){
db.execSQL(CREATE_PROVINCE);
db.execSQL(CREATE_CITY);
db.execSQL(CREATE_COUNTY);
}
@Override
public void onUpgrade(SQLiteDatabase db,int oldversion,int newVersion){
}
}
| 29.657895 | 82 | 0.779059 |
6c07d136f5b5297c5fbd63242942cfa9e0cf09a1 | 3,678 | package br.com.mariani.dao;
import br.com.mariani.connection.ConnectionFactory;
import br.com.mariani.models.Aluguel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author maryucha
*/
public class DaoAluguel {
private final Connection con = ConnectionFactory.getConnection();
/*----------------------------------------------------------*/
public void addLocacao(int id, Aluguel aluguel) throws SQLException {
String sql = "insert into en_aluguel (id_cliente,data_aluguel,valor) values(?,?,?)";
PreparedStatement stm = null;
try {
stm = con.prepareStatement(sql);
stm.setInt(1, aluguel.getClienteId());
stm.setDate(2, aluguel.getDataAluguel());
stm.setDouble(3, aluguel.getValor());
stm.executeUpdate();
} catch (SQLException e) {
System.err.println("Erro ao salvar no banco. " + e);
} finally {
ConnectionFactory.fecharConexao(con, stm);
}
}
/*----------------------------------------------------------*/
public List<Aluguel> listarLocacao() throws SQLException {
String sql = "select * from en_aluguel";
List<Aluguel> list = new ArrayList<>();
PreparedStatement stm = null;
ResultSet rs = null;
try {
stm = con.prepareStatement(sql);
rs = stm.executeQuery();
while (rs.next()) {
Aluguel aluguel = new Aluguel();
aluguel.setId(rs.getInt("id"));
aluguel.setClienteId(rs.getInt("id_cliente"));
aluguel.setDataAluguel(rs.getDate("data_aluguel"));
aluguel.setValor(rs.getDouble("valor"));
list.add(aluguel);
}
} catch (SQLException e) {
System.err.println("Erro ao buscar do banco. " + e);
return null;
} finally {
ConnectionFactory.fecharConexao(con, stm, rs);
}
return list;
}
/*----------------------------------------------------------*/
public Aluguel buscarAluguel(int id) throws SQLException {
String sql = "Select * from en_aluguel where id =?";
PreparedStatement stm = null;
ResultSet rs = null;
Aluguel aluguelBuscado = new Aluguel();
try {
stm = con.prepareStatement(sql);
stm.setInt(1, id);
rs = stm.executeQuery();
if (rs.next()) {
aluguelBuscado.setId(rs.getInt("id"));
aluguelBuscado.setClienteId(rs.getInt("id_cliente"));
aluguelBuscado.setDataAluguel(rs.getDate("data_aluguel"));
aluguelBuscado.setValor(rs.getDouble("valor"));
}
} catch (SQLException e) {
System.err.println("Erro ao buscar do banco. " + e);
return null;
} finally {
ConnectionFactory.fecharConexao(con, stm, rs);
}
return aluguelBuscado;
}
/*----------------------------------------------------------*/
public void removerAluguel(int id) throws SQLException {
String sql = "DELETE FROM en_aluguel WHERE id = ?";
PreparedStatement stm = null;
try {
stm = con.prepareStatement(sql);
stm.setInt(1, id);
stm.executeUpdate();
} catch (SQLException e) {
System.err.println("Deu erro em excluir do banco." + e);
} finally {
ConnectionFactory.fecharConexao(con, stm);
}
}
}
| 32.548673 | 92 | 0.533714 |
90d1ce7af4da3313d22c088702d187f9a65f6e72 | 4,727 | package com.deer.wms.bill.manage.web;
import com.deer.wms.project.seed.annotation.OperateLog;
import com.deer.wms.project.seed.constant.SystemManageConstant;
import com.deer.wms.project.seed.core.result.CommonCode;
import com.deer.wms.project.seed.core.result.Result;
import com.deer.wms.project.seed.core.result.ResultGenerator;
import com.deer.wms.bill.manage.model.MtAloneAuditRelatMb;
import com.deer.wms.bill.manage.model.MtAloneAuditRelatMbParams;
import com.deer.wms.bill.manage.service.MtAloneAuditRelatMbService;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
/**
* Created by gtt on 2019/07/18.
*/
@Api(description = "审核业务模板-关联节点模板接口")
@RestController
@RequestMapping("/mt/alone/audit/relat/mbs")
public class MtAloneAuditRelatMbController {
@Autowired
private MtAloneAuditRelatMbService mtAloneAuditRelatMbService;
@ApiImplicitParams({
@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true) })
@OperateLog(description = "添加关联节点模板", type = "增加")
@ApiOperation(value = "添加关联节点模板", notes = "添加关联节点模板")
@PostMapping("/add")
public Result add(@RequestBody MtAloneAuditRelatMb mtAloneAuditRelatMb, @ApiIgnore @User CurrentUser currentUser) {
if(currentUser==null){
return ResultGenerator.genFailResult( CommonCode.SERVICE_ERROR,"未登录错误",null );
}
mtAloneAuditRelatMb.setCreateTime(new Date());
mtAloneAuditRelatMb.setCompanyId(currentUser.getCompanyId());
mtAloneAuditRelatMbService.save(mtAloneAuditRelatMb);
return ResultGenerator.genSuccessResult();
}
@ApiImplicitParams({
@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true) })
@OperateLog(description = "删除关联节点模板", type = "删除")
@ApiOperation(value = "删除关联节点模板", notes = "删除关联节点模板")
@DeleteMapping("/delete/{id}")
public Result delete(@PathVariable Integer Id) {
mtAloneAuditRelatMbService.deleteById(Id);
return ResultGenerator.genSuccessResult();
}
@ApiImplicitParams({
@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true) })
@OperateLog(description = "修改关联节点模板", type = "更新")
@ApiOperation(value = "修改关联节点模板", notes = "修改关联节点模板")
@PostMapping("/update")
public Result update(@RequestBody MtAloneAuditRelatMb mtAloneAuditRelatMb) {
// mtAloneAuditRelatMb.setUpdateTime(new Date());
mtAloneAuditRelatMbService.update(mtAloneAuditRelatMb);
return ResultGenerator.genSuccessResult();
}
@ApiImplicitParams({
@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true) })
@OperateLog(description = "根据ID获取关联节点模板", type = "获取")
@ApiOperation(value = "根据ID获取关联节点模板", notes = "根据ID获取关联节点模板")
@GetMapping("/detail/{id}")
public Result detail(@PathVariable Integer id) {
MtAloneAuditRelatMb mtAloneAuditRelatMb = mtAloneAuditRelatMbService.findById(id);
return ResultGenerator.genSuccessResult(mtAloneAuditRelatMb);
}
@ApiImplicitParams({
@ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", required = true) })
@OperateLog(description = "根据业务模板ID获取关联节点模板列表", type = "获取")
@ApiOperation(value = "根据业务模板ID获取关联节点模板列表", notes = "根据业务模板ID获取关联节点模板列表")
@GetMapping("/list")
public Result list(MtAloneAuditRelatMbParams params, @ApiIgnore @User CurrentUser currentUser) {
if(currentUser==null){
return ResultGenerator.genFailResult(CommonCode.SERVICE_ERROR,"未登录错误",null );
}
if (currentUser.getCompanyType() != SystemManageConstant.COMPANY_TYPE_MT){
params.setCompanyId(currentUser.getCompanyId());
}else{
params.setCompanyId(null);
}
PageHelper.startPage(params.getPageNum(), params.getPageSize());
List<MtAloneAuditRelatMb> list = mtAloneAuditRelatMbService.findList(params);
PageInfo pageInfo = new PageInfo(list);
return ResultGenerator.genSuccessResult(pageInfo);
}
}
| 45.451923 | 132 | 0.728369 |
0401f530c36789cde99989b2a940f0f4a5a41362 | 578 | package br.com.zup.casadocodigo.infra;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL;
@JsonInclude(NON_NULL)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class ApiErrorReturn {
private final String field;
private final String errorMessage;
public ApiErrorReturn (String field, String errorMessage) {
this.field = field;
this.errorMessage = errorMessage;
}
} | 30.421053 | 77 | 0.757785 |
00de47e804c5b11027afb92b17a06d39bbee2b99 | 2,401 | package com.diamon.nucleo;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
public abstract class Actor implements ImageObserver {
protected int x;
protected int y;
protected Dimension tamano;
protected boolean remover;
private float cuadros;
private float tiempo;
private int frames;
protected BufferedImage[] imagenes;
protected Pantalla pantalla;
protected Animacion animacion;
private boolean animar;
public Actor(Pantalla pantalla) {
this.pantalla = pantalla;
x = 0;
y = 0;
tiempo = 0;
frames = 0;
cuadros = 1;
imagenes = null;
tamano = new Dimension(0, 0);
remover = false;
animar = false;
animacion = null;
}
public void setPosicion(int x, int y) {
this.x = x;
this.y = y;
}
public void setCuadros(float cuadros) {
this.cuadros = cuadros;
}
public void setImagenes(BufferedImage... imagenes) {
this.imagenes = imagenes;
if (imagenes.length > 0) {
animar = true;
}
if (animar) {
animacion = new Animacion(cuadros / Juego.FPS, imagenes);
animacion.setModo(Animacion.REPETIR);
}
}
public boolean isRemover() {
return remover;
}
public void actualizar(float delta) {
if (animar) {
if (delta == 0) {
return;
}
if (delta > 0.1f) {
delta = 0.1f;
}
tiempo += delta;
}
}
public void dibujar(Graphics2D pincel, float delta) {
if (animar) {
if (animacion != null) {
pincel.drawImage(animacion.getKeyFrame(tiempo), x, y, tamano.width, tamano.height, this);
}
} else {
pincel.drawImage(imagenes[frames], x, y, tamano.width, tamano.height, this);
}
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Rectangle getRectangulo() {
return new Rectangle(x, y, tamano.width, tamano.height);
}
public void setTamano(int ancho, int alto) {
tamano.setSize(ancho, alto);
}
public Dimension getTamano() {
return tamano;
}
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int w, int h) {
return (infoflags & (ALLBITS | ABORT)) == 0;
}
public abstract void colision(Actor actor);
public void remover() {
remover = true;
}
}
| 13.338889 | 93 | 0.65556 |
4d629f49fb9d39e178eeaa8b7ce64ad42453758d | 1,170 | package de.gw.auto.domain;
import java.math.BigDecimal;
public class Info {
private String name;
private BigDecimal gesammt = BigDecimal.ZERO;
private BigDecimal diesesJahr = BigDecimal.ZERO;
private BigDecimal vorjahr = BigDecimal.ZERO;
public Info(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getGesammt() {
return gesammt;
}
public void setGesammt(BigDecimal gesammt) {
this.gesammt = gesammt;
}
public BigDecimal getDiesesJahr() {
return diesesJahr;
}
public void setDiesesJahr(BigDecimal diesesJahr) {
this.diesesJahr = diesesJahr;
}
public BigDecimal getVorjahr() {
return vorjahr;
}
public void setVorjahr(BigDecimal vorjahr) {
this.vorjahr = vorjahr;
}
public Vergleich Vergleich(BigDecimal zahl) {
Vergleich v = new Vergleich(zahl);
return v;
}
public Info add(Info info){
Info result = new Info("result");
result.gesammt = this.gesammt.add(info.gesammt);
result.diesesJahr = this.diesesJahr.add(info.diesesJahr);
result.vorjahr = this.vorjahr.add(info.vorjahr);
return result;
}
} | 19.180328 | 59 | 0.721368 |
0d50568291f22e667fefe3fd8a2e371b4f13ee28 | 3,000 | package com.feihua.framework.base.impl;
import com.feihua.framework.base.modules.config.api.ApiBaseConfigService;
import com.feihua.framework.base.modules.oss.cloud.api.ApiCloudStorageService;
import com.feihua.framework.base.modules.oss.cloud.dto.CloudStorageConfig;
import com.feihua.framework.base.modules.oss.cloud.impl.AliyunCloudStorageServiceImpl;
import com.feihua.framework.base.modules.oss.cloud.impl.LocalStorageServiceImpl;
import com.feihua.framework.base.modules.oss.cloud.impl.QcloudCloudStorageServiceImpl;
import com.feihua.framework.base.modules.oss.cloud.impl.QiniuCloudStorageServiceImpl;
import com.feihua.framework.constants.ConfigConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.InputStream;
/**
* @Auther: wzn
* @Date: 2019/2/20 15:27
* @Description: 云存储(支持七牛、阿里云、腾讯云、又拍云)
*/
@Service
public class ApiCloudStorageServiceImpl implements ApiCloudStorageService {
@Autowired
private ApiBaseConfigService apiBaseConfigService;
/**
* 构建云配置对象
*
* @return
*/
private ApiCloudStorageService build() {
CloudStorageConfig config = getConfig();
//获取云存储配置信息
if (ConfigConstant.OSSCloud.QNY.name().equals(config.getType())) {
return new QiniuCloudStorageServiceImpl(config.getQiniu());
} else if (ConfigConstant.OSSCloud.ALY.name().equals(config.getType())) {
return new AliyunCloudStorageServiceImpl(config.getAliyun());
} else if (ConfigConstant.OSSCloud.TXY.name().equals(config.getType())) {
return new QcloudCloudStorageServiceImpl(config.getQcloud());
}else if (ConfigConstant.OSSCloud.LOCAL.name().equals(config.getType())) {
return new LocalStorageServiceImpl(config.getLocal());
}
return null;
}
@Override
public CloudStorageConfig getConfig() {
/** 云存储配置信息 */
CloudStorageConfig config = apiBaseConfigService.getConfigObject(ConfigConstant.ConfigKey.OSS_CLOUD_STORAGE_CONFIG_KEY.name(), CloudStorageConfig.class);
return config;
}
@Override
public String upload(byte[] data, String filepath) {
return this.build().upload(data, filepath);
}
@Override
public String uploadSuffix(byte[] data,String prefixPath, String suffix) {
return this.build().uploadSuffix(data,prefixPath,suffix);
}
@Override
public String upload(InputStream inputStream, String filepath) {
return this.build().upload(inputStream, filepath);
}
@Override
public String uploadSuffix(InputStream inputStream,String prefixPath, String suffix) {
return this.build().uploadSuffix(inputStream,prefixPath,suffix);
}
@Override
public byte[] download(String objectName) {
return this.build().download(objectName);
}
@Override
public int delete(String objectName) {
return this.build().delete(objectName);
}
}
| 35.294118 | 161 | 0.722333 |
bc86ff347e71ef692ad531608ce1036114f15775 | 1,246 | package com.kaciras.blog.infra.autoconfigure;
import com.kaciras.blog.infra.FilterChainCapture;
import org.assertj.core.data.Offset;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.WebApplicationContextRunner;
import javax.servlet.Filter;
import static org.assertj.core.api.Assertions.assertThat;
final class DevelopmentAutoConfigurationTest {
private final WebApplicationContextRunner contextRunner = new WebApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(DevelopmentAutoConfiguration.class));
// 这时间波动也太大了,难道要用 PowerMockito 之类的来 mock Thread.sleep() ?
@Test
void delayFilter() {
contextRunner.withPropertyValues("app.development.http-delay=200ms").run(context -> {
var delayFilter = context.getBean(Filter.class);
// warm up
FilterChainCapture.doFilter((req, res, chain) -> {});
// avoid gc pause in the next
System.gc();
var begin = System.currentTimeMillis();
var capture = FilterChainCapture.doFilter(delayFilter);
var end = System.currentTimeMillis();
assertThat(end - begin).isCloseTo(200, Offset.offset(60L));
assertThat(capture.outRequest).isNotNull();
});
}
}
| 31.948718 | 92 | 0.777689 |
a8e889771c7b5fbe35540a091ce9192fc1e6d5fd | 26,724 | package edu.stanford.nlp.pipeline;
import edu.stanford.nlp.io.FileSequentialCollection;
import edu.stanford.nlp.io.IOUtils;
import edu.stanford.nlp.io.RuntimeIOException;
import edu.stanford.nlp.util.StringUtils;
import edu.stanford.nlp.util.logging.Redwood;
import edu.stanford.nlp.util.logging.StanfordRedwoodConfiguration;
import java.io.*;
import java.net.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static edu.stanford.nlp.util.logging.Redwood.Util.*;
/**
* An annotation pipeline in spirit identical to {@link StanfordCoreNLP}, but
* with the backend supported by a web server.
*
* @author Gabor Angeli
*/
@SuppressWarnings("FieldCanBeLocal")
public class StanfordCoreNLPClient extends AnnotationPipeline {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(StanfordCoreNLPClient.class);
/** A simple URL spec, for parsing backend URLs */
private static final Pattern URL_PATTERN = Pattern.compile("(?:(https?)://)?([^:]+):([0-9]+)?");
/**
* Information on how to connect to a backend.
* The semantics of one of these objects is as follows:
* <ul>
* <li>It should define a hostname and port to connect to.</li>
* <li>This represents ONE thread on the remote server. The client should
* treat it as such.</li>
* <li>Two backends that are .equals() point to the same endpoint, but there can be
* multiple of them if we want to run multiple threads on that endpoint.</li>
* </ul>
*/
private static class Backend {
/** The protocol to connect to the server with. */
public final String protocol;
/** The hostname of the server running the CoreNLP annotators */
public final String host;
/** The port of the server running the CoreNLP annotators */
public final int port;
public Backend(String protocol, String host, int port) {
this.protocol = protocol;
this.host = host;
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Backend)) return false;
Backend backend = (Backend) o;
return port == backend.port && protocol.equals(backend.protocol) && host.equals(backend.host);
}
@Override
public int hashCode() {
throw new IllegalStateException("Hashing backends is dangerous!");
}
@Override
public String toString() {
return protocol + "://" + host + ":" + port;
}
}
/**
* A special type of {@link Thread}, which is responsible for scheduling jobs
* on the backend.
*/
private static class BackendScheduler extends Thread {
/**
* The list of backends that we can schedule on.
* This should not generally be called directly from anywhere
*/
public final List<Backend> backends;
/**
* The queue on requests for the scheduler to handle.
* Each element of this queue is a function: calling the function signals
* that this backend is available to perform a task on the passed backend.
* It is then obligated to call the passed Consumer to signal that it has
* released control of the backend, and it can be used for other things.
* Remember to lock access to this object with {@link BackendScheduler#stateLock}.
*/
private final Queue<BiConsumer<Backend, Consumer<Backend>>> queue;
/**
* The lock on access to {@link BackendScheduler#queue}.
*/
private final Lock stateLock = new ReentrantLock();
/**
* Represents the event that an item has been added to the work queue.
* Linked to {@link BackendScheduler#stateLock}.
*/
private final Condition enqueued = stateLock.newCondition();
/**
* Represents the event that the queue has become empty, and this schedule is no
* longer needed.
*/
public final Condition shouldShutdown = stateLock.newCondition();
/**
* The queue of annotators (backends) that are free to be run on.
* Remember to lock access to this object with {@link BackendScheduler#stateLock}.
*/
private final Queue<Backend> freeAnnotators;
/**
* Represents the event that an annotator has freed up and is available for
* work on the {@link BackendScheduler#freeAnnotators} queue.
* Linked to {@link BackendScheduler#stateLock}.
*/
private final Condition newlyFree = stateLock.newCondition();
/**
* While this is true, continue running the scheduler.
*/
private boolean doRun = true;
/**
* Create a new scheduler from a list of backends.
* These can contain duplicates -- in that case, that many concurrent
* calls can be made to that backend.
*/
public BackendScheduler(List<Backend> backends) {
super();
setDaemon(true);
this.backends = backends;
this.freeAnnotators = new LinkedList<>(backends);
this.queue = new LinkedList<>();
}
/** {@inheritDoc} */
@Override
public void run() {
try {
while (doRun) {
// Wait for a request
BiConsumer<Backend, Consumer<Backend>> request;
Backend annotator;
stateLock.lock();
try {
while (queue.isEmpty()) {
enqueued.await();
if (!doRun) {
return;
}
}
// Get the actual request
request = queue.poll();
// We have a request
// Find a free annotator
while (freeAnnotators.isEmpty()) {
newlyFree.await();
}
annotator = freeAnnotators.poll();
} finally {
stateLock.unlock();
}
// We have an annotator
// Run the annotation
request.accept(annotator, freedAnnotator -> {
// ASYNC: we've freed this annotator
// add it back to the queue and register it as available
stateLock.lock();
try {
freeAnnotators.add(freedAnnotator);
// If the queue is empty, and all the annotators have returned, we're done
if (queue.isEmpty() && freeAnnotators.size() == backends.size()) {
log.info("All annotations completed. Signaling for shutdown");
shouldShutdown.signalAll();
}
newlyFree.signal();
} finally {
stateLock.unlock();
}
});
// Annotator is running (in parallel, most likely)
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
/**
* Schedule a new job on the backend
* @param annotate A callback, which will be called when a backend is free
* to do some processing. The implementation of this callback
* MUST CALL the second argument when it is done processing,
* to register the backend as free for further work.
*/
public void schedule(BiConsumer<Backend, Consumer<Backend>> annotate) {
stateLock.lock();
try {
queue.add(annotate);
enqueued.signal();
} finally {
stateLock.unlock();
}
}
} // end static class BackEndScheduler
/** The path on the server to connect to. */
private final String path = "";
/** The Properties file to annotate with. */
private final Properties properties;
/** The Properties file to send to the server, serialized as JSON. */
private final String propsAsJSON;
/** The API key to authenticate with, or null */
private final String apiKey;
/** The API secret to authenticate with, or null */
private final String apiSecret;
/** The scheduler to use when running on multiple backends at a time */
private final BackendScheduler scheduler;
/**
* The annotation serializer responsible for translating between the wire format
* (protocol buffers) and the {@link Annotation} classes.
*/
private final ProtobufAnnotationSerializer serializer = new ProtobufAnnotationSerializer(true);
/**
* The main constructor. Create a client from a properties file and a list of backends.
* Note that this creates at least one Daemon thread.
*
* @param properties The properties file, as would be passed to {@link StanfordCoreNLP}.
* @param backends The backends to run on.
* @param apiKey The key to authenticate with as a username
* @param apiSecret The key to authenticate with as a password
*/
private StanfordCoreNLPClient(Properties properties, List<Backend> backends,
String apiKey, String apiSecret) {
// Save the constructor variables
this.properties = properties;
Properties serverProperties = new Properties();
for (String key : properties.stringPropertyNames()) {
serverProperties.setProperty(key, properties.getProperty(key));
}
Collections.shuffle(backends, new Random(System.currentTimeMillis()));
this.scheduler = new BackendScheduler(backends);
this.apiKey = apiKey;
this.apiSecret = apiSecret;
// Set required serverProperties
serverProperties.setProperty("inputFormat", "serialized");
serverProperties.setProperty("outputFormat", "serialized");
serverProperties.setProperty("inputSerializer", ProtobufAnnotationSerializer.class.getName());
serverProperties.setProperty("outputSerializer", ProtobufAnnotationSerializer.class.getName());
// Create a list of all the properties, as JSON map elements
List<String> jsonProperties = serverProperties.stringPropertyNames().stream().map(key -> '"' + JSONOutputter.cleanJSON(key) + "\": \"" +
JSONOutputter
.cleanJSON(serverProperties.getProperty(key)) + '"')
.collect(Collectors.toList());
// Create the JSON object
this.propsAsJSON = "{ " + StringUtils.join(jsonProperties, ", ") + " }";
// Start 'er up
this.scheduler.start();
}
/**
* The main constructor without credentials.
*
* @see StanfordCoreNLPClient#StanfordCoreNLPClient(Properties, List, String, String)
*/
private StanfordCoreNLPClient(Properties properties, List<Backend> backends) {
this(properties, backends, null, null);
}
/**
* Run the client, pulling credentials from the environment.
* Throws an IllegalStateException if the required environment variables aren't set.
* These are:
*
* <ul>
* <li>CORENLP_HOST</li>
* <li>CORENLP_KEY</li>
* <li>CORENLP_SECRET</li>
* </ul>
*
* @throws IllegalStateException Thrown if we could not read the required environment variables.
*/
@SuppressWarnings("unused")
public StanfordCoreNLPClient(Properties properties) throws IllegalStateException {
this(properties,
Optional.ofNullable(System.getenv("CORENLP_HOST")).orElseThrow(() -> new IllegalStateException("Environment variable CORENLP_HOST not specified")),
Optional.ofNullable(System.getenv("CORENLP_HOST")).map(x -> x.startsWith("http://") ? 80 : 443).orElse(443),
1,
Optional.ofNullable(System.getenv("CORENLP_KEY")).orElse(null),
Optional.ofNullable(System.getenv("CORENLP_SECRET")).orElse(null)
);
}
/**
* Run on a single backend.
*
* @see StanfordCoreNLPClient (Properties, List)
*/
@SuppressWarnings("unused")
public StanfordCoreNLPClient(Properties properties, String host, int port) {
this(properties, host, port, 1);
}
/**
* Run on a single backend, with authentication
*
* @see StanfordCoreNLPClient (Properties, List)
*/
@SuppressWarnings("unused")
public StanfordCoreNLPClient(Properties properties, String host, int port,
String apiKey, String apiSecret) {
this(properties, host, port, 1, apiKey, apiSecret);
}
/**
* Run on a single backend, with authentication
*
* @see StanfordCoreNLPClient (Properties, List)
*/
@SuppressWarnings("unused")
public StanfordCoreNLPClient(Properties properties, String host,
String apiKey, String apiSecret) {
this(properties, host, host.startsWith("http://") ? 80 : 443, 1, apiKey, apiSecret);
}
/**
* Run on a single backend, but with k threads on each backend.
*
* @see StanfordCoreNLPClient (Properties, List)
*/
@SuppressWarnings("unused")
public StanfordCoreNLPClient(Properties properties, String host, int port, int threads) {
this(properties, host, port, threads, null, null);
}
/**
* Run on a single backend, but with k threads on each backend, and with authentication
*
* @see StanfordCoreNLPClient (Properties, List)
*/
public StanfordCoreNLPClient(Properties properties, String host, int port, int threads,
String apiKey, String apiSecret) {
this(properties, new ArrayList<Backend>() {{
for (int i = 0; i < threads; ++i) {
add(new Backend(host.startsWith("http://") ? "http" : "https",
host.startsWith("http://") ? host.substring("http://".length()) : (host.startsWith("https://") ? host.substring("https://".length()) : host),
port));
}
}},
apiKey, apiSecret);
}
/**
* {@inheritDoc}
*
* This method creates an async call to the server, and blocks until the server
* has finished annotating the object.
*/
@Override
public void annotate(Annotation annotation) {
final Lock lock = new ReentrantLock();
final Condition annotationDone = lock.newCondition();
annotate(Collections.singleton(annotation), 1, (Annotation annInput) -> {
try {
lock.lock();
annotationDone.signal();
} finally {
lock.unlock();
}
});
try {
lock.lock();
annotationDone.await(); // Only wait for one callback to complete; only annotating one document
} catch (InterruptedException e) {
log.info("Interrupt while waiting for annotation to return");
} finally {
lock.unlock();
}
}
/**
* This method fires off a request to the server. Upon returning, it calls the provided
* callback method.
*
* @param annotations The input annotations to process
* @param numThreads The number of threads to run on. IGNORED in this class.
* @param callback A function to be called when an annotation finishes.
*/
@Override
public void annotate(final Iterable<Annotation> annotations, int numThreads, final Consumer<Annotation> callback){
for (Annotation annotation : annotations) {
annotate(annotation, callback);
}
}
/**
* The canonical entry point of the client annotator.
* Create an HTTP request, send this annotation to the server, and await a response.
*
* @param annotation The annotation to annotate.
* @param callback Called when the server has returned an annotated document.
* The input to this callback is the same as the passed Annotation object.
*/
public void annotate(final Annotation annotation, final Consumer<Annotation> callback) {
scheduler.schedule((Backend backend, Consumer<Backend> isFinishedCallback) -> new Thread(() -> {
try {
// 1. Create the input
// 1.1 Create a protocol buffer
ByteArrayOutputStream os = new ByteArrayOutputStream();
serializer.write(annotation, os);
os.close();
byte[] message = os.toByteArray();
// 1.2 Create the query params
String queryParams = String.format(
"properties=%s",
URLEncoder.encode(StanfordCoreNLPClient.this.propsAsJSON, "utf-8"));
// 2. Create a connection
URL serverURL = new URL(backend.protocol, backend.host,
backend.port,
StanfordCoreNLPClient.this.path + '?' + queryParams);
// 3. Do the annotation
// This method has two contracts:
// 1. It should call the two relevant callbacks
// 2. It must not throw an exception
doAnnotation(annotation, backend, serverURL, message, 0);
} catch (Throwable t) {
log.warn("Could not annotate via server! Trying to annotate locally...", t);
StanfordCoreNLP corenlp = new StanfordCoreNLP(properties);
corenlp.annotate(annotation);
} finally {
callback.accept(annotation);
isFinishedCallback.accept(backend);
}
}).start());
}
/**
* Actually try to perform the annotation on the server side.
* This is factored out so that we can retry up to 3 times.
*
* @param annotation The annotation we need to fill.
* @param backend The backend we are querying against.
* @param serverURL The URL of the server we are hitting.
* @param message The message we are sending the server (don't need to recompute each retry).
* @param tries The number of times we've tried already.
*/
@SuppressWarnings("unchecked")
private void doAnnotation(Annotation annotation, Backend backend, URL serverURL, byte[] message, int tries) {
try {
// 1. Set up the connection
URLConnection connection = serverURL.openConnection();
// 1.1 Set authentication
if (apiKey != null && apiSecret != null) {
String userpass = apiKey + ":" + apiSecret;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
connection.setRequestProperty("Authorization", basicAuth);
}
// 1.2 Set some protocol-independent properties
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-protobuf");
connection.setRequestProperty("Content-Length", Integer.toString(message.length));
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("User-Agent", StanfordCoreNLPClient.class.getName());
// 1.3 Set some protocol-dependent properties
switch (backend.protocol) {
case "https":
case "http":
((HttpURLConnection) connection).setRequestMethod("POST");
break;
default:
throw new IllegalStateException("Haven't implemented protocol: " + backend.protocol);
}
// 2. Annotate
// 2.1. Fire off the request
connection.connect();
connection.getOutputStream().write(message);
connection.getOutputStream().flush();
// 2.2 Await a response
// -- It might be possible to send more than one message, but we are not going to do that.
Annotation response = serializer.read(connection.getInputStream()).first;
// 2.3. Copy response over to original annotation
for (Class key : response.keySet()) {
annotation.set(key, response.get(key));
}
} catch (Throwable t) {
// 3. We encountered an error -- retry
if (tries < 3) {
log.warn(t);
doAnnotation(annotation, backend, serverURL, message, tries + 1);
} else {
throw new RuntimeException(t);
}
}
}
/**
* Runs the entire pipeline on the content of the given text passed in.
* @param text The text to process
* @return An Annotation object containing the output of all annotators
*/
public Annotation process(String text) {
Annotation annotation = new Annotation(text);
annotate(annotation);
return annotation;
}
/**
* Runs an interactive shell where input text is processed with the given pipeline.
*
* @param pipeline The pipeline to be used
* @throws IOException If IO problem with stdin
*/
private static void shell(StanfordCoreNLPClient pipeline) throws IOException {
log.info("Entering interactive shell. Type q RETURN or EOF to quit.");
final StanfordCoreNLP.OutputFormat outputFormat = StanfordCoreNLP.OutputFormat.valueOf(pipeline.properties.getProperty("outputFormat", "text").toUpperCase());
IOUtils.console("NLP> ", line -> {
if ( ! line.isEmpty()) {
Annotation anno = pipeline.process(line);
try {
switch (outputFormat) {
case XML:
new XMLOutputter().print(anno, System.out);
break;
case JSON:
new JSONOutputter().print(anno, System.out);
System.out.println();
break;
case CONLL:
new CoNLLOutputter().print(anno, System.out);
System.out.println();
break;
case TEXT:
new TextOutputter().print(anno, System.out);
break;
case SERIALIZED:
warn("You probably cannot read the serialized output, so printing in text instead");
new TextOutputter().print(anno, System.out);
break;
default:
throw new IllegalArgumentException("Cannot output in format " + outputFormat + " from the interactive shell");
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
});
}
/**
* The implementation of what to run on a command-line call of CoreNLPWebClient
*
* @throws IOException If any IO problem
*/
public void run() throws IOException {
StanfordRedwoodConfiguration.minimalSetup();
StanfordCoreNLP.OutputFormat outputFormat = StanfordCoreNLP.OutputFormat.valueOf(properties.getProperty("outputFormat", "text").toUpperCase());
//
// Process one file or a directory of files
//
if (properties.containsKey("file") || properties.containsKey("textFile")) {
String fileName = properties.getProperty("file");
if (fileName == null) {
fileName = properties.getProperty("textFile");
}
Collection<File> files = new FileSequentialCollection(new File(fileName), properties.getProperty("extension"), true);
StanfordCoreNLP.processFiles(null, files, 1, properties, this::annotate,
StanfordCoreNLP.createOutputter(properties, new AnnotationOutputter.Options()), outputFormat);
}
//
// Process a list of files
//
else if (properties.containsKey("filelist")){
String fileName = properties.getProperty("filelist");
Collection<File> inputFiles = StanfordCoreNLP.readFileList(fileName);
Collection<File> files = new ArrayList<>(inputFiles.size());
for (File file : inputFiles) {
if (file.isDirectory()) {
files.addAll(new FileSequentialCollection(new File(fileName), properties.getProperty("extension"), true));
} else {
files.add(file);
}
}
StanfordCoreNLP.processFiles(null, files, 1, properties, this::annotate,
StanfordCoreNLP.createOutputter(properties, new AnnotationOutputter.Options()), outputFormat);
}
//
// Run the interactive shell
//
else {
shell(this);
}
}
/**
* <p>
* Good practice to call after you are done with this object.
* Shuts down the queue of annotations to run and the associated threads.
* </p>
*
* <p>
* If this is not called, any job which has been scheduled but not run will be
* cancelled.
* </p>
*/
public void shutdown() throws InterruptedException {
scheduler.stateLock.lock();
try {
while (!scheduler.queue.isEmpty() || scheduler.freeAnnotators.size() != scheduler.backends.size()) {
scheduler.shouldShutdown.await(5, TimeUnit.SECONDS);
}
scheduler.doRun = false;
scheduler.enqueued.signalAll(); // In case the thread's waiting on this condition
} finally {
scheduler.stateLock.unlock();
}
}
/**
* This can be used just for testing or for command-line text processing.
* This runs the pipeline you specify on the
* text in the file that you specify and sends some results to stdout.
* The current code in this main method assumes that each line of the file
* is to be processed separately as a single sentence.
* <p>
* Example usage:<br>
* java -mx6g edu.stanford.nlp.pipeline.StanfordCoreNLP -props properties -backends site1:port1,site2,port2 <br>
* or just -host name -port number
*
* @param args List of required properties
* @throws java.io.IOException If IO problem
* @throws ClassNotFoundException If class loading problem
*/
public static void main(String[] args) throws IOException, ClassNotFoundException {
//
// process the arguments
//
// extract all the properties from the command line
// if cmd line is empty, set the properties to null. The processor will search for the properties file in the classpath
// if (args.length < 2) {
// log.info("Usage: " + StanfordCoreNLPClient.class.getSimpleName() + " -host <hostname> -port <port> ...");
// System.exit(1);
// }
Properties props = StringUtils.argsToProperties(args);
boolean hasH = props.containsKey("h");
boolean hasHelp = props.containsKey("help");
if (hasH || hasHelp) {
String helpValue = hasH ? props.getProperty("h") : props.getProperty("help");
StanfordCoreNLP.printHelp(System.err, helpValue);
return;
}
// Create the backends
List<Backend> backends = new ArrayList<>();
String defaultBack = "http://localhost:9000";
String backStr = props.getProperty("backends");
if (backStr == null) {
String host = props.getProperty("host");
String port = props.getProperty("port");
if (host != null) {
if (port != null) {
defaultBack = host + ':' + port;
} else {
defaultBack = host;
}
}
}
for (String spec : props.getProperty("backends", defaultBack).split(",")) {
Matcher matcher = URL_PATTERN.matcher(spec.trim());
if (matcher.matches()) {
String protocol = matcher.group(1);
if (protocol == null) {
protocol = "http";
}
String host = matcher.group(2);
int port = 80;
String portStr = matcher.group(3);
if (portStr != null) {
port = Integer.parseInt(portStr);
}
backends.add(new Backend(protocol, host, port));
}
}
log.info("Using backends: " + backends);
// Run the pipeline
StanfordCoreNLPClient client = new StanfordCoreNLPClient(props, backends);
client.run();
try {
client.shutdown(); // In case anything is pending on the server
} catch (InterruptedException ignored) { }
} // end main()
}
| 36.359184 | 162 | 0.64661 |
886d12f75fc8f2ce31deb47b041331a588f83155 | 384 | package test.org.oss.junit.stoptestsuite;
import static org.junit.Assert.assertFalse;
import org.junit.BeforeClass;
import org.junit.Test;
public class StopOnFirstFailureTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
assertFalse(false);
}
@Test(expected=AssertionError.class)
public void testStopOnFirstFailure() {
assertFalse(true);
}
}
| 18.285714 | 57 | 0.78125 |
cf47f541cf3ace006574f8257276e0efa242d2b5 | 458 | package ch.awae.datasocket;
import java.util.Map;
class TypedMapping<V> {
private final Map<Class<?>, V> map;
TypedMapping(Map<Class<?>, V> map) {
this.map = map;
}
V get(Class<?> tClass) {
return map.entrySet()
.stream()
.filter(entry -> entry.getKey().isAssignableFrom(tClass))
.findAny()
.map(Map.Entry::getValue)
.orElse(null);
}
}
| 19.913043 | 73 | 0.510917 |
16de99814cb438efcbd8bb9ca7f64464cdc3f79d | 1,908 | package dk.statsbiblioteket.user.tra.apt;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
/**
* <p>
* ConfigurationMap holds a map of string to string (i.e. the general form
* of java properties). The toString() method list the keys in alphabetical order.
* </p>
*/
public class ConfigurationMap extends TreeMap<String, String> {
/**
* Adds those system properties with the provided keys that actually exist (value != null) to the configuration map.
*/
public void addSystemProperties(String... propertyKeys) {
for (String key : propertyKeys) {
String value = System.getProperty(key);
if (value != null) {
this.put(key, value);
}
}
}
/**
* EventAdderValuePutter those environment variables with the provided keys that actually exist (value != null) to the configuration map.
*/
public void addEnvironmentVariables(String... variableKeys) {
for (String key : variableKeys) {
String value = System.getenv(key);
if (value != null) {
this.put(key, value);
}
}
}
/**
* Buffers the reader, reads in the entries, and add them to the configuration map. The reader is closed afterwards. Values (but not keys) are trimmed.
*/
public void addPropertyFile(Reader reader) throws IOException {
Properties p = new Properties();
try (BufferedReader bufferedReader = new BufferedReader(reader)) {
p.load(bufferedReader);
}
for (Map.Entry<Object, Object> entry : p.entrySet()) {
String key = String.valueOf(entry.getKey());
String value = String.valueOf(entry.getValue()).trim();
this.put(key, value);
}
}
}
| 31.278689 | 157 | 0.624214 |
c77d4f94036945cd11d89a0893d23ca1bd8acc12 | 2,437 | /**
* commons - Various Java Utils
* Copyright (C) 2009 Adrian Cristian Ionescu - https://github.com/acionescu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.segoia.util.data;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
public class LfuSet implements Set{
/**
*
*/
private static final long serialVersionUID = 3899301974769690116L;
private int maxSize;
private TreeMap treeMap;
public LfuSet(){
}
public LfuSet(int maxSize){
this.maxSize = maxSize;
}
public boolean add(Object arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean addAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public void clear() {
// TODO Auto-generated method stub
}
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
public boolean containsAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
public Iterator iterator() {
// TODO Auto-generated method stub
return null;
}
public boolean remove(Object o) {
// TODO Auto-generated method stub
return false;
}
public boolean removeAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public boolean retainAll(Collection arg0) {
// TODO Auto-generated method stub
return false;
}
public int size() {
// TODO Auto-generated method stub
return 0;
}
public Object[] toArray() {
// TODO Auto-generated method stub
return null;
}
public Object[] toArray(Object[] arg0) {
// TODO Auto-generated method stub
return null;
}
}
final class LfuComparator implements Comparator{
public int compare(Object arg0, Object arg1) {
// TODO Auto-generated method stub
return 0;
}
}
| 21.008621 | 77 | 0.712762 |
2cddabe44a1a90faaefee635eb8c21f83769eb9d | 2,792 | /**
* Copyright 2007 The Apache Software Foundation
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.rest.descriptors;
/**
*
*/
public class ScannerDescriptor {
byte[][] columns;
long timestamp;
byte[] startRow;
byte[] stopRow;
String filters;
/**
* @param columns
* @param timestamp
* @param startRow
* @param stopRow
* @param filters
*/
public ScannerDescriptor(byte[][] columns, long timestamp, byte[] startRow,
byte[] stopRow, String filters) {
super();
this.columns = columns;
this.timestamp = timestamp;
this.startRow = startRow;
this.stopRow = stopRow;
this.filters = filters;
if(this.startRow == null) {
this.startRow = new byte[0];
}
if(this.stopRow == null) {
this.stopRow = new byte[0];
}
}
/**
* @return the columns
*/
public byte[][] getColumns() {
return columns;
}
/**
* @param columns
* the columns to set
*/
public void setColumns(byte[][] columns) {
this.columns = columns;
}
/**
* @return the timestamp
*/
public long getTimestamp() {
return timestamp;
}
/**
* @param timestamp
* the timestamp to set
*/
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
/**
* @return the startRow
*/
public byte[] getStartRow() {
return startRow;
}
/**
* @param startRow
* the startRow to set
*/
public void setStartRow(byte[] startRow) {
this.startRow = startRow;
}
/**
* @return the stopRow
*/
public byte[] getStopRow() {
return stopRow;
}
/**
* @param stopRow
* the stopRow to set
*/
public void setStopRow(byte[] stopRow) {
this.stopRow = stopRow;
}
/**
* @return the filters
*/
public String getFilters() {
return filters;
}
/**
* @param filters
* the filters to set
*/
public void setFilters(String filters) {
this.filters = filters;
}
} | 21.476923 | 77 | 0.628223 |
f7a67a68ea544fa820233afffa79044287fd86f4 | 1,580 | package org.apereo.cas.configuration.model.support.hazelcast;
import org.apereo.cas.configuration.model.core.util.EncryptionRandomizedSigningJwtCryptographyProperties;
import org.apereo.cas.configuration.support.RequiredModule;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
/**
* Encapsulates hazelcast properties exposed by CAS via properties file property source in a type-safe manner.
*
* @author Dmitriy Kopylenko
* @since 4.2.0
*/
@RequiredModule(name = "cas-server-support-hazelcast-ticket-registry")
public class HazelcastTicketRegistryProperties extends BaseHazelcastProperties {
private static final long serialVersionUID = -1095208036374406772L;
/**
* Page size is used by a special Predicate which helps to get a page-by-page result of a query.
*/
private int pageSize = 500;
/**
* Crypto settings for the registry.
*/
@NestedConfigurationProperty
private EncryptionRandomizedSigningJwtCryptographyProperties crypto = new EncryptionRandomizedSigningJwtCryptographyProperties();
public HazelcastTicketRegistryProperties() {
this.crypto.setEnabled(false);
}
public EncryptionRandomizedSigningJwtCryptographyProperties getCrypto() {
return crypto;
}
public void setCrypto(final EncryptionRandomizedSigningJwtCryptographyProperties crypto) {
this.crypto = crypto;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(final int pageSize) {
this.pageSize = pageSize;
}
}
| 32.244898 | 133 | 0.749367 |
7d2e3c3573de901798ce89ea59c27f7b7f635710 | 4,393 | /*-
* ========================LICENSE_START=================================
* pgSqlBlocks
* %
* Copyright (C) 2017 - 2018 "Technology" LLC
* %
* 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.
* =========================LICENSE_END==================================
*/
package ru.taximaxim.treeviewer.filter;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;
import ru.taximaxim.treeviewer.utils.TriFunction;
/**
* Enum for types of column filters
*/
enum FilterOperation {
NONE("", (o, s, t) -> true),
EQUALS("=", FilterOperation::equalsByType),
NOT_EQUALS("!=", (o, s, t) -> !EQUALS.matchesForType(o, s, t)),
CONTAINS("~", (o, s, t) -> o.toLowerCase().contains(s.toLowerCase())),
GREATER(">", FilterOperation::greater),
GREATER_OR_EQUAL(">=", (o, s, t) -> EQUALS.matchesForType(o, s, t) || GREATER.matchesForType(o, s, t)),
LESS("<", FilterOperation::less),
LESS_OR_EQUAL("<=", (o, s, t) -> EQUALS.matchesForType(o, s, t) || LESS.matchesForType(o, s, t));
private final String conditionText;
private final TriFunction<String, String, ColumnType, Boolean> matcherFunction;
FilterOperation(String conditionText, TriFunction<String, String, ColumnType, Boolean> matcherFunction) {
this.conditionText = conditionText;
this.matcherFunction = matcherFunction;
}
boolean matchesForType(String objectValue, String searchValue, ColumnType columnType) {
return matcherFunction.apply(objectValue, searchValue, columnType);
}
@Override
public String toString() {
return conditionText;
}
public String getConditionText() {
return conditionText;
}
public static FilterOperation find(String text) {
FilterOperation[] list = FilterOperation.values();
for (FilterOperation filterOperation : list) {
if (filterOperation.getConditionText().equals(text)) {
return filterOperation;
}
}
return FilterOperation.NONE;
}
private static boolean equalsByType(String objectValue, String searchValue, ColumnType columnType) {
switch (columnType) {
case INTEGER:
return matches(objectValue, searchValue, FilterOperation::getInteger, Integer::equals);
case DATE:
case STRING:
return objectValue.equals(searchValue);
}
return false;
}
private static boolean greater(String objectValue, String searchValue, ColumnType columnType) {
switch (columnType) {
case INTEGER:
return matches(objectValue, searchValue, FilterOperation::getInteger, (i1, i2) -> i1 > i2);
case DATE:
case STRING:
return objectValue.compareTo(searchValue) > 0;
}
return false;
}
private static boolean less(String objectValue, String searchValue, ColumnType columnType) {
switch (columnType) {
case INTEGER:
return matches(objectValue, searchValue, FilterOperation::getInteger, (i1, i2) -> i1 < i2);
case DATE:
case STRING:
return objectValue.compareTo(searchValue) < 0;
}
return false;
}
private static <T> boolean matches(String objectValue, String searchValue,
Function<String, Optional<T>> converter, BiFunction<T, T, Boolean> matcher) {
Optional<T> objectOpt = converter.apply(objectValue);
Optional<T> searchOpt = converter.apply(searchValue);
return objectOpt.isPresent() && searchOpt.isPresent() && matcher.apply(objectOpt.get(), searchOpt.get());
}
private static Optional<Integer> getInteger(String value) {
try {
return Optional.of(Integer.parseInt(value));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
}
| 36.305785 | 113 | 0.643069 |
f3086a5afc2f149af72306a734e436671dfec046 | 1,881 | package edu.gemini.network;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
* Класс - клиент для получения данных из сокета
*/
public class BufferedSocketClient {
public static void main(String args[]) throws Exception {
// Определяем номер порта, на котором нас ожидает сервер для ответа
int portNumber = 1777;
// Подготавливаем строку для запроса
String str = "Тестовая строка для передачи";
// Пишем, что стартовали клиент
System.out.println("Client is started");
// Открыть сокет (Socket) для обращения к локальному компьютеру (InetAddress.getLocalHost())
// Это специальный класс для сетевого взаимодействия c клиентской стороны
Socket socket1 = new Socket(InetAddress.getLocalHost(), portNumber);
// Создать поток для чтения символов из сокета
// Для этого надо открыть поток сокета - socket1.getInputStream()
// Потом перобразовать его в поток символов - new InputStreamReader
// И уже потом сделать его читателем строк - BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(socket1.getInputStream()));
// Создать поток для записи симовлов в сокет
PrintWriter pw = new PrintWriter(socket1.getOutputStream(), true);
// Мечатаем строку в сокет
pw.println(str);
// Читаем, что нам ответили из сокета
while ((str = br.readLine()) != null) {
// Отправляем тестовую строку
System.out.println(str);
// И потом посылаем ему "bye" для окончания "разговора"
pw.println("bye");
if (str.equals("bye")) {
break;
}
}
br.close();
pw.close();
socket1.close();
}
}
| 33.589286 | 100 | 0.64487 |
2359163d3606db9620ff035cd9be56ee56d18f6e | 1,081 | package com.gmail.picono435.picojobs.storage;
import java.util.UUID;
public abstract class StorageFactory {
protected abstract boolean initializeStorage() throws Exception;
public abstract boolean createPlayer(UUID uuid) throws Exception;
public abstract boolean playerExists(UUID uuid) throws Exception;
public abstract String getJob(UUID uuid) throws Exception;
public abstract double getMethod(UUID uuid) throws Exception;
public abstract double getMethodLevel(UUID uuid) throws Exception;
public abstract boolean isWorking(UUID uuid) throws Exception;
public abstract double getSalary(UUID uuid) throws Exception;
public abstract boolean setJob(UUID uuid, String job) throws Exception;
public abstract boolean setMethod(UUID uuid, double method) throws Exception;
public abstract boolean setMethodLevel(UUID uuid, double level) throws Exception;
public abstract boolean setWorking(UUID uuid, boolean isWorking) throws Exception;
public abstract boolean setSalary(UUID uuid, double salary) throws Exception;
protected abstract void destroyStorage();
}
| 41.576923 | 83 | 0.817761 |
e06b9bb338c1cf117da238b3b7c2b3c736ecd8c0 | 2,348 | package com.dncrm.service.system.regelevStandard;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.dncrm.dao.DaoSupport;
import com.dncrm.entity.Page;
import com.dncrm.util.PageData;
@Service("regelevStandardService")
public class RegelevStandardService {
@Resource(name = "daoSupport")
private DaoSupport dao;
/**
* 电梯标准分页列表
* @param page
* @return
* @throws Exception
*/
public List<PageData> listPageRegelevStandard(Page page) throws Exception{
return (List<PageData>) dao.findForList("RegelevStandardMapper.regelevStandardlistPage", page);
}
/**
* 电梯标准列表全部
* @param page
* @return
* @throws Exception
*/
public List<PageData> listAllRegelevStandard() throws Exception{
return (List<PageData>) dao.findForList("RegelevStandardMapper.listAllRegelevStandard", "");
}
/**
* 电梯标准价格添加
* @param pd
* @throws Exception
*/
public void regelevStandardAdd(PageData pd) throws Exception{
dao.save("RegelevStandardMapper.regelevStandardAdd", pd);
}
/**
* 扶梯标准价格添加
* @param pd
* @throws Exception
*/
public void escalatorStandardAdd(PageData pd) throws Exception{
dao.save("RegelevStandardMapper.escalatorStandardAdd", pd);
}
/**
* 根据主键查询
* @param pd
* @throws Exception
*/
public PageData findById(PageData pd) throws Exception{
return (PageData)dao.findForObject("RegelevStandardMapper.findById", pd);
}
public PageData findByModelsId(PageData pd) throws Exception{
return (PageData)dao.findForObject("RegelevStandardMapper.findByModelsId", pd);
}
public PageData findByModelsId2(PageData pd) throws Exception{
return (PageData)dao.findForObject("RegelevStandardMapper.findByModelsId2", pd);
}
/**
* 根据主键查询--扶梯标准
* @param pd
* @throws Exception
*/
public PageData findById2(PageData pd) throws Exception{
return (PageData)dao.findForObject("RegelevStandardMapper.findById2", pd);
}
/**
* 根据主键查询--家用梯标准
* @param pd
* @throws Exception
*/
public PageData findById3(PageData pd) throws Exception{
return (PageData)dao.findForObject("RegelevStandardMapper.findById3", pd);
}
/**
* 获取常规梯 全部电梯型号信息
*/
public List<PageData> modelsList(Page page) throws Exception{
return (List<PageData>) dao.findForList("RegelevStandardMapper.modelsList", page);
}
}
| 23.019608 | 97 | 0.73339 |
4323f4cf1d9806d8bef8e0b780c18100380a4095 | 4,152 | /*****************************************************************************
* File: UnitTestDSAQueue.java *
* Author: Sean Ashton * Student ID: *
* Unit: COMP1002 Data Structures and Algorithms *
* Purpose: Unit Test for DSAQueue Class *
* Reference: None. *
* Comments: This comment block is the maximum width of 78 characters. *
* Requires: Nothing. List dependencies here *
* Created: 15/08/2018 * Last Modified: 24/08/2018 *
*****************************************************************************/
public class UnitTestDSAQueue
{
public static void main ( String [] Args )
{
int iNumPassed = 0;
int iNumTests = 0;
DSAQueue<Object> queue;
Integer[] testArr = new Integer[6];
for (int i = 0; i < testArr.length; i++)
{
testArr[i] = i;
}
// Test with normal conditions (shouldn't throw exception)
System.out.println( "\n" );
System.out.println( "Testing Normal Conditions - Constructor" );
System.out.println( "=======================================" );
try
{
iNumTests++;
System.out.print( "Testing creation of DSAQueue: " );
queue = new DSAQueue<Object>();
iNumPassed++;
System.out.println( "Passed" );
iNumTests++;
System.out.print( "Testing isEmpty() while empty: " );
if ( queue.isEmpty() )
{
iNumPassed++;
System.out.println( "Passed" );
}
else
{
System.out.println( "FAILED" );
}
iNumTests++;
System.out.print( "Testing adding size number of elements: " );
try
{
for (int i = 0; i < testArr.length; i++)
{
queue.enqueue(testArr[i]);
}
iNumPassed++;
System.out.println( "Passed" );
}
catch (Exception e)
{
System.out.println( "FAILED" );
}
iNumTests++;
System.out.print( "Testing isEmpty() while full: " );
if ( !queue.isEmpty() )
{
iNumPassed++;
System.out.println( "Passed" );
}
else
{
System.out.println( "FAILED" );
}
iNumTests++;
System.out.print( "Testing peek(): " );
if ( queue.peek() == testArr[0] )
{
iNumPassed++;
System.out.println( "Passed" );
}
else
{
System.out.println( "FAILED" );
}
iNumTests++;
System.out.print( "Testing dequeue(): " );
try
{
int test;
for (int ii = 0; ii < testArr.length; ii++)
{
test = (int)queue.dequeue();
if (testArr[ii] != test)
{
throw new IllegalArgumentException( "FAILED" );
}
}
iNumPassed++;
System.out.println( "Passed" );
}
catch (Exception e)
{
System.out.println( "FAILED: " + e.getMessage() );
}
iNumTests++;
System.out.print( "Testing dequeue() while empty: " );
try
{
queue.dequeue();
System.out.println( "FAILED" );
}
catch (Exception e)
{
System.out.println( "Passed" );
}
}
catch (Exception e)
{
System.out.println( "Uncaught FAILED" + e.getMessage() );
}
}
}
| 30.985075 | 78 | 0.378613 |
a81d61270333a456e5c4c831e4e1247bd4657abb | 3,973 | /*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.util.fxdesigner;
import static net.sourceforge.pmd.util.fxdesigner.util.AstTraversalUtil.parentIterator;
import java.util.Objects;
import org.reactfx.EventStream;
import org.reactfx.EventStreams;
import org.reactfx.SuspendableEventStream;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.symboltable.NameDeclaration;
import net.sourceforge.pmd.util.fxdesigner.app.AbstractController;
import net.sourceforge.pmd.util.fxdesigner.app.DesignerRoot;
import net.sourceforge.pmd.util.fxdesigner.app.NodeSelectionSource;
import net.sourceforge.pmd.util.fxdesigner.util.DataHolder;
import net.sourceforge.pmd.util.fxdesigner.util.DesignerIteratorUtil;
import net.sourceforge.pmd.util.fxdesigner.util.controls.ScopeHierarchyTreeCell;
import net.sourceforge.pmd.util.fxdesigner.util.controls.ScopeHierarchyTreeItem;
import javafx.fxml.FXML;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
/**
* Controller of the scopes panel
*
* @author Clément Fournier
* @since 6.0.0
*/
@SuppressWarnings("PMD.UnusedPrivateField")
public class ScopesPanelController extends AbstractController implements NodeSelectionSource {
@FXML
private TreeView<Object> scopeHierarchyTreeView;
private SuspendableEventStream<TreeItem<Object>> myScopeItemSelectionEvents;
public ScopesPanelController(DesignerRoot designerRoot) {
super(designerRoot);
}
@Override
protected void beforeParentInit() {
scopeHierarchyTreeView.setCellFactory(view -> new ScopeHierarchyTreeCell());
// suppress as early as possible in the pipeline
myScopeItemSelectionEvents = EventStreams.valuesOf(scopeHierarchyTreeView.getSelectionModel().selectedItemProperty()).suppressible();
EventStream<NodeSelectionEvent> selectionEvents = myScopeItemSelectionEvents.filter(Objects::nonNull)
.map(TreeItem::getValue)
.filterMap(o -> o instanceof NameDeclaration, o -> (NameDeclaration) o)
.map(NameDeclaration::getNode)
.map(NodeSelectionEvent::of);
initNodeSelectionHandling(getDesignerRoot(), selectionEvents, true);
}
@Override
public void setFocusNode(final Node node, DataHolder options) {
if (node == null) {
scopeHierarchyTreeView.setRoot(null);
return;
}
// current selection
TreeItem<Object> previousSelection = scopeHierarchyTreeView.getSelectionModel().getSelectedItem();
ScopeHierarchyTreeItem rootScope = ScopeHierarchyTreeItem.buildAscendantHierarchy(node);
scopeHierarchyTreeView.setRoot(rootScope);
if (previousSelection != null) {
// Try to find the node that was previously selected and focus it in the new ascendant hierarchy.
// Otherwise, when you select a node in the scope tree, since focus of the app is shifted to that
// node, the scope hierarchy is reset and you lose the selection - even though obviously the node
// you selected is in its own scope hierarchy so it looks buggy.
int maxDepth = DesignerIteratorUtil.count(parentIterator(previousSelection, true));
rootScope.tryFindNode(previousSelection.getValue(), maxDepth)
// suspend notifications while selecting
.ifPresent(item -> myScopeItemSelectionEvents.suspendWhile(() -> scopeHierarchyTreeView.getSelectionModel().select(item)));
}
}
@Override
public String getDebugName() {
return "scopes-panel";
}
}
| 38.201923 | 155 | 0.681097 |
cc91d94cec6b5d0060e92d13fd224b8523db80f0 | 825 | package com.minhtetoo.wifichatting;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this,this);
}
@OnClick(R.id.btn_server)
public void onTapServer(View view){
startActivity(new Intent(getApplicationContext(),Server.class));
}
@OnClick(R.id.btn_client)
public void onTapClient(View view){
startActivity(new Intent(getApplicationContext(),Client.class));
}
}
| 25 | 72 | 0.741818 |
58716028872651f1bbe4143f886e2755b1c5fd9f | 673 | package com.botsoffline.eve.repository;
import java.util.List;
import java.util.Optional;
import com.botsoffline.eve.domain.CharacterSystemStatus;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface CharacterSystemStatusRepository extends MongoRepository<CharacterSystemStatus, String> {
Optional<CharacterSystemStatus> findByCharacterIdAndEndIsNull(long characterId);
Optional<CharacterSystemStatus> findByCharacterIdAndSystemIdAndEndIsNull(long characterId, long systemId);
List<CharacterSystemStatus> findAllBySystemIdAndEndIsNullOrderByStartAsc(long systemId);
List<CharacterSystemStatus> findAllByEndIsNull();
}
| 35.421053 | 110 | 0.849926 |
5023e2b5c68bdbea94847a94de645305ac06f457 | 5,715 | /*
* G2Dj Game engine
* Written by Joseph Cameron
*/
package grimhaus.com.G2Dj.Type.Physics2D;
import grimhaus.com.G2Dj.Imp.Graphics.Color;
import grimhaus.com.G2Dj.Imp.Physics2D.Collider;
import grimhaus.com.G2Dj.Imp.Physics2D.ColliderType;
import grimhaus.com.G2Dj.Type.Graphics.LineVisualizer;
import grimhaus.com.G2Dj.Type.Math.Vector2;
import grimhaus.com.G2Dj.Type.Math.Vector3;
import org.jbox2d.collision.shapes.PolygonShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.FixtureDef;
/**
*
* @author Joseph Cameron
*/
public class CompositeCollider extends Collider
{
//*************
// Data members
//*************
private Vector2[][] m_VertexArrays = new Vector2[][]{};
protected FixtureDef[] m_FixtureDefinitions;
protected LineVisualizer[] m_LineVisualizers;
//
// Accessors
//
@Override public FixtureDef[] getB2DFixtures(){return m_FixtureDefinitions;}
public void setVerticies(final Vector2[][] aCounterClockwiseVerticies){m_VertexArrays = aCounterClockwiseVerticies;requestShapeRebuildOnNextTick();}
//
// Collider implementation
//
@Override
protected void buildShape()
{
//Init/Reinit Fixtures
m_FixtureDefinitions = new FixtureDef[m_VertexArrays.length];
for(int i=0,s=m_FixtureDefinitions.length;i<s;i++)
{
m_FixtureDefinitions[i] = new FixtureDef();
m_FixtureDefinitions[i].shape = new PolygonShape();
m_FixtureDefinitions[i].setDensity(m_Density);
m_FixtureDefinitions[i].setFriction(m_Friction);
m_FixtureDefinitions[i].setRestitution(m_Restitution);
m_FixtureDefinitions[i].setSensor(m_ColliderType.toB2TriggerBool());
}
//Init/Reinit Visualizers
if (getDrawDebugLines())
{
//destroy visualizers
if (m_LineVisualizers!=null)
for(int i=0,s=m_LineVisualizers.length;i<s;i++)
getGameObject().get().removeComponent(m_LineVisualizers[i]);
//create visualizers
m_LineVisualizers = new LineVisualizer[m_VertexArrays.length];
for(int i=0,s=m_VertexArrays.length;i<s;i++)
{
m_LineVisualizers[i] = (LineVisualizer)getGameObject().get().addComponent(LineVisualizer.class);
if (m_ColliderType == ColliderType.Collidable)
m_LineVisualizers[i].setColor(Color.Green());
else
m_LineVisualizers[i].setColor(Color.DarkGreen());
}
}
//Build the fixtures
if (m_VertexArrays != null)
for(int i=0,s=m_VertexArrays.length;i<s;i++)
if (m_VertexArrays[i] != null)
{
LineVisualizer currentVisualizer = null;
if (m_LineVisualizers != null && i < m_LineVisualizers.length)
currentVisualizer = m_LineVisualizers[i];
buildAFixture(m_VertexArrays[i],currentVisualizer,m_FixtureDefinitions[i]);
}
}
//
// Implementation
//
private Vec2[] generateDefaultVertexData()
{
Vector3 scale = getGameObject().get().getTransform().get().getScale();
final float hx = 0.5f;
final float hy = 0.5f;
final int count = 4;
Vec2[] b2verts = new Vec2[count];
for(int i=0,s=count;i<s;i++)
b2verts[i] = new Vec2();
b2verts[0].set((-hx +m_Offset.x)*scale.x, (-hy +m_Offset.y)*scale.z);
b2verts[1].set(( hx +m_Offset.x)*scale.x, (-hy +m_Offset.y)*scale.z);
b2verts[2].set(( hx +m_Offset.x)*scale.x, ( hy +m_Offset.y)*scale.z);
b2verts[3].set((-hx +m_Offset.x)*scale.x, ( hy +m_Offset.y)*scale.z);
return b2verts;
}
private void buildAFixture(Vector2[] m_Vertices, LineVisualizer m_LineVisualizer, FixtureDef m_FixtureDefinition)
{
Vec2[] b2verts;
PolygonShape m_Shape = (PolygonShape)m_FixtureDefinition.shape;
Vector3 scale = getGameObject().get().getTransform().get().getScale();
if (m_Vertices == null || m_Vertices.length == 0)
b2verts = generateDefaultVertexData();
else
{
b2verts = new Vec2[m_Vertices.length];
for(int i=0,s=m_Vertices.length;i<s;i++)
b2verts[i] = new Vec2((m_Vertices[i].x+m_Offset.x)*scale.x,(m_Vertices[i].y+m_Offset.y)*scale.z);
}
m_Shape.set(b2verts, b2verts.length);
m_Shape.m_centroid.set(b_Vec2Buffer.set((m_Offset.x),(m_Offset.y)));
//Generate the line mesh
float[] visualVerts = new float[(b2verts.length*3)+3];
for(int i=0,s=b2verts.length,j=0;i<s;++i,j=i*3)
{
visualVerts[j+0] = b2verts[i].x/scale.x;
visualVerts[j+1] = 0.0f;
visualVerts[j+2] = b2verts[i].y/scale.z;
}
//The first vert has to be repeated due to visualizer using GL_LINE_STRIP not "_LOOP
visualVerts[visualVerts.length-3] = b2verts[0].x/scale.x;
visualVerts[visualVerts.length-2] = 0.0f;
visualVerts[visualVerts.length-1] = b2verts[0].y/scale.z;
if (m_LineVisualizer != null)
m_LineVisualizer.setVertexData(visualVerts);
m_FixtureDefinition.density = 1;
}
}
| 35.06135 | 152 | 0.576378 |
86133799ccbf51b93f77e0f630b84911a7fa6fa1 | 1,305 | /*
*
* * Copyright 2013 the original author or authors.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package tests.resource;
import org.junit.Test;
import tests.OAuth2TestBase;
import tests.TokenResponse;
public class BookControllerTest extends OAuth2TestBase {
@Test
public void testBadRequest() {
logout("");
ajaxGet("/book").assertNotOk();
//resp.assert400();
/*
JsonValue json = resp.getJson();
assert(json.isMap());
assertEquals(json.asMap().get("error"), OAuth2Errors.ERROR_INVALID_REQUEST);
*/
}
@Test
public void testRemoteAccessTokenStore() {
TokenResponse token = obtainAccessTokenImplicit();
withAccessToken(useGet("/book"), token.accessToken).send().assertOk();
}
} | 28.369565 | 78 | 0.688123 |
726aa37732a05099b5ddc66d5beb4eca27c3fe76 | 674 | package de.rainu.example.store;
import org.springframework.stereotype.Component;
/**
* This class represents a in-memory token store.
*/
@Component
public class TokenStore extends AbstractStore<String, String> {
public TokenStore() {
}
@Override
protected void initilizeStore() {
//no tokens are stored on startup
}
@Override
public String get(String token) {
return super.get(token);
}
@Override
public boolean contains(String token) {
return super.contains(token);
}
@Override
public void put(String token, String username) {
super.put(token, username);
}
@Override
public String remove(String token) {
return super.remove(token);
}
}
| 17.282051 | 63 | 0.725519 |
cc3bc2f94022c2f03732632ae8371095ec950ad4 | 1,178 | /*
* Copyright 2019 HERMENEUT Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package eu.hermeneut.service;
import eu.hermeneut.domain.Criticality;
import eu.hermeneut.domain.compact.output.CriticalityType;
import java.util.List;
public interface CriticalityService {
Criticality save(Criticality criticality);
List<Criticality> findAll();
List<Criticality> findAllByCompanyProfileID(Long companyProfileID);
Criticality findOneByCompanyProfileAttackStrategyAndCriticalityType(Long companyProfileID, Long attackSTrategyID, CriticalityType criticalityType);
Criticality findOne(Long id);
void delete(Long id);
}
| 31 | 151 | 0.767402 |
397af0dd5cf55bab2ff149dc5f7f0007b0a17a8c | 1,439 | /*
* Copyright (C) 2016 Ronald Jack Jenkins Jr.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package info.ronjenkins.maven.rtr;
import org.apache.commons.lang.Validate;
import org.apache.maven.project.ProjectBuilder;
/**
* Components needed throughout the Smart Reactor that can't be accessed
* directly via Plexus.
*
* @author Ronald Jack Jenkins Jr.
*/
// TODO: work on eliminating this class if possible.
public final class RTRComponents {
private final ProjectBuilder projectBuilder;
/**
* Constructor.
*
* @param projectBuilder
* not null.
*/
public RTRComponents(final ProjectBuilder projectBuilder) {
Validate.notNull(projectBuilder, "Project builder is null");
this.projectBuilder = projectBuilder;
}
/**
* Returns the shared project builder.
*
* @return never null.
*/
public ProjectBuilder getProjectBuilder() {
return this.projectBuilder;
}
}
| 28.215686 | 75 | 0.722029 |
9ff4ec9e99ad31be77a2ad0d66b2f34aba8665bd | 1,017 | package car_shop_extend;
import car_shop_extend.interfaces.Rentable;
public class Audi extends CarImpl implements Rentable {
private Integer minRentDay;
private Double pricePerDay;
public Audi(String model, String color, Integer horsepower, String country,
Integer minRentDay, Double pricePerDay) {
super(model, color, horsepower, country);
this.minRentDay = minRentDay;
this.pricePerDay = pricePerDay;
}
@Override
public int getMinRentDay() {
return this.minRentDay;
}
@Override
public Double getPricePerDay() {
return this.pricePerDay;
}
@Override
public String toString() {
return String.format(
"This is %s produced in %s and have %d tires" + System.lineSeparator() +
"Minimum rental period of %d days. Price per day %f",
this.getModel(), this.countryProduce(), TIRES,
this.getMinRentDay(), this.getPricePerDay());
}
}
| 29.057143 | 88 | 0.632252 |
984fc72075d87f5478d0c851448a4336e3c46fed | 1,030 | package com.lanking.uxb.service.diagnostic.api;
import java.util.List;
import com.lanking.cloud.domain.yoomath.diagnostic.DiagnosticClassStudent;
import com.lanking.cloud.sdk.data.Page;
import com.lanking.cloud.sdk.data.Pageable;
/**
* @author xinyu.zhou
* @since 2.1.0
*/
public interface DiagnosticClassStudentService {
/**
* 分页查询班级学生掌握情况
*
* @param pageable
* {@link Pageable}
* @param day0
* 统计时间范围
* @param orderBy
* 根据如何进行排序
* @param classId
* 班级id
* @return {@link Page}
*/
Page<DiagnosticClassStudent> query(Pageable pageable, int day0, int orderBy, long classId);
/**
* 不分页查询班级学生掌握情况
*
* @param day0
* 统计时间范围
* @param orderBy
* 0.正确率DESC(名次榜)<br>
* 1.floatRank DESC(进步榜)<br>
* 2.floatRank ASC(退步榜)<br>
* 3.作业数量 DESC(勤奋榜)<br>
* @param classId
* 班级id
* @return {@link Page}
*/
List<DiagnosticClassStudent> query(int day0, int orderBy, long classId);
}
| 22.888889 | 92 | 0.61068 |
fcce7b56e0c4923d2b37a1be6911e9ae5644baea | 1,849 | /*
* Copyright 2011, 2012 Odysseus Software GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.odysseus.staxon.base;
/**
* Object pair.
* @param <F> first type
* @param <S> second type
*/
class Pair<F, S> {
private final F first;
private final S second;
/**
* Create a new pair instance.
* @param first first object
* @param second second object
*/
Pair(F first, S second) {
this.first = first;
this.second = second;
}
/**
* @return first object
*/
F getFirst() {
return first;
}
/**
* @return second object
*/
S getSecond() {
return second;
}
@Override
public int hashCode() {
return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Pair<?, ?> other = (Pair<?, ?>) obj;
if (first == null) {
if (other.first != null) {
return false;
}
} else if (!first.equals(other.first)) {
return false;
}
if (second == null) {
if (other.second != null) {
return false;
}
} else if (!second.equals(other.second)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Pair(" + first + "," + second + ")";
}
}
| 21.252874 | 91 | 0.628989 |
6b705905d321f7805af8ceb61f1d58b091c1b3c8 | 14,731 | /*
* Code licensed under new-style BSD (see LICENSE).
* All code up to tags/original: Copyright (c) 2013, Joshua Kaplan
* All code after tags/original: Copyright (c) 2016, DiffPlug
*/
package matlabcontrol.demo;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.text.NumberFormat;
import java.util.concurrent.atomic.AtomicReference;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import matlabcontrol.MatlabConnectionException;
import matlabcontrol.MatlabInvocationException;
import matlabcontrol.MatlabProxy;
import matlabcontrol.MatlabProxyFactory;
import matlabcontrol.MatlabProxyFactoryOptions;
import matlabcontrol.PermissiveSecurityManager;
/**
* A GUI example to demonstrate the main functionality of controlling MATLAB with matlabcontrol. The code in this
* class (and the rest of the package) is not intended to serve as an example for how to use matlabcontrol, instead
* the application exists to interactively demonstrate the API's capabilities.
* <br><br>
* The icon is part of the Um collection created by <a href="mailto:[email protected]">mattahan (Paul Davey)</a>. It is
* licensed under the <a href="http://creativecommons.org/licenses/by-nc-sa/3.0/">CC Attribution-Noncommercial-Share
* Alike 3.0 License</a>.
*
* @author <a href="mailto:[email protected]">Joshua Kaplan</a>
*/
@SuppressWarnings("serial")
public class DemoFrame extends JFrame {
//Status messages
private static final String STATUS_DISCONNECTED = "Connection Status: Disconnected",
STATUS_CONNECTING = "Connection Status: Connecting",
STATUS_CONNECTED_EXISTING = "Connection Status: Connected (Existing)",
STATUS_CONNECTED_LAUNCHED = "Connection Status: Connected (Launched)";
//Return messages
private static final String RETURNED_DEFAULT = "Returned Object / Java Exception",
RETURNED_OBJECT = "Returned Object",
RETURNED_EXCEPTION = "Java Exception";
//Panel/Pane sizes
private static final int PANEL_WIDTH = 660;
private static final Dimension CONNECTION_PANEL_SIZE = new Dimension(PANEL_WIDTH, 70),
RETURN_PANEL_SIZE = new Dimension(PANEL_WIDTH, 250),
METHOD_PANEL_SIZE = new Dimension(PANEL_WIDTH, 110 + 28 * ArrayPanel.NUM_ENTRIES),
DESCRIPTION_PANE_SIZE = new Dimension(PANEL_WIDTH, 200),
COMMAND_PANEL_SIZE = new Dimension(PANEL_WIDTH, METHOD_PANEL_SIZE.height + DESCRIPTION_PANE_SIZE.height),
MAIN_PANEL_SIZE = new Dimension(PANEL_WIDTH, CONNECTION_PANEL_SIZE.height + COMMAND_PANEL_SIZE.height + RETURN_PANEL_SIZE.height);
//Factory to create proxy
private final MatlabProxyFactory _factory;
//Proxy to communicate with MATLAB
private final AtomicReference<MatlabProxy> _proxyHolder = new AtomicReference<MatlabProxy>();
//UI components
private JButton _invokeButton;
private JScrollPane _returnPane;
private JTextArea _returnArea;
public static BufferedImage getIcon() {
try {
return ImageIO.read(DemoFrame.class.getResource("/matlabcontrol/demo/logo_128.png"));
} catch (Exception e) {
e.printStackTrace();
return new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
}
}
/**
* Create the main GUI.
*/
public DemoFrame(String title, String matlabLocation) {
super(title);
System.setSecurityManager(new PermissiveSecurityManager());
setIconImage(getIcon());
//Panel that contains the over panels
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.setBackground(Color.WHITE);
mainPanel.setPreferredSize(MAIN_PANEL_SIZE);
mainPanel.setSize(MAIN_PANEL_SIZE);
this.add(mainPanel);
//Connection panel, button to connect, progress bar
final JPanel connectionPanel = new JPanel();
connectionPanel.setBackground(mainPanel.getBackground());
connectionPanel.setBorder(BorderFactory.createTitledBorder(STATUS_DISCONNECTED));
connectionPanel.setPreferredSize(CONNECTION_PANEL_SIZE);
connectionPanel.setSize(CONNECTION_PANEL_SIZE);
final JButton connectionButton = new JButton("Connect");
connectionPanel.add(connectionButton);
final JProgressBar connectionBar = new JProgressBar();
connectionPanel.add(connectionBar);
//To display what has been returned from MATLAB
_returnArea = new JTextArea();
_returnArea.setEditable(false);
//Put the returnArea in pane, add it
_returnPane = new JScrollPane(_returnArea);
_returnPane.setBackground(Color.WHITE);
_returnPane.setPreferredSize(RETURN_PANEL_SIZE);
_returnPane.setBorder(BorderFactory.createTitledBorder(RETURNED_DEFAULT));
//Command Panel
JPanel commandPanel = this.createCommandPanel();
//Structure the panels so that on resize the layout updates appropriately
JPanel combinedPanel = new JPanel(new BorderLayout());
combinedPanel.add(connectionPanel, BorderLayout.NORTH);
combinedPanel.add(commandPanel, BorderLayout.SOUTH);
mainPanel.add(combinedPanel, BorderLayout.NORTH);
mainPanel.add(_returnPane, BorderLayout.CENTER);
this.pack();
//Create proxy factory
MatlabProxyFactoryOptions options = new MatlabProxyFactoryOptions.Builder()
.setUsePreviouslyControlledSession(true)
.setMatlabLocation(matlabLocation)
.build();
_factory = new MatlabProxyFactory(options);
//Connect to MATLAB when the Connect button is pressed
connectionButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//Request a proxy
_factory.requestProxy(new MatlabProxyFactory.RequestCallback() {
@Override
public void proxyCreated(final MatlabProxy proxy) {
_proxyHolder.set(proxy);
proxy.addDisconnectionListener(new MatlabProxy.DisconnectionListener() {
@Override
public void proxyDisconnected(MatlabProxy proxy) {
_proxyHolder.set(null);
//Visual update
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
connectionPanel.setBorder(BorderFactory.createTitledBorder(STATUS_DISCONNECTED));
_returnPane.setBorder(BorderFactory.createTitledBorder(RETURNED_DEFAULT));
_returnArea.setText("");
connectionBar.setValue(0);
connectionButton.setEnabled(true);
_invokeButton.setEnabled(false);
}
});
}
});
//Visual update
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
String status;
if (proxy.isExistingSession()) {
status = STATUS_CONNECTED_EXISTING;
} else {
status = STATUS_CONNECTED_LAUNCHED;
}
connectionPanel.setBorder(BorderFactory.createTitledBorder(status));
connectionBar.setValue(100);
connectionBar.setIndeterminate(false);
_invokeButton.setEnabled(true);
}
});
}
});
//Update GUI
connectionPanel.setBorder(BorderFactory.createTitledBorder(STATUS_CONNECTING));
connectionBar.setIndeterminate(true);
connectionButton.setEnabled(false);
} catch (MatlabConnectionException exc) {
_returnPane.setBorder(BorderFactory.createTitledBorder(RETURNED_EXCEPTION));
_returnArea.setText(ReturnFormatter.formatException(exc));
_returnArea.setCaretPosition(0);
}
}
});
//Window events
this.addWindowListener(new WindowAdapter() {
/**
* On window appearance set the minimum size to the same width and 80% of the height.
*/
@Override
public void windowOpened(WindowEvent e) {
Dimension size = DemoFrame.this.getSize();
size.height *= .8;
DemoFrame.this.setMinimumSize(size);
}
});
}
/**
* Create the command panel.
*
* @param returnArea
* @return
*/
private JPanel createCommandPanel() {
//Panel that contains the methods, input, and description
JPanel commandPanel = new JPanel(new BorderLayout());
commandPanel.setBackground(Color.WHITE);
commandPanel.setPreferredSize(COMMAND_PANEL_SIZE);
commandPanel.setSize(COMMAND_PANEL_SIZE);
//Method
JPanel methodPanel = new JPanel(new BorderLayout());
methodPanel.setBorder(BorderFactory.createTitledBorder("Method"));
methodPanel.setBackground(Color.WHITE);
methodPanel.setPreferredSize(METHOD_PANEL_SIZE);
methodPanel.setSize(METHOD_PANEL_SIZE);
commandPanel.add(methodPanel, BorderLayout.NORTH);
//Upper part - drop down and button
JPanel methodUpperPanel = new JPanel();
methodUpperPanel.setBackground(Color.WHITE);
methodPanel.add(methodUpperPanel, BorderLayout.NORTH);
//Lower part - input fields
JPanel methodLowerPanel = new JPanel();
methodLowerPanel.setBackground(Color.WHITE);
methodPanel.add(methodLowerPanel, BorderLayout.SOUTH);
//Method choice
final JComboBox methodBox = new JComboBox(ProxyMethodDescriptor.values());
methodUpperPanel.add(methodBox);
//Invoke button
_invokeButton = new JButton("Invoke");
_invokeButton.setEnabled(false);
methodUpperPanel.add(_invokeButton);
//Input
final JTextField field = new JTextField();
field.setBackground(methodPanel.getBackground());
field.setColumns(16);
methodLowerPanel.add(field);
//Return count
final JFormattedTextField nargoutField = new JFormattedTextField(NumberFormat.INTEGER_FIELD);
nargoutField.setBackground(methodPanel.getBackground());
nargoutField.setColumns(8);
nargoutField.setBorder(BorderFactory.createTitledBorder("nargout"));
methodLowerPanel.add(nargoutField);
//Array entries
final ArrayPanel arrayPanel = new ArrayPanel();
methodLowerPanel.add(arrayPanel);
//Method description
final JEditorPane descriptionArea = new JEditorPane("text/html", "");
descriptionArea.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
JScrollPane descriptionPane = new JScrollPane(descriptionArea);
descriptionPane.setBackground(Color.WHITE);
descriptionArea.setFont(new Font("SansSerif", Font.PLAIN, 13));
descriptionPane.setBorder(BorderFactory.createTitledBorder("Method description"));
descriptionPane.setPreferredSize(DESCRIPTION_PANE_SIZE);
descriptionArea.setEditable(false);
commandPanel.add(descriptionPane, BorderLayout.SOUTH);
//Listen for method choices
methodBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Get selected method
ProxyMethodDescriptor method = (ProxyMethodDescriptor) methodBox.getSelectedItem();
//Update box titles
field.setBorder(BorderFactory.createTitledBorder(method.stringInputName));
//Disable/enable return count and update text appropriately
if (method.returnCountEnabled) {
nargoutField.setText("1");
nargoutField.setEnabled(true);
} else {
nargoutField.setText("N/A");
nargoutField.setEnabled(false);
}
//Disable/enable array input appropriately
arrayPanel.setBorder(BorderFactory.createTitledBorder(method.argsInputName));
arrayPanel.enableInputFields(method.argsInputNumberEnabled);
//Update description text
descriptionArea.setText(method.message);
//Scroll to the top of the description text
descriptionArea.setCaretPosition(0);
//Select text in field and switch focus
field.selectAll();
field.grabFocus();
}
});
//Select first index to have action take effect
methodBox.setSelectedIndex(0);
//Invoke button action
_invokeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProxyMethodDescriptor descriptor = (ProxyMethodDescriptor) methodBox.getSelectedItem();
//eval(String command)
if (descriptor == ProxyMethodDescriptor.EVAL) {
try {
_proxyHolder.get().eval(field.getText());
displayReturn();
} catch (MatlabInvocationException ex) {
displayException(ex);
}
}
//returningEval(String command, int nargout)
else if (descriptor == ProxyMethodDescriptor.RETURNING_EVAL) {
int nargout = 0;
try {
nargout = Integer.parseInt(nargoutField.getText());
} catch (Exception ex) {}
try {
displayResult(_proxyHolder.get().returningEval(field.getText(), nargout));
} catch (MatlabInvocationException ex) {
displayException(ex);
}
}
//feval(String functionName, Object... args)
else if (descriptor == ProxyMethodDescriptor.FEVAL) {
try {
_proxyHolder.get().feval(field.getText(), arrayPanel.getArray());
displayReturn();
} catch (MatlabInvocationException ex) {
displayException(ex);
}
}
//returningFeval(String functionName, int nargout, Object... args)
else if (descriptor == ProxyMethodDescriptor.RETURNING_FEVAL) {
int nargout = 0;
try {
nargout = Integer.parseInt(nargoutField.getText());
} catch (Exception ex) {}
try {
displayResult(_proxyHolder.get().returningFeval(field.getText(), nargout, arrayPanel.getArray()));
} catch (MatlabInvocationException ex) {
displayException(ex);
}
}
//setVariable(String variableName, Object value)
else if (descriptor == ProxyMethodDescriptor.SET_VARIABLE) {
try {
_proxyHolder.get().setVariable(field.getText(), arrayPanel.getFirstEntry());
displayReturn();
} catch (MatlabInvocationException ex) {
displayException(ex);
}
}
//getVariable(String variableName)
else if (descriptor == ProxyMethodDescriptor.GET_VARIABLE) {
try {
displayResult(_proxyHolder.get().getVariable(field.getText()));
} catch (MatlabInvocationException ex) {
displayException(ex);
}
}
}
});
return commandPanel;
}
private void displayReturn() {
_returnArea.setText("");
}
private void displayResult(Object result) {
_returnPane.setBorder(BorderFactory.createTitledBorder(RETURNED_OBJECT));
_returnArea.setForeground(Color.BLACK);
_returnArea.setText(ReturnFormatter.formatResult(result));
_returnArea.setCaretPosition(0);
}
private void displayException(Exception exc) {
_returnPane.setBorder(BorderFactory.createTitledBorder(RETURNED_EXCEPTION));
_returnArea.setForeground(Color.RED);
_returnArea.setText(ReturnFormatter.formatException(exc));
_returnArea.setCaretPosition(0);
}
}
| 34.907583 | 133 | 0.742923 |
f01a09a2c241cec623c8597b1150a4f973ac38ef | 1,787 | package com.base.module.app;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import com.base.module.home.AppHomeActivity;
import com.base.module.login.AppLoginActivity;
import com.base.module.order.AppOrderActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private final static int ID_SM_LOGIN = 11; // 登陆
private final static int ID_SM_HOME = 12; // 首页
private final static int ID_SM_ORDER = 13; // 我的订单
private FlowLayout mFlowLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFlowLayout = findViewById(R.id.flow_layout);
initView();
}
private void initView() {
mFlowLayout.addView(getItemView("Login-登陆", ID_SM_LOGIN));
mFlowLayout.addView(getItemView("Home-首页", ID_SM_HOME));
mFlowLayout.addView(getItemView("Orders-订单", ID_SM_ORDER));
}
private View getItemView(String content, int viewId) {
return ViewItemUtil.generateItemView(this, content, viewId, this);
}
@Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case ID_SM_LOGIN: // 登陆
intent = new Intent(this, AppLoginActivity.class);
break;
case ID_SM_HOME: // 首页
intent = new Intent(this, AppHomeActivity.class);
break;
case ID_SM_ORDER: // 订单
intent = new Intent(this, AppOrderActivity.class);
break;
}
if (intent != null) {
startActivity(intent);
}
}
}
| 30.810345 | 85 | 0.648573 |
094dfb942d0bafa89ef2ffe2e4e78fa39cb46c44 | 2,996 | package com.nitobi.jsp.calendar;
import javax.servlet.jsp.JspException;
import com.nitobi.jsp.NitobiBodyTag;
/**
* @author mhan
* @jsp.tag name="dateinput"
*
*/
public class DateInput extends NitobiBodyTag
{
private String displaymask;
private String editmask;
private String editable;
private String width;
private String onblur;
private String onfocus;
public int doStartTag() throws JspException
{
writeDateInputStartTag();
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspException
{
writeDateInputEndTag();
return EVAL_PAGE;
}
private void writeDateInputStartTag() throws JspException
{
try
{
pageContext.getOut().print("<ntb:dateinput ");
writeTagAttributes();
pageContext.getOut().print(">");
}
catch (java.io.IOException e)
{
throw new JspException(e);
}
}
private void writeDateInputEndTag() throws JspException
{
try
{
pageContext.getOut().print("</ntb:dateinput>");
}
catch (java.io.IOException e)
{
throw new JspException(e);
}
}
/**
* @jsp.attribute required="false"
* rtexprvalue="true"
* description="The displaymask attribute"
* @return the displaymask
*/
public String getDisplaymask() {
return displaymask;
}
/**
* @param displaymask the displaymask to set
*/
public void setDisplaymask(String displaymask) {
this.displaymask = displaymask;
}
/**
* @jsp.attribute required="false"
* rtexprvalue="true"
* description="The editmask attribute"
* @return the editmask
*/
public String getEditmask() {
return editmask;
}
/**
* @param editmask the editmask to set
*/
public void setEditmask(String editmask) {
this.editmask = editmask;
}
/**
* @jsp.attribute required="false"
* rtexprvalue="true"
* description="The editable attribute"
* @return the editable
*/
public String getEditable() {
return editable;
}
/**
* @param editable the editable to set
*/
public void setEditable(String editable) {
this.editable = editable;
}
/**
* @jsp.attribute required="false"
* rtexprvalue="true"
* description="The width attribute"
* @return the width
*/
public String getWidth() {
return width;
}
/**
* @param width the width to set
*/
public void setWidth(String width) {
this.width = width;
}
/**
* @jsp.attribute required="false"
* rtexprvalue="true"
* description="The onblur attribute"
* @return the onblur
*/
public String getOnblur() {
return onblur;
}
/**
* @param onblur the onblur to set
*/
public void setOnblur(String onblur) {
this.onblur = onblur;
}
/**
* @jsp.attribute required="false"
* rtexprvalue="true"
* description="The onfocus attribute"
* @return the onfocus
*/
public String getOnfocus() {
return onfocus;
}
/**
* @param onfocus the onfocus to set
*/
public void setOnfocus(String onfocus) {
this.onfocus = onfocus;
}
}
| 18.493827 | 59 | 0.654539 |
e3340721d9eae73993177a6b6c7b0d85f8e8ab81 | 879 | /*
* Copyright by the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tdcoinj.wallet.listeners;
import org.tdcoinj.wallet.KeyChainGroup;
public interface CurrentKeyChangeEventListener {
/**
* Called by {@link KeyChainGroup} whenever a current key and/or address changes.
*/
void onCurrentKeyChanged();
}
| 32.555556 | 85 | 0.739477 |
fbdc5600a5cd79d0e91a23c32cb66c4acb57944d | 857 | package pokecube.alternative.container.belt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import pokecube.core.items.pokecubes.PokecubeManager;
import thut.lib.CompatWrapper;
public class SlotPokemon extends Slot
{
public SlotPokemon(IInventory par2IInventory, int par3, int par4, int par5)
{
super(par2IInventory, par3, par4, par5);
}
@Override
public boolean isItemValid(ItemStack stack)
{
if (PokecubeManager.isFilled(stack)) { return true; }
return false;
}
@Override
public boolean canTakeStack(EntityPlayer player)
{
return CompatWrapper.isValid(this.getStack());
}
@Override
public int getSlotStackLimit()
{
return 1;
}
}
| 22.552632 | 79 | 0.707118 |
e8c12315400f1c18254404c4487168d1ebce7844 | 2,922 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alipay.dw.jstorm.example.window;
import java.util.concurrent.TimeUnit;
import org.apache.storm.starter.bolt.PrinterBolt;
import org.apache.storm.starter.bolt.SlidingWindowSumBolt;
import org.apache.storm.starter.spout.RandomIntegerSpout;
import com.alibaba.starter.utils.Assert;
import com.alibaba.starter.utils.JStormHelper;
import backtype.storm.Config;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.topology.base.BaseWindowedBolt;
import backtype.storm.topology.base.BaseWindowedBolt.Duration;
/**
* Windowing based on tuple timestamp (e.g. the time when tuple is generated
* rather than when its processed).
*/
public class SlidingTupleTsTopology {
static boolean isLocal = true;
static Config conf = JStormHelper.getConfig(null);
public static void test() {
String[] className = Thread.currentThread().getStackTrace()[1].getClassName().split("\\.");
String topologyName = className[className.length - 1];
try {
TopologyBuilder builder = new TopologyBuilder();
BaseWindowedBolt bolt = new SlidingWindowSumBolt()
.withWindow(new Duration(5, TimeUnit.SECONDS), new Duration(3, TimeUnit.SECONDS))
.withTimestampField("ts").withLag(new Duration(5, TimeUnit.SECONDS));
builder.setSpout("integer", new RandomIntegerSpout(), 1);
builder.setBolt("slidingsum", bolt, 1).shuffleGrouping("integer");
builder.setBolt("printer", new PrinterBolt(), 1).shuffleGrouping("slidingsum");
conf.setDebug(true);
JStormHelper.runTopology(builder.createTopology(), topologyName, conf, 60,
new JStormHelper.CheckAckedFail(conf), isLocal);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Assert.fail("Failed");
}
}
public static void main(String[] args) throws Exception {
isLocal = false;
conf = JStormHelper.getConfig(args);
test();
}
}
| 40.027397 | 101 | 0.689596 |
192c4ceec6b31ebd4e7be3e83478d5a51c28f563 | 1,715 | package com.serenitybdd.screens.base;
import net.serenitybdd.core.annotations.findby.FindBy;
import net.serenitybdd.core.pages.PageObject;
import net.serenitybdd.core.pages.WebElementFacade;
import java.util.Set;
public class ChangePasswordScreen extends PageObject{
@FindBy(id = "newpassword")
private WebElementFacade fill_newPass;
@FindBy(id = "confirmpassword")
private WebElementFacade fill_ConfirmPass;
@FindBy(id = "answer")
private WebElementFacade fill_Answer;
@FindBy(id = "password-button")
private WebElementFacade clik_SubmitBtn;
private void setFill_newPass(String fill_newPass) {
this.fill_newPass.sendKeys(fill_newPass);
}
private void setFill_ConfirmPass(String fill_ConfirmPass){
this.fill_ConfirmPass.sendKeys(fill_ConfirmPass);
}
private void setFill_Answer(String fill_Answer){
this.fill_Answer.sendKeys(fill_Answer);
}
public void ChangePasswordScreen(String fill_newPass, String fill_ConfirmPass, String fill_Answer){
String parentHandle = getDriver().getWindowHandle();
System.out.println(parentHandle);
//Get all handles
Set<String> handles = getDriver().getWindowHandles();
//ChangePasswordScreen between handles
for (String handle : handles) {
System.out.println(handle);
if (!handle.equals(parentHandle)) {
getDriver().switchTo().window(handle);
setFill_newPass(fill_newPass);
setFill_ConfirmPass(fill_ConfirmPass);
setFill_Answer(fill_Answer);
if (clik_SubmitBtn.isEnabled()) {
this.clik_SubmitBtn.click();
}
break;
}
}
}
}
| 31.181818 | 103 | 0.692128 |
f71d616764f761a71c4e4597aa355ceeba4d3869 | 1,591 | package com.ailbb.alt.linux.ssh;
import com.ailbb.ajj.entity.$Result;
import com.ailbb.ajj.entity.$Status;
import com.ailbb.alt.$;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* Created by Wz on 7/10/2019.
*/
public class $SSHThread implements Runnable {
// 设置读取的字符编码
private String character = "GB2312";
private $Result rs;
private InputStream inputStream;
private String type;
public $SSHThread(InputStream inputStream, $Result rs) {
this(inputStream, rs, "data");
}
public $SSHThread(InputStream inputStream, $Result rs, String type) {
this.inputStream = inputStream;
this.rs = rs;
this.type = type;
}
public void start() {
Thread thread = new Thread(this);
thread.setDaemon(true);//将其设置为守护线程
thread.start();
}
public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream, character));
String line = null;
while ((line = br.readLine()) != null) {
if (line != null) {
$.sout(line);
if(type.equals("message"))
rs.addMessage(line);
else
rs.addData(line);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
$.file.closeStearm(inputStream);
$.file.closeStearm(br);
}
}
}
| 26.081967 | 83 | 0.558768 |
e21ae27bbb7561ab1f7af49eb1c39db48c1b56b2 | 777 | package com.dsvl.flood.controller;
import com.dsvl.flood.Node;
import com.dsvl.flood.model.NodeDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class NodeDetailsController {
private Node node;
@GetMapping("/node-details")
public NodeDetails getNodeDetails() {
return new NodeDetails(
node.getBootstrapServerAddress(),
node.getStatus(),
node.getNodeAddress(),
node.getTcpPort(),
node.getNodeUdpPort()
);
}
@Autowired
public void setNode(Node node) {
this.node = node;
}
}
| 25.064516 | 62 | 0.66538 |
e895e4f4b40e5fa6f9fce27c4d85fef9425bbd71 | 715 | package org.laboys.game.birzzle.window;
import org.laboys.game.birzzle.model.Board;
import javax.swing.*;
public class GameFrame extends JFrame {
private final int WINDOW_WIDTH = 420;
private final int WINDOW_HEIGHT = 444;
private final int BOARD_WIDTH = 8;
private final int BOARD_HEIGHT = 8;
private final TilesPanel tilesPanel;
public GameFrame() {
tilesPanel = new TilesPanel(new Board(BOARD_WIDTH, BOARD_HEIGHT));
setTitle("Birzzle");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(tilesPanel);
}
}
| 23.064516 | 75 | 0.662937 |
a747a06b23e727b9aa5c4f09687d10634bd050b2 | 113 | package com.adaptris.core.elastic.rest;
public interface FieldNameMapper {
public String map(String name);
}
| 18.833333 | 39 | 0.778761 |
84b75a8dd5cfbf70e0de6c1abfdab9ec127fb555 | 1,710 | /*
* JasperReports - Free Java Reporting Library.
* Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved.
* http://www.jaspersoft.com
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program is part of JasperReports.
*
* JasperReports 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 3 of the License, or
* (at your option) any later version.
*
* JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.jasperreports.engine.fill;
/**
* Interface of elements that can be cloned at fill time.
* <p>
* In some cases multiple copies of the same element are evaluated, prepared and filled simultaneously.
* Such an element should implement this interface so that working clones of the element can be created.
*
* @author Lucian Chirita ([email protected])
* @version $Id: JRFillCloneable.java 5878 2013-01-07 20:23:13Z teodord $
*/
public interface JRFillCloneable
{
/**
* Creates a working clone of itself.
*
* @param factory the clone factory to use while creating the clone
* @return a working clone of itself
*/
JRFillCloneable createClone(JRFillCloneFactory factory);
}
| 37.173913 | 104 | 0.750292 |
53c59438aa70f01486bbc20598103736072f91eb | 7,299 | package com.wordnik.swagger.models;
import com.wordnik.swagger.models.auth.SecuritySchemeDefinition;
import com.fasterxml.jackson.annotation.*;
import com.wordnik.swagger.models.parameters.Parameter;
import java.util.*;
public class Swagger {
protected String swagger = "2.0";
protected Info info;
protected String host;
protected String basePath;
protected List<Tag> tags;
protected List<Scheme> schemes;
protected List<String> consumes;
protected List<String> produces;
protected List<SecurityRequirement> securityRequirements;
protected Map<String, Path> paths;
protected Map<String, SecuritySchemeDefinition> securityDefinitions;
protected Map<String, Model> definitions;
protected Map<String, Parameter> parameters;
protected ExternalDocs externalDocs;
// builders
public Swagger info(Info info) {
this.setInfo(info);
return this;
}
public Swagger host(String host) {
this.setHost(host);
return this;
}
public Swagger basePath(String basePath) {
this.setBasePath(basePath);
return this;
}
public Swagger externalDocs(ExternalDocs value) {
this.setExternalDocs(value);
return this;
}
public Swagger tags(List<Tag> tags) {
this.setTags(tags);
return this;
}
public Swagger tag(Tag tag) {
this.addTag(tag);
return this;
}
public Swagger schemes(List<Scheme> schemes) {
this.setSchemes(schemes);
return this;
}
public Swagger scheme(Scheme scheme) {
this.addScheme(scheme);
return this;
}
public Swagger consumes(List<String> consumes) {
this.setConsumes(consumes);
return this;
}
public Swagger consumes(String consumes) {
this.addConsumes(consumes);
return this;
}
public Swagger produces(List<String> produces) {
this.setProduces(produces);
return this;
}
public Swagger produces(String produces) {
this.addProduces(produces);
return this;
}
public Swagger paths(Map<String, Path> paths) {
this.setPaths(paths);
return this;
}
public Swagger path(String key, Path path) {
if(this.paths == null)
this.paths = new LinkedHashMap<String, Path>();
this.paths.put(key, path);
return this;
}
public Swagger parameter(String key, Parameter parameter) {
this.addParameter(key, parameter);
return this;
}
public Swagger securityDefinition(String name, SecuritySchemeDefinition securityDefinition) {
this.addSecurityDefinition(name, securityDefinition);
return this;
}
public Swagger model(String name, Model model) {
this.addDefinition(name, model);
return this;
}
// getter & setters
public String getSwagger() {
return swagger;
}
public void setSwagger(String swagger) {
this.swagger = swagger;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public List<Scheme> getSchemes() {
return schemes;
}
public void setSchemes(List<Scheme> schemes) {
this.schemes = schemes;
}
public void addScheme(Scheme scheme) {
if(this.schemes == null)
this.schemes = new ArrayList<Scheme>();
boolean found = false;
for(Scheme existing : this.schemes) {
if(existing.equals(scheme))
found = true;
}
if(!found)
this.schemes.add(scheme);
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public void addTag(Tag tag) {
if(this.tags == null)
this.tags = new ArrayList<Tag>();
if(tag != null && tag.getName() != null) {
boolean found = false;
for(Tag existing : this.tags) {
if(existing.getName().equals(tag.getName()))
found = true;
}
if(!found)
this.tags.add(tag);
}
}
public List<String> getConsumes() {
return consumes;
}
public void setConsumes(List<String> consumes) {
this.consumes = consumes;
}
public void addConsumes(String consumes) {
if(this.consumes == null)
this.consumes = new ArrayList<String>();
this.consumes.add(consumes);
}
public List<String> getProduces() {
return produces;
}
public void setProduces(List<String> produces) {
this.produces = produces;
}
public void addProduces(String produces) {
if(this.produces == null)
this.produces = new ArrayList<String>();
this.produces.add(produces);
}
public Map<String, Path> getPaths() {
if(paths == null)
return null;
Map<String, Path> sorted = new LinkedHashMap<String, Path>();
List<String> keys = new ArrayList<String>();
keys.addAll(paths.keySet());
Collections.sort(keys);
for(String key: keys) {
sorted.put(key, paths.get(key));
}
return sorted;
}
public void setPaths(Map<String, Path> paths) {
this.paths = paths;
}
public Path getPath(String path) {
if(this.paths == null)
return null;
return this.paths.get(path);
}
public Map<String, SecuritySchemeDefinition> getSecurityDefinitions() {
return securityDefinitions;
}
public void setSecurityDefinitions(Map<String, SecuritySchemeDefinition> securityDefinitions) {
this.securityDefinitions = securityDefinitions;
}
public void addSecurityDefinition(String name, SecuritySchemeDefinition securityDefinition) {
if(this.securityDefinitions == null)
this.securityDefinitions = new HashMap<String, SecuritySchemeDefinition>();
this.securityDefinitions.put(name, securityDefinition);
}
public List<SecurityRequirement> getSecurityRequirement() {
return securityRequirements;
}
public void setSecurityRequirement(List<SecurityRequirement> securityRequirements) {
this.securityRequirements = securityRequirements;
}
public void addSecurityDefinition(SecurityRequirement securityRequirement) {
if(this.securityRequirements == null)
this.securityRequirements = new ArrayList<SecurityRequirement>();
this.securityRequirements.add(securityRequirement);
}
public void setDefinitions(Map<String, Model> definitions) {
this.definitions = definitions;
}
public Map<String, Model> getDefinitions() {
return definitions;
}
public void addDefinition(String key, Model model) {
if(this.definitions == null)
this.definitions = new HashMap<String, Model>();
this.definitions.put(key, model);
}
public Map<String, Parameter> getParameters() {
return parameters;
}
public void setParameters(Map<String, Parameter> parameters) {
this.parameters = parameters;
}
public Parameter getParameter(String parameter) {
if(this.parameters == null)
return null;
return this.parameters.get(parameter);
}
public void addParameter(String key, Parameter parameter) {
if(this.parameters == null)
this.parameters = new HashMap<String, Parameter>();
this.parameters.put(key, parameter);
}
public ExternalDocs getExternalDocs() {
return externalDocs;
}
public void setExternalDocs(ExternalDocs value) {
externalDocs = value;
}
}
| 26.541818 | 97 | 0.689135 |
6a66288a126c39df2e5fb51d365ac66f019ccf44 | 4,509 | package org.liveontologies.protege.explanation.proof;
/*-
* #%L
* Protege Proof-Based Explanation
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2014 - 2016 Live Ontologies Project
* %%
* 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.
* #L%
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import org.liveontologies.protege.explanation.proof.list.ProofFrame;
import org.liveontologies.protege.explanation.proof.list.ProofFrameList;
import org.liveontologies.protege.explanation.proof.service.ProofService;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.ui.explanation.ExplanationResult;
import org.semanticweb.owlapi.model.OWLAxiom;
/**
* The component that displays a proof-based explanation for an entailment
*
* @author Pavel Klinov [email protected]
*
* @author Yevgeny Kazakov
*
*/
public class ProofBasedExplanationResult extends ExplanationResult
implements ProofManager.ChangeListener {
private static final long serialVersionUID = -4072183414834233365L;
private final ProofManager proofManager_;
private final OWLEditorKit kit_;
private final ProofFrame frame_;
private final ProofFrameList frameList_;
private final JScrollPane scrollPane;
private ProofBasedExplanationResult(ProofManager proofManager) {
setLayout(new BorderLayout());
this.proofManager_ = proofManager;
this.kit_ = proofManager.getOWLEditorKit();
Collection<ProofService> proofServices = proofManager_
.getServices();
switch (proofServices.size()) {
case 0:
break;
case 1:
proofManager_.selectService(proofServices.iterator().next());
break;
default:
JComboBox<ProofService> proofServiceSelector = createComboBox(
proofServices);
add(proofServiceSelector, BorderLayout.NORTH);
}
proofManager_.addListener(this);
frame_ = new ProofFrame(proofManager_, kit_);
frameList_ = new ProofFrameList(kit_, frame_);
scrollPane = new JScrollPane(frameList_);
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(scrollPane, BorderLayout.CENTER);
}
public ProofBasedExplanationResult(ProofServiceManager proofServiceMan,
ImportsClosureManager importsClosureMan, OWLAxiom entailment) {
this(new ProofManager(proofServiceMan,
importsClosureMan.getImportsClosure(
proofServiceMan.getOWLEditorKit().getModelManager()
.getActiveOntology()),
entailment));
}
@Override
public void dispose() {
frame_.dispose();
frameList_.dispose();
proofManager_.removeListener(this);
proofManager_.dispose();
}
private JComboBox<ProofService> createComboBox(
Collection<ProofService> proofServices) {
final ProofService[] services = proofServices
.toArray(new ProofService[proofServices.size()]);
final JComboBox<ProofService> selector = new JComboBox<ProofService>(
services);
if (services.length > 0) {
selector.setSelectedItem(services[0]);
proofManager_.selectService(services[0]);
}
selector.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
proofManager_.selectService(
(ProofService) selector.getSelectedItem());
}
});
return selector;
}
@Override
public Dimension getMinimumSize() {
return new Dimension(10, 10);
}
public void updateProofRoot() {
frame_.updateProof();
scrollPane.validate();
}
@Override
public Dimension getPreferredSize() {
Dimension workspaceSize = kit_.getWorkspace().getSize();
int width = (int) (workspaceSize.getWidth() * 0.8);
int height = (int) (workspaceSize.getHeight() * 0.7);
return new Dimension(width, height);
}
@Override
public void proofRootChanged() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateProofRoot();
}
});
}
}
| 28.358491 | 75 | 0.755822 |
a89629b0bb6ccd0cf9c0e2065c28f35f2fccaf06 | 353 | package org.andot.share.basic.entity;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class Organ extends BaseEntity {
private Long organId;
private String organName;
private Byte organType;
private Byte orderCode;
private Integer organParentId;
private String caption;
} | 23.533333 | 39 | 0.767705 |
5015f07a3320e061192703b4dd8de0f5187ce630 | 2,469 | // Copyright 2009 Google Inc. All Rights Reserved.
/**
*
*/
package com.google.ie.business.dao.impl;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import com.google.ie.business.domain.User;
import com.google.ie.dto.RetrievalInfo;
import com.google.ie.test.DatastoreTest;
import org.junit.Before;
import org.junit.Test;
/**
* Test case for UserDaoImpl class
*
* @author ssbains
*
*/
public class UserDaoImplTest extends DatastoreTest {
private UserDaoImpl userDaoImpl;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() {
super.setUp();
userDaoImpl = new UserDaoImpl();
userDaoImpl.setPersistenceManagerFactory(pmf);
}
/**
* Test method for
* {@link com.google.ie.business.dao.impl.UserDaoImpl#saveUser(com.google.ie.business.domain.User)}
* .
*/
@Test
public void testSaveUser() {
User userToBeSaved = new User();
userToBeSaved.setDisplayName("test user");
User savedUser = userDaoImpl.saveUser(userToBeSaved);
assertNotNull(savedUser);
assertEquals(userToBeSaved.getDisplayName(), savedUser.getDisplayName());
}
/**
* Test method for
* {@link com.google.ie.business.dao.impl.UserDaoImpl#getUserById(java.lang.String)}
* .
*/
@Test
public void getUserById() {
User userToBeSaved = new User();
userToBeSaved.setDisplayName("test user");
userToBeSaved.setId("IDString");
userDaoImpl.saveUser(userToBeSaved);
User fetchedUser = userDaoImpl.getUserById(userToBeSaved.getId());
assertNotNull(fetchedUser);
assertEquals(userToBeSaved.getUserKey(), fetchedUser.getUserKey());
}
/**
*
*/
@Test
public void getUsers() {
User userToBeSaved = new User();
userToBeSaved.setDisplayName("test user");
userToBeSaved.setRoleName("admin");
userDaoImpl.saveUser(userToBeSaved);
User userToBeSaved2 = new User();
userToBeSaved2.setDisplayName("test user");
userToBeSaved2.setRoleName("user");
userDaoImpl.saveUser(userToBeSaved2);
RetrievalInfo retrievalInfo = createDummyRetrievalParam(0, 10, "createdOn", "asc");
assertEquals(1, userDaoImpl.getUsers(retrievalInfo, "user", null).size());
}
}
| 28.709302 | 104 | 0.637505 |
4286e92bcc9ad2c1c7b35ddbb60118c048dc4a18 | 2,436 | /*
* The MIT License (MIT)
* Copyright © 2019-2020 <sky>
*
* 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 com.sky.framework.oss.strategy;
import com.sky.framework.oss.model.UploadToken;
import java.io.File;
import java.io.InputStream;
import java.util.Map;
/**
* @author
*/
public abstract class AbstractOssClient implements OssClient {
@Override
public String upload(File file) {
return null;
}
@Override
public String upload(String fileKey, File file) {
return null;
}
@Override
public String upload(String fileKey, File file, String catalog) {
return null;
}
@Override
public String upload(String fileKey, byte[] contents) {
return null;
}
@Override
public String upload(String fileKey, byte[] contents, String catalog) {
return null;
}
@Override
public String upload(String fileKey, InputStream in, String mimeType) {
return null;
}
@Override
public String upload(String fileKey, InputStream in, String mimeType, String catalog) {
return null;
}
@Override
public boolean delete(String fileKey) {
return false;
}
@Override
public String getDownloadUrl(String fileKey) {
return null;
}
@Override
public Map<String, Object> createUploadToken(UploadToken param) {
return null;
}
}
| 28.325581 | 91 | 0.699097 |
6e881be203656fea4c277284a82608439ef22667 | 555 | package org.mytest.processor;
import java.util.Date;
public class MyTestBean {
private String testStr = "testStr";
private Date producDate;
public Date getProducDate() {
return producDate;
}
public void setProducDate(Date producDate) {
this.producDate = producDate;
}
public String getTestStr() {
return testStr;
}
public void setTestStr(String testStr) {
this.testStr = testStr;
}
public void test(){
System.out.println("test T_T");
}
@Override
public String toString() {
return this.testStr + " " + producDate;
}
}
| 15.857143 | 45 | 0.702703 |
b7f8e82e8fd266107ed5235fe1de8dad575e73f7 | 2,613 | /*
* Copyright (c) 2016 Qiscus.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.qiscus.sdk.util;
import android.media.MediaRecorder;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created on : November 02, 2016
* Author : zetbaitsu
* Name : Zetra
* GitHub : https://github.com/zetbaitsu
*/
public class QiscusAudioRecorder {
private MediaRecorder recorder;
private boolean recording;
private String fileName;
public void startRecording() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String audioFileName = "AUDIO_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
storageDir.mkdirs();
String file = storageDir.getAbsolutePath();
file += File.separator + audioFileName + ".m4a";
startRecording(file);
}
private void startRecording(String fileName) throws IOException {
if (!recording) {
this.fileName = fileName;
recording = true;
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
recorder.setOutputFile(fileName);
recorder.prepare();
recorder.start();
}
}
public File stopRecording() {
cancelRecording();
return new File(fileName);
}
public void cancelRecording() {
if (recording) {
recording = false;
try {
recorder.stop();
recorder.release();
recorder = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public boolean isRecording() {
return recording;
}
}
| 30.741176 | 101 | 0.646383 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.