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
|
---|---|---|---|---|---|
3ce6f4b1bd5a4f89abbb2b3df848b42fb831db10 | 544 | /*
* GenericsError.java
*
* Created on September 1, 2005, 9:36 AM
*
*/
import java.util.Collection;
interface GenericsError {
public Collection<String> test(
boolean arg1,
boolean arg2,
Object arg3) ;
}
/*
* GenericsErrorImpl.java
*
* Created on September 1, 2005, 9:37 AM
*
*/
class GenericsErrorImpl implements GenericsError {
public Collection<String> test(
boolean arg1,
boolean arg2,
Object arg3) { return null; }
}
aspect ForceUnpacking {
before() : execution(* *(..)) {}
} | 14.315789 | 50 | 0.636029 |
cddf0cead5704a8fd59e9cdc0451e10ecf365c01 | 3,667 | package net.minecraft.world.item.crafting;
import net.minecraft.core.NonNullList;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.resources.MinecraftKey;
import net.minecraft.world.inventory.InventoryCrafting;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemWrittenBook;
import net.minecraft.world.item.Items;
import net.minecraft.world.level.World;
public class RecipeBookClone extends IRecipeComplex {
public RecipeBookClone(MinecraftKey minecraftkey) {
super(minecraftkey);
}
public boolean matches(InventoryCrafting inventorycrafting, World world) {
int i = 0;
ItemStack itemstack = ItemStack.EMPTY;
for (int j = 0; j < inventorycrafting.getContainerSize(); ++j) {
ItemStack itemstack1 = inventorycrafting.getItem(j);
if (!itemstack1.isEmpty()) {
if (itemstack1.is(Items.WRITTEN_BOOK)) {
if (!itemstack.isEmpty()) {
return false;
}
itemstack = itemstack1;
} else {
if (!itemstack1.is(Items.WRITABLE_BOOK)) {
return false;
}
++i;
}
}
}
return !itemstack.isEmpty() && itemstack.hasTag() && i > 0;
}
public ItemStack assemble(InventoryCrafting inventorycrafting) {
int i = 0;
ItemStack itemstack = ItemStack.EMPTY;
for (int j = 0; j < inventorycrafting.getContainerSize(); ++j) {
ItemStack itemstack1 = inventorycrafting.getItem(j);
if (!itemstack1.isEmpty()) {
if (itemstack1.is(Items.WRITTEN_BOOK)) {
if (!itemstack.isEmpty()) {
return ItemStack.EMPTY;
}
itemstack = itemstack1;
} else {
if (!itemstack1.is(Items.WRITABLE_BOOK)) {
return ItemStack.EMPTY;
}
++i;
}
}
}
if (!itemstack.isEmpty() && itemstack.hasTag() && i >= 1 && ItemWrittenBook.getGeneration(itemstack) < 2) {
ItemStack itemstack2 = new ItemStack(Items.WRITTEN_BOOK, i);
NBTTagCompound nbttagcompound = itemstack.getTag().copy();
nbttagcompound.putInt("generation", ItemWrittenBook.getGeneration(itemstack) + 1);
itemstack2.setTag(nbttagcompound);
return itemstack2;
} else {
return ItemStack.EMPTY;
}
}
public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inventorycrafting) {
NonNullList<ItemStack> nonnulllist = NonNullList.withSize(inventorycrafting.getContainerSize(), ItemStack.EMPTY);
for (int i = 0; i < nonnulllist.size(); ++i) {
ItemStack itemstack = inventorycrafting.getItem(i);
if (itemstack.getItem().hasCraftingRemainingItem()) {
nonnulllist.set(i, new ItemStack(itemstack.getItem().getCraftingRemainingItem()));
} else if (itemstack.getItem() instanceof ItemWrittenBook) {
ItemStack itemstack1 = itemstack.copy();
itemstack1.setCount(1);
nonnulllist.set(i, itemstack1);
break;
}
}
return nonnulllist;
}
@Override
public RecipeSerializer<?> getSerializer() {
return RecipeSerializer.BOOK_CLONING;
}
@Override
public boolean canCraftInDimensions(int i, int j) {
return i >= 3 && j >= 3;
}
}
| 33.036036 | 121 | 0.572948 |
ffcadcd8595f1c0b24d5fcff485d360df2933db9 | 4,004 | /*
Copyright 2011-2016 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.Debug.DebuggerSelectionPanel;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.Help.CHelpFunctions;
import com.google.security.zynamics.binnavi.Help.IHelpInformation;
import com.google.security.zynamics.binnavi.Help.IHelpProvider;
import com.google.security.zynamics.binnavi.debug.debugger.BackEndDebuggerProvider;
import com.google.security.zynamics.binnavi.debug.debugger.interfaces.IDebugger;
import com.google.security.zynamics.binnavi.debug.debugger.interfaces.DebuggerProviderListener;
import java.net.URL;
import javax.swing.JComboBox;
/**
* Combobox class that is used to choose from available debuggers.
*
* The combobox automatically updates itself on changes in the debugger provider that is passed in
* the constructor.
*/
public final class CDebuggerComboBox extends JComboBox<CDebuggerWrapper> implements IHelpProvider {
/**
* Keeps track of changes in the available debuggers.
*/
private final DebuggerProviderListener m_internalDebuggerListener =
new InternalDebuggerListener();
/**
* Provides information about the available debuggers.
*/
private final BackEndDebuggerProvider m_provider;
/**
* Creates a new debugger combobox.
*
* @param provider Provides information about the available debuggers.
*/
public CDebuggerComboBox(final BackEndDebuggerProvider provider) {
m_provider = Preconditions.checkNotNull(provider, "IE01363: Provider can not be null");
// Each existing debugger is added to the combobox of debuggers for
// the user to choose from.
for (final IDebugger debugger : provider.getDebuggers()) {
addItem(new CDebuggerWrapper(debugger));
}
// We want to be notified about new debuggers or deleted debuggers
provider.addListener(m_internalDebuggerListener);
}
/**
* Frees allocated resources.
*/
public void dispose() {
m_provider.removeListener(m_internalDebuggerListener);
}
@Override
public IHelpInformation getHelpInformation() {
return new IHelpInformation() {
@Override
public String getText() {
return "Used to select the active debugger. This debugger is the one who receives input when you click buttons like Resume or set breakpoints.";
}
@Override
public URL getUrl() {
return CHelpFunctions.urlify(CHelpFunctions.MAIN_WINDOW_FILE);
}
};
}
@Override
public CDebuggerWrapper getSelectedItem() {
return (CDebuggerWrapper) super.getSelectedItem();
}
/**
* Keeps the debugger combobox synchronized with the existing debuggers.
*/
private class InternalDebuggerListener implements DebuggerProviderListener {
/**
* When a new debugger is added, we have to add another entry in the combobox for that debugger.
*/
@Override
public void debuggerAdded(final BackEndDebuggerProvider provider, final IDebugger debugger) {
addItem(new CDebuggerWrapper(debugger));
}
/**
* When a debugger is removed, we have to remove the corresponding entry from the combobox.
*/
@Override
public void debuggerRemoved(final BackEndDebuggerProvider provider, final IDebugger debugger) {
for (int i = 0; i < getItemCount(); i++) {
if (getItemAt(i).getObject() == debugger) {
removeItemAt(i);
return;
}
}
}
}
}
| 33.366667 | 152 | 0.738761 |
3366312c52790647e1546ec0f0ff427c49e4cf74 | 2,741 | package com.company;
import java.text.SimpleDateFormat;
public class RescueAnimal {
// Instance variables
private String name;
private String type;
private String gender;
private int age;
private float weight;
private String acquisitionDate;
private SimpleDateFormat statusDate;
private String acquisitionSource;
private Boolean reserved;
private String trainingLocation;
private SimpleDateFormat trainingStart;
private SimpleDateFormat trainingEnd;
private String trainingStatus;
private String inServiceCountry;
private String inServiceCity;
private String inServiceAgency;
private String inServicePOC;
private String inServiceEmail;
private String inServicePhone;
private String inServicePostalAddress;
// Constructor
public RescueAnimal() {
}
// Add Accessor Methods here
public String getAnimalName(){
return name;
}
public String getAnimalType(){
return type;
}
public String getAnimalGender(){
return gender;
}
public int getAnimalAge(){
return age;
}
public float getAnimalWeight(){
return weight;
}
public String getAnimalAcquisitionDate(){
return acquisitionDate;
}
public SimpleDateFormat getAnimalStatusDate(){
return statusDate;
}
public String getAnimalAcquisitionSource(){
return acquisitionSource;
}
public boolean getReserved(){
return reserved;
}
public String getTrainingLocation(){
return trainingLocation;
}
// Add Mutator Methods here
public void setAnimalName(String inputAnimalName){
name = inputAnimalName;
}
public void setAnimalType(String inputAnimalType){
type = inputAnimalType;
}
public void setAnimalGender(String inputAnimalGender){
gender = inputAnimalGender;
}
public void setAnimalAge(int inputAnimalAge){
age = inputAnimalAge;
}
public void setAnimalWeight(float inputAnimalWeight){
weight = inputAnimalWeight;
}
public void setAnimalAcuisitionDate(String inputAnimalAcquisitionDate){
acquisitionDate = inputAnimalAcquisitionDate;
}
public void setAnimalStatusDate(SimpleDateFormat inputAnimalStatusDate){
statusDate = inputAnimalStatusDate;
}
public void setAnimalScquisitionSource(String inputAnimalAcquisitionSource){
acquisitionSource = inputAnimalAcquisitionSource;
}
public void setAnimalReserved(boolean inputAnimalReserve){
reserved = inputAnimalReserve;
}
public void setTrainingLocation(String trainingLocation){
this.trainingLocation = trainingLocation;
}
}
| 26.872549 | 80 | 0.703393 |
ce1c337db377e303fa559cd6a6ca9f106e39e1f7 | 3,358 | package seedu.exercise.logic.parser;
import static seedu.exercise.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.exercise.logic.parser.CliSyntax.PREFIX_CATEGORY;
import static seedu.exercise.logic.parser.CliSyntax.PREFIX_INDEX;
import static seedu.exercise.logic.parser.CliSyntax.PREFIX_NAME;
import java.util.List;
import seedu.exercise.commons.core.index.Index;
import seedu.exercise.logic.commands.DeleteCommand;
import seedu.exercise.logic.commands.DeleteExerciseCommand;
import seedu.exercise.logic.commands.DeleteRegimeCommand;
import seedu.exercise.logic.parser.exceptions.ParseException;
import seedu.exercise.model.property.Name;
/**
* Parses input arguments and creates a new DeleteExerciseCommand object
*/
public class DeleteCommandParser implements Parser<DeleteCommand> {
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns a DeleteCommand object for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public DeleteCommand parse(String args) throws ParseException {
ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_CATEGORY, PREFIX_NAME, PREFIX_INDEX);
if (!argMultimap.arePrefixesPresent(PREFIX_CATEGORY)
|| !argMultimap.getPreamble().isEmpty()) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
String category = ParserUtil.parseCategory(argMultimap.getValue(PREFIX_CATEGORY).get());
if (category.equals("exercise")) {
return parseExercise(argMultimap);
}
if (category.equals("regime")) {
return parseRegime(argMultimap);
}
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE));
}
/**
* Parses arguments and returns DeleteExerciseCommand for execution
*/
private DeleteExerciseCommand parseExercise(ArgumentMultimap argMultimap) throws ParseException {
if (!argMultimap.arePrefixesPresent(PREFIX_INDEX)) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
DeleteExerciseCommand.MESSAGE_USAGE));
}
Index index = ParserUtil.parseIndex(argMultimap.getValue(PREFIX_INDEX).get());
return new DeleteExerciseCommand(index);
}
/**
* Parses arguments and returns DeleteRegimeCommand for execution
*/
private DeleteRegimeCommand parseRegime(ArgumentMultimap argMultimap) throws ParseException {
if (!argMultimap.arePrefixesPresent(PREFIX_NAME)) {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
DeleteRegimeCommand.MESSAGE_USAGE));
}
Name regimeName = ParserUtil.parseName(argMultimap.getValue(PREFIX_NAME).get());
// index present, delete exercise in regime
if (argMultimap.arePrefixesPresent(PREFIX_INDEX)) {
List<Index> indexes = ParserUtil.parseIndexes(argMultimap.getAllValues(PREFIX_INDEX));
return new DeleteRegimeCommand(regimeName, indexes);
} else { //index not present delete regime
return new DeleteRegimeCommand(regimeName, null);
}
}
}
| 39.97619 | 116 | 0.72841 |
254a3bca3574ae67a57a62b9c12e933e6048cda3 | 1,999 | /**
* Exercise 12,13
*/
package com.ciaoshen.thinkinjava.chapter21;
import java.util.concurrent.*;
public class Exercise12 implements Runnable{
private volatile int i=0;
private int duration;
public Exercise12(int duration){
this.duration=duration;
}
public synchronized void f3(){
//System.out.println(Thread.currentThread().getName()+"#f3() @ "+System.currentTimeMillis());
i++;i++;i++;
}
public void run(){
long stop=System.currentTimeMillis()+duration;
//System.out.println("#stop @ "+stop);
while(System.currentTimeMillis()<stop){
//System.out.println(Thread.currentThread().getName()+"#run() @ "+System.currentTimeMillis());
f3();
}
Thread.yield();
}
public int getValue(){return i;}
public class Checker implements Runnable{
public void check(){
int value;
synchronized(Exercise12.this){
value=getValue();
}
if(value%3!=0){
System.out.println(value);
}
}
public void run(){
while(true){
//System.out.println(Thread.currentThread().getName()+"#check() @ "+System.currentTimeMillis());
check();
Thread.yield();
}
}
}
public static void main(String[] args){
ExecutorService mainService=Executors.newCachedThreadPool();
ExecutorService daemonService=Executors.newCachedThreadPool(new ThreadFactory(){
public Thread newThread(Runnable r){
Thread th=new Thread(r);
th.setDaemon(true);
return th;
}
});
Exercise12 task=new Exercise12(10);
Checker checker=task.new Checker();
mainService.execute(task);
daemonService.execute(checker);
mainService.shutdown();
daemonService.shutdown();
}
} | 30.753846 | 112 | 0.557279 |
150b8d48f128381979a318895ac114dbdd05fa95 | 1,118 | package org.folio.rest;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Launcher;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import org.folio.okapi.common.MetricsUtil;
public class RestLauncher extends Launcher {
public static void main(String[] args) {
new RestLauncher().dispatch(args);
}
@Override
public void beforeStartingVertx(VertxOptions options) {
super.beforeStartingVertx(options);
System.out.println("starting rest verticle service..........");
options.setBlockedThreadCheckInterval(1500000);
options.setWarningExceptionTime(1500000);
MetricsUtil.init(options);
}
@Override
public void afterStartingVertx(Vertx vertx) {
super.afterStartingVertx(vertx);
}
@Override
public void beforeDeployingVerticle(DeploymentOptions deploymentOptions) {
super.beforeDeployingVerticle(deploymentOptions);
}
@Override
public void handleDeployFailed(Vertx vertx, String mainVerticle, DeploymentOptions deploymentOptions, Throwable cause) {
super.handleDeployFailed(vertx, mainVerticle, deploymentOptions, cause);
}
}
| 27.268293 | 122 | 0.769231 |
fdcfb0a734707d8d7540fb551eab757dfe1bc631 | 1,131 | package org.jzy3d.plot3d.builder.delaunay;
import java.util.Iterator;
import org.jzy3d.plot3d.builder.delaunay.jdt.Point_dt;
import org.jzy3d.plot3d.builder.delaunay.jdt.Triangle_dt;
/**
*
* @author Mo
*/
public interface Triangulation {
/**
* insert the point to this Delaunay Triangulation. Note: if p is null or
* already exist in this triangulation p is ignored.
*
* @param p
* new vertex to be inserted the triangulation.
*/
public void insertPoint(Point_dt p);
/**
* computes the current set (vector) of all triangles and
* return an iterator to them.
*
* @return an iterator to the current set of all triangles.
*/
public Iterator<Triangle_dt> trianglesIterator();
/**
* returns an iterator to the set of points compusing this triangulation.
* @return iterator to the set of points compusing this triangulation.
*/
public Iterator<Point_dt> verticesIterator();
/**
* @return the number of triangles in the triangulation. <br />
* Note: includes infinife faces!!.
*/
public int trianglesSize();
}
| 25.704545 | 77 | 0.670203 |
4208d426efd696376be123c35fff6ce2957037e1 | 10,633 | package com.rnandroid;
import android.os.BatteryManager;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Promise;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.Locale;
import java.util.Collections;
import java.net.NetworkInterface;
import java.math.BigInteger;
public class StatusModule extends ReactContextBaseJavaModule {
BatteryManager battery = null;
ReactApplicationContext reactContext = null;
WifiManager wfManager = null;
FusedLocationProviderClient fusedLocationClient;
public StatusModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
this.battery = (BatteryManager) reactContext.getSystemService(reactContext.BATTERY_SERVICE);
this.fusedLocationClient = LocationServices.getFusedLocationProviderClient(reactContext);
}
@Override
public String getName() {
return "AndroidSystemStatus";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("brand", Build.BRAND);
constants.put("deviceCountry", this.getCurrentCountry());
constants.put("systemVersion", Build.VERSION.RELEASE);
constants.put("isEmulator", this.isEmulator());
constants.put("apiLevel", Build.VERSION.SDK_INT);
constants.put("model", Build.MODEL);
return constants;
}
private Boolean isEmulator() {
return Build.FINGERPRINT.startsWith("generic")
|| Build.FINGERPRINT.startsWith("unknown")
|| Build.MODEL.contains("google_sdk")
|| Build.MODEL.contains("Emulator")
|| Build.MODEL.contains("Android SDK built for x86")
|| Build.MANUFACTURER.contains("Genymotion")
|| (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
|| "google_sdk".equals(Build.PRODUCT);
}
@ReactMethod
public void getLastKnownLocation(final Promise promise) {
this.fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
WritableMap wm = new WritableNativeMap();
wm.putDouble("latitude", location.getLatitude());
wm.putDouble("longitude", location.getLongitude());
promise.resolve(wm);
} else {
promise.reject("ERROR", "Unknown location");
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
promise.reject(e);
}
})
.addOnCanceledListener(new OnCanceledListener() {
@Override
public void onCanceled() {
promise.reject("ERROR", "Task canceled");
}
});
}
// Using deprecated getConfiguration().locale only if the api leve of device is old
@SuppressWarnings("deprecation")
private String getCurrentCountry() {
Locale current;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//requires api level 24
current = getReactApplicationContext().getResources().getConfiguration().getLocales().get(0);
} else {
// Deprecated in api level 24
current = getReactApplicationContext().getResources().getConfiguration().locale;
}
return current.getCountry();
}
/*
Warning: this functions requires android.permission.ACCESS_WIFI_STATE
*/
private WifiManager getWifiManager() {
if(this.wfManager == null) {
this.wfManager = (WifiManager) this.reactContext.getApplicationContext().getSystemService(this.reactContext.WIFI_SERVICE);
}
return this.wfManager;
}
private WifiInfo getWifiInfo() {
WifiManager wifiMgr = this.getWifiManager();
return wifiMgr.getConnectionInfo();
}
private Boolean isWifiConnected() {
WifiManager wifiMgr = this.getWifiManager();
if(wifiMgr.isWifiEnabled()) { // Wi-Fi adapter is ON
WifiInfo wifiInfo = this.getWifiInfo();
if( wifiInfo.getNetworkId() == -1 ) {
return false; // Not connected to an access point
}
return true; // Connected to an access point
} else {
return false; // Wi-Fi adapter is OFF
}
}
// Using deprecated getConfiguration().locale only if the api leve of device is old
@SuppressWarnings("deprecation")
@ReactMethod
private void getCurrentLanguage(Promise promisse) {
Locale current;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// requires api level 24
current = getReactApplicationContext().getResources().getConfiguration().getLocales().get(0);
} else {
// Deprecated in api level 24
current = getReactApplicationContext().getResources().getConfiguration().locale;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
promisse.resolve( current.toLanguageTag() );
} else {
StringBuilder builder = new StringBuilder();
builder.append(current.getLanguage());
if (current.getCountry() != null) {
builder.append("-");
builder.append(current.getCountry());
}
promisse.resolve( builder.toString() );
}
}
@ReactMethod
public void getFreeDiskStorage(Promise promisse) {
try {
StatFs external = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
promisse.resolve( BigInteger.valueOf(external.getAvailableBytes()).toString() );
} catch (Exception e) {
promisse.reject(e);
}
}
@ReactMethod
public void isWifiConnected(Promise promisse) {
try {
promisse.resolve( this.isWifiConnected() );
} catch (Exception e) {
promisse.reject(e);
}
}
@ReactMethod
public void isWifiEnabled(Promise promisse) {
try {
WifiManager wifiMgr = this.getWifiManager();
promisse.resolve( wifiMgr.isWifiEnabled() );
} catch (Exception e) {
promisse.reject(e);
}
}
@ReactMethod
public void getIpAddress(Promise promisse) {
try {
if(!this.isWifiConnected()) {
promisse.reject("WIFI_DISCONNECTED", "The WiFi adapter are not connected in any access point");
}
} catch (Exception e) {
promisse.reject(e);
}
try {
int ip = getWifiInfo().getIpAddress();
String ipStr = String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
promisse.resolve(ipStr);
} catch(Exception e) {
promisse.reject(e);
}
}
@ReactMethod
public void getMacAddress(Promise promisse) {
// Maybe this work, but we have no guarantee.
String macAddress = "Unknown";
try {
macAddress = getWifiInfo().getMacAddress();
} catch(Exception e) {
promisse.reject(e);
return;
}
String permission = "android.permission.INTERNET";
int res = this.reactContext.checkCallingOrSelfPermission(permission);
// Trying a better way to get this info
if (res == PackageManager.PERMISSION_GRANTED) {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
macAddress = "";
} else {
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}
if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
macAddress = res1.toString();
}
}
} catch (Exception ex) { /* Empty because we already have the info */ }
}
promisse.resolve(macAddress);
}
@ReactMethod
public void getBatteryLevel(Promise promisse) {
try {
Intent batteryIntent = this.reactContext.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryLevel = level / (float) scale;
promisse.resolve(Math.round(batteryLevel*100));
}
catch(Exception e) { // Any exception causes a rejection of the promisse
promisse.reject(e);
}
}
@ReactMethod
public void batteryIsCharging(Promise promisse) {
try {
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.reactContext.getApplicationContext().registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
promisse.resolve(isCharging);
}
catch(Exception e) { // Any exception causes a rejection of the promisse
promisse.reject(e);
}
}
}
| 34.189711 | 140 | 0.636509 |
018e84418822fe82a59bab1ea3a43e9c3631aa0e | 2,627 | package com.a6raywa1cher.jsonrestsecurity.faillimiter;
import com.a6raywa1cher.jsonrestsecurity.web.JsonRestSecurityConfigProperties;
import com.a6raywa1cher.jsonrestsecurity.web.JsonRestSecurityPropertiesConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.core.annotation.Order;
import static org.springframework.core.Ordered.HIGHEST_PRECEDENCE;
/**
* Configures all beans from {@link com.a6raywa1cher.jsonrestsecurity.faillimiter} package.
* <br/>
* FailLimiter can be disabled by property {@code json-rest-security.fail-limiter.enable=false}
*/
@Configuration
@ConditionalOnProperty(prefix = "json-rest-security.fail-limiter", name = "enable", havingValue = "true",
matchIfMissing = true)
@Import(JsonRestSecurityPropertiesConfiguration.class)
@SuppressWarnings("SpringFacetCodeInspection")
public class FailLimiterConfiguration {
private final JsonRestSecurityConfigProperties.FailLimiterConfigProperties properties;
public FailLimiterConfiguration(JsonRestSecurityConfigProperties properties) {
this.properties = properties.getFailLimiter();
}
/**
* Returns the {@link FailLimiterService} bean with {@link LoadingCacheFailLimiterService} implementation.
* <br/>
* Max attempts are being taken from {@code json-rest-security.fail-limiter.max-attempts} property (by default 5).
* <br/>
* The block duration is being taken from {@code json-rest-security.fail-limiter.block-duration} property (by default 1 minute).
* <br/>
* The max cache size is being taken from {@code json-rest-security.fail-limiter.max-cache-size} property (by default 30000).
*
* @return FailLimiterService bean
*/
@Bean
@ConditionalOnMissingBean(FailLimiterService.class)
public FailLimiterService failLimiterService() {
return new LoadingCacheFailLimiterService(properties.getMaxAttempts(), properties.getBlockDuration(), properties.getMaxCacheSize());
}
/**
* Returns the {@link FailLimiterFilter} bean.
* <br/>
* The block duration is being taken from {@code json-rest-security.fail-limiter.block-duration} property (by default 1 minute).
*
* @return FailLimiterFilter bean
*/
@Bean
@Order(HIGHEST_PRECEDENCE)
public FailLimiterFilter failLimiterFilter(FailLimiterService service) {
return new FailLimiterFilter(service, properties.getBlockDuration().toSeconds());
}
}
| 43.065574 | 134 | 0.803198 |
fbbb6dc3ab2cf64ae0bbd662a69ceb1e537d0792 | 3,921 | /*==========================================================================
KJCALC/plotting
PlotCanvasPlots.java
Copyright (c)2017 Kevin Boone, GPL 3.0
==========================================================================*/
package net.kevinboone.math.kjcalc.plotting;
import net.kevinboone.math.kjexpr.*;
import java.math.*;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
The display of the plot lines. Does not include axes or axis lines.
*/
public class PlotCanvasPlots extends JPanel
{
int yAxisWidth = 20;
int xAxisHeight = 20;
final PlotData plotData;
final PlotCanvas plotCanvas;
public PlotCanvasPlots (PlotCanvas _plotCanvas, PlotData _plotData)
{
this.plotData = _plotData;
this.plotCanvas = _plotCanvas;
addMouseMotionListener (new MouseMotionAdapter()
{
@Override
public void mouseMoved(MouseEvent e)
{
if (!plotData.hasData()) return;
Point p = e.getPoint();
int px = p.x;
int py = p.y;
int w = getWidth();
int h = getHeight();
PlotRange r = plotData.getRange();
double xRange = r.xMax - r.xMin;
double yRange = r.yMax - r.yMin;
double xScale = (double) w / xRange;
double yScale = (double) h / yRange;
double x = (double) px / xScale + r.xMin;
double y = (double) (h - py) / yScale + r.yMin;
//System.out.println ("x=" + x + ",y=" + y);
plotCanvas.showCursorPos (x, y);
}
});
}
void drawAxes (Graphics g, int w, int h, PlotRange r)
{
if (!plotData.hasData()) return;
// TODO check ranges
double xRange = r.xMax - r.xMin;
double yRange = r.yMax - r.yMin;
// TODO color
g.setColor (Color.BLACK);
double xScale = (double) w / xRange;
double yScale = (double) h / yRange;
int ordinateX0 = 0;
int ordinateX1 = w;
int ordinateY0 = h - (int)(yScale * -r.yMin) - 1;
int ordinateY1 = h - (int)(yScale * -r.yMin) - 1;
g.drawLine (ordinateX0, ordinateY0, ordinateX1, ordinateY1);
int abscissaX0 = (int)(xScale * -r.xMin);
int abscissaX1 = (int)(xScale * -r.xMin);
int abscissaY0 = 0;
int abscissaY1 = h;
g.drawLine (abscissaX0, abscissaY0, abscissaX1, abscissaY1);
}
void plotLine (Graphics g, PlotPoint[] line, int w, int h, PlotRange r)
{
int l = line.length;
//for (int i = 0; i < l; i++)
// System.out.println ("" + line[i].x + "," + line[i].y);
double xRange = r.xMax - r.xMin;
double yRange = r.yMax - r.yMin;
// TODO check ranges
double xScale = (double) w / xRange;
double yScale = (double) h / yRange;
for (int i = 1; i < l; i++)
{
double x0 = line[i-1].x;
double y0 = line[i-1].y;
double x1 = line[i].x;
double y1 = line[i].y;
double xOff0 = x0 - r.xMin;
double yOff0 = y0 - r.yMin;
double xOff1 = x1 - r.xMin;
double yOff1 = y1 - r.yMin;
g.drawLine ((int)(xOff0 * xScale), h - 1 - (int)(yOff0 * yScale),
(int)(xOff1 * xScale), h - 1- (int)(yOff1 * yScale));
//System.out.println ("" + xOff0 + " " + yOff0);
}
}
protected void repaintAll()
{
int w = getWidth();
int h = getHeight();
repaint (0, 0, 0, w, h);
}
protected void paintComponent (Graphics g)
{
int w = getWidth();
int h = getHeight();
g.setColor (Color.WHITE);
g.fillRect (0, 0, w, h);
PlotRange r = plotData.getRange();
int i = 0;
for (PlotPoint[] l : plotData.getLines())
{
switch (i % 3)
{
case 0: g.setColor (Color.RED); break;
case 1: g.setColor (Color.GREEN); break;
default: g.setColor (Color.BLUE); break;
}
plotLine (g, l, w, h, r);
i++;
}
drawAxes (g, w, h, r);
}
}
| 24.354037 | 76 | 0.536343 |
a6e30dc65e77b4682dd2888055f1fda03762dd35 | 1,551 | /*-
* #%L
* Partial response support for Cloud Endpoints v2
* ---
* Copyright (C) 2018 AODocs (Altirnao Inc)
* ---
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.aodocs.partialresponse.servlet;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.api.server.spi.config.Api;
@Api(name = "test", resource = "test")
public class TestApi {
public TestResource get() {
return new TestResource(1, "a", new String[] {"0", "1"},
new TestResource(2, "b"));
}
public static class TestResource {
@JsonProperty
private final Integer integer;
@JsonProperty
private final String string;
@JsonProperty
private final String[] array;
@JsonProperty
private final TestResource object;
public TestResource(int integer, String string) {
this(integer, string, null, null);
}
public TestResource(int integer, String string, String[] array, TestResource object) {
this.integer = integer;
this.string = string;
this.array = array;
this.object = object;
}
}
}
| 28.2 | 88 | 0.710509 |
fd3a27ef119b279c0ebbaa65902321ea2bf21d99 | 14,598 | /*
* Copyright (C) 2008-2017 Matt Gumbley, DevZendo.org http://devzendo.org
*
* 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.devzendo.commoncode.string;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
/**
* Toolkit for String utility methods.
*
* @author matt
*
*/
public final class StringUtils {
private StringUtils() {
// do not instantiate
}
/**
* A Kilosomething
*/
public static final long KILO = 1024L;
/**
* A Megasomething
*/
public static final long MEGA = KILO * KILO;
/**
* A Gigasomething
*/
public static final long GIGA = MEGA * KILO;
/**
* A Terasomething
*/
public static final long TERA = GIGA * KILO;
/**
* A Petasomething
*/
public static final long PETA = TERA * KILO;
/**
* An Etasomething
*/
public static final long ETA = PETA * KILO;
/**
* Translate a number of bytes into an SI binary representation.
* @param bytes the number of bytes, e.g. 1024
* @return e.g. 1KB
*/
public static String translateByteUnits(final long bytes) {
//myLogger.debug("Converting " + bytes + " into byte units... ");
final Formatter fmt = new Formatter();
final double work = bytes;
if (bytes < KILO) {
//myLogger.debug("BYTES: " + Long.valueOf(bytes));
fmt.format("%4dB", Long.valueOf(bytes));
} else if (bytes < MEGA) {
//myLogger.debug("KILOBYTES: " + Double.valueOf(work / KILO));
fmt.format("%6.2fKB", Double.valueOf(work / KILO));
} else if (bytes < GIGA) {
fmt.format("%6.2fMB", Double.valueOf(work / MEGA));
} else if (bytes < TERA) {
fmt.format("%6.2fGB", Double.valueOf(work / GIGA));
} else if (bytes < PETA) {
fmt.format("%6.2fTB", Double.valueOf(work / TERA));
} else if (bytes < ETA) {
fmt.format("%6.2fPB", Double.valueOf(work / PETA));
} else {
fmt.format("???.?xB");
}
return fmt.toString();
}
/**
* Remove all trailing slashes (directory separators). Directory separators
* are platform-specific.
* @param dirPath the original path e.g. /tmp/// or null (which causes an empty string to be returned)
* @return the path with no trailing slashes e.g. /tmp. Never null; can be empty.
*/
public static String unSlashTerminate(final String dirPath) {
if (dirPath == null) {
return "";
}
final StringBuilder sb = new StringBuilder(dirPath.trim());
unSlashTerminate(sb);
return sb.toString();
}
private static void unSlashTerminate(final StringBuilder sb) {
while (sb.length() != 0 && sb.charAt(sb.length() - 1) == File.separatorChar) {
sb.deleteCharAt(sb.length() - 1);
}
}
/**
* Ensure there is only one trailing slash (directory separator). Directory
* separators are platform-specific.
* @param dirPath the original path e.g. /tmp/// or /foo
* @return the path with one trailing slash e.g. /tmp/ or /foo/
*/
public static String slashTerminate(final String dirPath) {
if (dirPath == null) {
return File.separator;
}
final StringBuilder sb = new StringBuilder(dirPath.trim());
unSlashTerminate(sb);
sb.append(File.separatorChar);
return sb.toString();
}
/**
* Given a name, typically a set name, convert it into a sensible file
* name, i.e. replace spaces and dots with underscores, trim.
* @param name the original name
* @return the sensible version
*/
public static String sensibilizeFileName(final String name) {
if (name == null) {
return "";
}
final StringBuilder sb = new StringBuilder(name.trim());
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == ' ' || sb.charAt(i) == '.') {
sb.setCharAt(i, '_');
}
}
return sb.toString();
}
/**
* How many ms in a second?
*/
public static final long MS_IN_SEC = 1000;
/**
* How many ms in minute?
*/
public static final long MS_IN_MIN = MS_IN_SEC * 60;
/**
* How many ms in an hour?
*/
public static final long MS_IN_HOUR = MS_IN_MIN * 60;
/**
* How many ms in a day?
*/
public static final long MS_IN_DAY = MS_IN_HOUR * 24;
/**
* How many ms in a week?
*/
public static final long MS_IN_WEEK = MS_IN_DAY * 7;
/**
* Translate a number of milliseconds into a human-understandable
* description of the time, i.e. in hours, mins, seconds, and ms.
* @param ms the number of milliseconds
* @return the time, stupid
*/
public static String translateTimeDuration(final long ms) {
long m = ms;
long v = 0;
final StringBuilder sb = new StringBuilder();
if (m > MS_IN_WEEK) {
v = m / MS_IN_WEEK;
m %= MS_IN_WEEK;
sb.append(v);
sb.append("w ");
}
if (m > MS_IN_DAY) {
v = m / MS_IN_DAY;
m %= MS_IN_DAY;
sb.append(v);
sb.append("d ");
}
if (m > MS_IN_HOUR) {
v = m / MS_IN_HOUR;
m %= MS_IN_HOUR;
sb.append(v);
sb.append("h ");
}
if (m > MS_IN_MIN) {
v = m / MS_IN_MIN;
m %= MS_IN_MIN;
sb.append(v);
sb.append("m ");
}
if (m > MS_IN_SEC) {
v = m / MS_IN_SEC;
m %= MS_IN_SEC;
sb.append(v);
sb.append("s ");
}
if (m >= 0) {
sb.append(m);
sb.append("ms ");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == ' ') {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
/**
* Given a number of bytes, create a comma-ized version. e.g. given
* 32768, return "32,768". or given 1123233223, return "1,123,233,223"
* @param bytesTransferred a number
* @return a comma-ized version
*/
public static String translateCommaBytes(final long bytesTransferred) {
final NumberFormat nf = NumberFormat.getNumberInstance();
nf.setGroupingUsed(true);
return nf.format(bytesTransferred);
}
/**
* Translate a bandwidth figure.
* @param dur How many ms the transfer took
* @param bytesTransferred How many bytes were transferred
* @return e.g. 2.3 MB/s
*/
public static String translateBandwidth(final long dur, final long bytesTransferred) {
final StringBuilder sb = new StringBuilder();
final double elapsedSecsD = (dur) / 1000.0;
final double xferRate = (bytesTransferred / MEGA) / elapsedSecsD;
sb.append(translateByteUnits(bytesTransferred));
sb.append(" (");
sb.append(translateCommaBytes(bytesTransferred));
sb.append(" byte");
if (bytesTransferred != 1) {
sb.append("s");
}
sb.append(") transferred in ");
sb.append(translateTimeDuration(dur));
sb.append(" (");
final Formatter fmt = new Formatter();
fmt.format("%.2f", Double.valueOf(xferRate));
sb.append(fmt.toString());
sb.append(" MB/s)");
return sb.toString();
}
/**
* Translate a fraction into a percentage
* @param numerator e.g. 5
* @param denominator e.g. 10
* @return e.g. 50%
*/
public static Object translatePercentage(final long numerator, final long denominator) {
final double p = ((double) numerator / (double) denominator) * 100.0;
return new Formatter().format("%3.2f%%", Double.valueOf(p));
}
/**
* Join words together
* @param words the words to join
* @param inBetween what goes between
* @return the joined up string
*/
public static String join(final String[] words, final String inBetween) {
return join(null, words, null, inBetween);
}
/**
* Join words together
* @param sb a StringBuilder to fill
* @param start something to put at the start
* @param words the words to join
* @param end something to put at the end
* @param inBetween what goes between each word
*/
public static void join(final StringBuilder sb, final String start, final String[] words, final String end, final String inBetween) {
if (start != null) {
sb.append(start);
}
if (words.length != 0) {
for (int i = 0; i < words.length - 1; i++) {
sb.append(words[i]);
sb.append(inBetween);
}
sb.append(words[words.length - 1]);
}
if (end != null) {
sb.append(end);
}
}
/**
* Join words together
* @param start something to put at the start
* @param words the words to join
* @param end something to put at the end
* @param inBetween what goes between each word
* @return the joined up string
*/
public static String join(final String start, final String[] words, final String end, final String inBetween) {
final StringBuilder sb = new StringBuilder();
join(sb, start, words, end, inBetween);
return sb.toString();
}
/**
* Join words together
* @param words the words to join
* @param inBetween what goes between each word
* @return the joined up string
*/
public static String join(final List<String> words, final String inBetween) {
return join(words.toArray(new String[0]), inBetween);
}
/**
* Given an array of objects, and an object-to-String function, return an
* array produced by running each object through the function
* @param objects an array of objects
* @param func a MapStringFunction that does some object-to-object transform
* @return the transformed objects, as Strings
*/
public String[] map(final Object[] objects, final MapStringFunction func) {
final ArrayList < String > list = new ArrayList < String >();
for (final Object object : objects) {
list.add(func.mapToString(object));
}
return list.toArray(new String[0]);
}
/**
* A string mapping function
* @author matt
*
*/
public interface MapStringFunction {
/**
* Map an Object to a String
* @param object some object
* @return the String that it maps to
*/
String mapToString(final Object object);
}
/**
* Given an array of objects, and an object-to-object function, return an
* array produced by running each object through the function
* @param objects an array of objects
* @param func a MapFunction that does some object-to-object transform
* @return the transformed objects
*/
public Object[] map(final Object[] objects, final MapFunction func) {
final ArrayList < Object > list = new ArrayList < Object >();
for (final Object object : objects) {
list.add(func.mapToObject(object));
}
return list.toArray(new String[0]);
}
/**
* An Object mapping function
* @author matt
*
*/
public interface MapFunction {
/**
* @param object an input Object
* @return an output Object
*/
Object mapToObject(final Object object);
}
/**
* Generate a simplistic pluralisation of a word. Don't expect
* linguistic correctness if you ask it to pluralise sheep, fish,
* octopus. Dog/Dogs is as far as it goes.
*
* @param word the word to pluralise, e.g. "file"
* @param num how many of these things there are
* @return the word, possibly with 's' added.
*/
public static String pluralise(final String word, final int num) {
return num == 1 ? word : (word + "s");
}
/**
* Return the correct word, are or is, depending on some number,
* e.g. there are 2, there is 1.
* @param num a number
* @return are or is
*/
public static String getAreIs(final int num) {
return num == 1 ? "is" : "are";
}
/**
* Encode the given string to an ASCII byte array
* @param input the input string
* @return the ASCII bytes
*/
public static byte[] stringToASCII(final String input) {
try {
return input.getBytes("ASCII");
} catch (final UnsupportedEncodingException e) {
// when hell freezes over :-)
return new byte[0];
}
}
/**
* Convert a string into a number os asterisks, as long as
* the input, for the masking of sentivie information, e.g.
* passwords
* @param input the input string, can be null
* @return the converted output, or an empty string - never
* null
*/
public static String maskSensitiveText(final String input) {
if (input == null) {
return "";
}
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
sb.append("*");
}
return sb.toString();
}
}
| 32.584821 | 138 | 0.556241 |
29a29f6967badd9823e724a109690c629697db65 | 5,866 | /**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2009 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
* 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.collectionspace.authentication.spring;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.security.acl.Group;
import javax.security.auth.Subject;
import org.collectionspace.authentication.CSpaceTenant;
import org.collectionspace.authentication.spi.AuthNContext;
import org.springframework.security.authentication.jaas.JaasAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* SpringAuthNContext provides utilities to CSpace services runtime
* @author
*/
final public class SpringAuthNContext extends AuthNContext {
//private static final String SUBJECT_CONTEXT_KEY = "javax.security.auth.Subject.container";
public String getUserId() {
String result = ANONYMOUS_USER;
Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
if (authToken != null) {
result = authToken.getName();
}
return result;
}
/**
* retrieve tenant ids from Jaas LoginContext
* @return
*/
@Override
public String[] getTenantIds() {
ArrayList<String> tenantList = new ArrayList<String>();
CSpaceTenant[] tenants = getTenants();
for (CSpaceTenant tenant : tenants) {
tenantList.add(tenant.getId());
}
return tenantList.toArray(new String[0]);
}
@Override
public String getCurrentTenantId() {
String result = ANONYMOUS_TENANT_ID;
String userId = getUserId();
if (userId.equals(ANONYMOUS_USER) == false && userId.equals(SPRING_ADMIN_USER) == false) {
String[] tenantIds = getTenantIds();
if (tenantIds.length < 1) {
throw new IllegalStateException("No tenant associated with user=" + getUserId());
}
result = getTenantIds()[0];
}
return result;
}
public CSpaceTenant[] getTenants() {
List<CSpaceTenant> tenants = new ArrayList<CSpaceTenant>();
Subject caller = getSubject();
if (caller == null) {
if (getUserId().equals(SPRING_ADMIN_USER) == false) {
String msg = String.format("Could not find Subject in SpringAuthNContext for user '%s'!", getUserId());
System.err.println(msg);
}
return tenants.toArray(new CSpaceTenant[0]);
}
Set<Group> groups = null;
groups = caller.getPrincipals(Group.class);
if (groups != null && groups.size() == 0) {
String msg = "no role(s)/tenant(s) found!";
//TODO: find out why no roles / tenants found
//FIXME: if logger is loaded when authn comes up, use it
//logger.warn(msg);
System.err.println(msg);
return tenants.toArray(new CSpaceTenant[0]);
}
for (Group g : groups) {
if ("Tenants".equals(g.getName())) {
Enumeration members = g.members();
while (members.hasMoreElements()) {
CSpaceTenant tenant = (CSpaceTenant) members.nextElement();
tenants.add(tenant);
//FIXME: if logger is loaded when authn comes up, use it
// if (logger.isDebugEnabled()) {
// logger.debug("found tenant id=" + tenant.getId()
// + " name=" + tenant.getName());
// }
}
}
}
return tenants.toArray(new CSpaceTenant[0]);
}
@Override
public String getCurrentTenantName() {
String result = ANONYMOUS_TENANT_NAME;
if (getUserId().equals(ANONYMOUS_USER) == false) {
CSpaceTenant[] tenants = getTenants();
if (tenants.length < 1) {
throw new IllegalStateException("No tenant associated with user=" + getUserId());
}
result = getTenants()[0].getName();
}
return result;
}
public Subject getSubject() {
Subject caller = null;
//if Spring was not used....
//caller = (Subject) PolicyContext.getContext(SUBJECT_CONTEXT_KEY);
//FIXME the follow call should be protected with a privileged action
//and must only be available to users with super privileges
//Spring does not offer any easy mechanism
//It is a bad idea to ship with a kernel user...kernel user should be
//created at startup time perhaps and used it here
Authentication authToken = SecurityContextHolder.getContext().getAuthentication();
JaasAuthenticationToken jaasToken = null;
if (authToken instanceof JaasAuthenticationToken) {
jaasToken = (JaasAuthenticationToken) authToken;
caller = (Subject) jaasToken.getLoginContext().getSubject();
}
return caller;
}
}
| 36.209877 | 117 | 0.636379 |
4ed8c13be406957f4ea248b314cc14ff4657ab49 | 6,947 | package org.cosmicode.freelancr.service;
import allbegray.slack.SlackClientFactory;
import allbegray.slack.exception.SlackArgumentException;
import allbegray.slack.exception.SlackResponseErrorException;
import allbegray.slack.type.Group;
import allbegray.slack.webapi.SlackWebApiClient;
import org.cosmicode.freelancr.config.Constants;
import org.cosmicode.freelancr.domain.Position;
import org.cosmicode.freelancr.domain.Project;
import org.cosmicode.freelancr.domain.User;
import org.cosmicode.freelancr.domain.enumeration.ProjectStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
* Service Implementation for Slack integration.
*/
@Service
@Transactional
public class SlackIntegrationService {
private final Logger log = LoggerFactory.getLogger(SlackIntegrationService.class);
private final SlackWebApiClient slackWebApiClient;
public SlackIntegrationService() {
this.slackWebApiClient = SlackClientFactory.createWebApiClient(Constants.SLACK_TOKEN);
}
/**
* Create the private slack channel for the team.
* @param project
* @return updated project.
*/
public Project createSlackChannel(Project project) {
log.debug("Create Slack Private Channel for project: " + project.getId());
try {
Group projectSlackChannel = slackWebApiClient.createGroup("p-" + project.getId());
log.debug(projectSlackChannel.toString());
slackWebApiClient.setGroupTopic(projectSlackChannel.getId(), project.getTitle());
slackWebApiClient.setGroupPurpose(projectSlackChannel.getId(), project.getDescription());
slackWebApiClient.postMessage(projectSlackChannel.getId(), project.getTitle() + " project has been started.");
project.setSlackChannel(projectSlackChannel.getId());
} catch (SlackArgumentException e) {
log.error(e.getMessage());
project.setSlackChannel(null);
} catch (SlackResponseErrorException e) {
log.error(e.getMessage());
project.setSlackChannel(null);
}
return project;
}
/**
* Adds current project members to the private Slack Channel
* @param project
*/
public void updateSlackMembership(Project project) {
Group slackGroup = slackWebApiClient.getGroupInfo(project.getSlackChannel());
if(slackGroup == null) return;
List<allbegray.slack.type.User> slackUserList = slackWebApiClient.getUserList();
if(slackUserList.isEmpty()) return;
log.debug("Add project administrator to channel: {}", project.getUser().getLogin());
Optional<allbegray.slack.type.User> projectAdminSlackUser = slackUserList.stream().filter(o -> project.getUser().getEmail().equals(o.getProfile().getEmail())).findFirst();
if(!projectAdminSlackUser.isPresent()) {
log.error("Project admin does not have a slack user associated with his email, slack not created.");
return;
}
slackWebApiClient.inviteUserToGroup(project.getSlackChannel(), projectAdminSlackUser.get().getId());
for (Position position: project.getPositions()) {
for (User hiredUser: position.getHiredUsers()) {
log.debug("Add project collaborator to slack: {}", hiredUser.getLogin());
Optional<allbegray.slack.type.User> collaboratorSlackUser = slackUserList.stream().filter(o -> hiredUser.getEmail().equals(o.getProfile().getEmail())).findFirst();
if(collaboratorSlackUser.isPresent()) {
slackWebApiClient.inviteUserToGroup(project.getSlackChannel(), collaboratorSlackUser.get().getId());
} else {
log.error("{} does not have a slack user associated with his email", hiredUser.getEmail());
}
}
}
}
/**
* Gets last 10 messages for slack channel.
* @param slackChannel
* @return
*/
public List<allbegray.slack.type.Message> getSlackLatestMessages(String slackChannel) {
allbegray.slack.type.History groupHistory = slackWebApiClient.getGroupHistory(slackChannel, 10);
return groupHistory.getMessages();
}
/**
* Remove current project members to the private Slack Channel
* @param project
*/
public void removeSlackMembership(Project project){
Group slackGroup = slackWebApiClient.getGroupInfo(project.getSlackChannel());
if(slackGroup == null) return;
List<allbegray.slack.type.User> slackUserList = slackWebApiClient.getUserList();
if(slackUserList.isEmpty()) return;
Optional<allbegray.slack.type.User> projectAdminSlackUser = slackUserList.stream().filter(o -> project.getUser().getEmail().equals(o.getProfile().getEmail())).findFirst();
if(!projectAdminSlackUser.isPresent()) {
log.error("Project admin does not have a slack user associated with his email, slack not created.");
return;
}
try {
for (String slackUser: slackGroup.getMembers()) {
log.debug("Checking channel access for {}", slackUser);
if (!slackUser.equals(projectAdminSlackUser.get().getId()) && !slackUser.equals(Constants.SLACK_ADMIN_USER)){ //Do not remove freelancer nor project admin.
slackWebApiClient.kickUserFromGroup(slackGroup.getId(), slackUser);
log.debug("Removed {} from project channel", slackUser);
}
}
} catch(Exception e){
log.error(e.getMessage());
}
}
/**
* Send a message to a project channel
* @param slackChannel
* @param message
* @return true if message was sent correctly.
*/
public boolean sendMessageChannel(String slackChannel, String message){
try {
//Check channel exist
Group slackGroup = slackWebApiClient.getGroupInfo(slackChannel);
if(slackGroup == null) { return false; }
//send message
slackWebApiClient.postMessage(slackChannel, message);
} catch(Exception e){
log.error(e.getMessage());
return false;
}
return true;
}
/**
* Update slack Channel membership after the positions changed on an "IN_PROGRESS" project
* @param project
* @return true if update completed correct.
*/
public boolean updateSlackPositionsChanged(Project project){
if (!project.getStatus().equals(ProjectStatus.IN_PROGRESS)) return false;
// Remove all current slack users.
removeSlackMembership(project);
// Add all current project collaborators to slack.
updateSlackMembership(project);
return true;
}
}
| 37.755435 | 179 | 0.669498 |
82fa258af2d46fb4b9f39a9df5f3af0367d190f5 | 4,459 | // Copyright 2020 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package build.buildfarm.common.redis;
import com.google.common.collect.SetMultimap;
import java.util.List;
///
/// @class ProvisionedRedisQueue
/// @brief A queue that is designed to hold particularly provisioned
/// elements.
/// @details A provisioned redis queue is an implementation of a queue data
/// structure which internally uses a redis cluster to distribute the
/// data across shards. Its important to know that the lifetime of
/// the queue persists before and after the queue data structure is
/// created (since it exists in redis). Therefore, two redis queues
/// with the same name, would in fact be the same underlying redis
/// queue. This redis queue comes with a list of required provisions.
/// If the queue element does not meet the required provisions, it
/// should not be stored in the queue. Provision queues are intended
/// to represent particular operations that should only be processed
/// by particular workers. An example use case for this would be to
/// have two dedicated provision queues for CPU and GPU operations.
/// CPU/GPU requirements would be determined through the remote api's
/// command platform properties. We designate provision queues to
/// have a set of "required provisions" (which match the platform
/// properties). This allows the scheduler to distribute operations
/// by their properties and allows workers to dequeue from particular
/// queues.
///
public class ProvisionedRedisQueue {
///
/// @field requiredProvisions
/// @brief The required provisions of the queue.
/// @details The required provisions to allow workers and operations to be
/// added to the queue. These often match the remote api's command
/// platform properties.
///
private SetMultimap<String, String> requiredProvisions;
///
/// @field queue
/// @brief The queue itself.
/// @details A balanced redis queue designed to hold particularly provisioned
/// elements.
///
private BalancedRedisQueue queue;
///
/// @brief Constructor.
/// @details Construct the provision queue.
/// @param name The global name of the queue.
/// @param hashtags Hashtags to distribute queue data.
/// @param requiredProvisions The required provisions of the queue.
///
public ProvisionedRedisQueue(
String name, List<String> hashtags, SetMultimap<String, String> requiredProvisions) {
this.queue = new BalancedRedisQueue(name, hashtags);
this.requiredProvisions = requiredProvisions;
}
///
/// @brief Checks required provisions.
/// @details Checks whether the provisions given fulfill all of the required
/// provisions of the queue.
/// @param provisions Provisions to check that requirements are met.
/// @return Whether the queue is eligible based on the provisions given.
/// @note Suggested return identifier: isEligible.
///
public boolean isEligible(SetMultimap<String, String> provisions) {
for (String checkedProvision : requiredProvisions.asMap().keySet()) {
if (!provisions.asMap().containsKey(checkedProvision)) {
return false;
}
}
return true;
}
///
/// @brief Get queue.
/// @details Obtain the internal queue.
/// @return The internal queue.
/// @note Suggested return identifier: queue.
///
public BalancedRedisQueue queue() {
return queue;
}
///
/// @brief Get provisions.
/// @details Obtain the required provisions.
/// @return The required provisions.
/// @note Suggested return identifier: provisions.
///
public SetMultimap<String, String> provisions() {
return requiredProvisions;
}
}
| 40.908257 | 91 | 0.684234 |
bb242dab697970a1d4f477076a9317581dfcd831 | 9,189 | package com.hypertrack.ridesharing.adapters;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.hypertrack.maps.google.widget.GoogleMapAdapter;
import com.hypertrack.sdk.views.maps.HyperTrackMap;
import com.hypertrack.sdk.views.maps.models.MapLocation;
import com.hypertrack.sdk.views.maps.models.MapObject;
import com.hypertrack.sdk.views.maps.models.MapTrip;
import com.hypertrack.sdk.views.dao.DeviceStatus;
import com.hypertrack.sdk.views.dao.Location;
import com.hypertrack.sdk.views.dao.Trip;
import com.hypertrack.ridesharing.R;
import com.hypertrack.ridesharing.utils.MapUtils;
import com.hypertrack.ridesharing.utils.TextFormatUtils;
import java.util.concurrent.TimeUnit;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
public class MapInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
private final LayoutInflater layoutInflater;
private final GoogleMapAdapter mapAdapter;
public MapInfoWindowAdapter(Context context, GoogleMapAdapter mapAdapter) {
layoutInflater = LayoutInflater.from(context);
this.mapAdapter = mapAdapter;
}
@SuppressLint("CheckResult")
@Override
public View getInfoWindow(final Marker marker) {
MapObject mapObject = mapAdapter.findMapObjectByMarker(marker);
if (mapObject != null) {
Single<String> single;
ViewHolder viewHolder = (ViewHolder) marker.getTag();
if (mapObject.getType() == HyperTrackMap.TRIP_MAP_OBJECT_TYPE) {
marker.setInfoWindowAnchor(4.2f, 1.6f);
GoogleMapAdapter.GMapTrip mapTrip = (GoogleMapAdapter.GMapTrip) mapObject;
if (mapTrip.getDestinationMarker().getId().equals(marker.getId())) {
if (viewHolder == null) {
View view = layoutInflater.inflate(R.layout.info_window_to, null);
viewHolder = new ViewHolder(view);
marker.setTag(viewHolder);
}
single = viewHolder.updateTripDestination(mapTrip);
} else {
if (!mapTrip.trip.getStatus().equals("completed")) {
return null;
}
if (viewHolder == null) {
View view = layoutInflater.inflate(R.layout.info_window_from, null);
viewHolder = new ViewHolder(view);
marker.setTag(viewHolder);
}
single = viewHolder.updateTripOrigin(mapTrip);
}
} else {
marker.setInfoWindowAnchor(3.4f, 1.3f);
MapLocation mapLocation = (MapLocation) mapObject;
if (viewHolder == null) {
View view = layoutInflater.inflate(R.layout.info_window_from, null);
viewHolder = new ViewHolder(view);
marker.setTag(viewHolder);
}
single = viewHolder.updateLocation(mapLocation);
}
single.subscribe(new Consumer<String>() {
@Override
public void accept(String s) throws Exception {
if (!TextUtils.isEmpty(s)) {
marker.showInfoWindow();
}
}
});
return viewHolder.view;
}
return null;
}
@Override
public View getInfoContents(Marker marker) {
return null;
}
@SuppressLint("CheckResult")
static class ViewHolder {
View view;
TextView title;
TextView text;
ViewHolder(View view) {
this.view = view;
title = view.findViewById(R.id.title);
text = view.findViewById(R.id.text);
}
Single<String> updateLocation(MapLocation mapLocation) {
String status = view.getContext().getString(R.string.my_location);
if (mapLocation.deviceStatus != -1) {
if (DeviceStatus.STOP == mapLocation.deviceStatus) {
status = view.getContext().getString(R.string.stopped);
} else {
status = view.getContext().getString(R.string.driver);
}
}
title.setText(status);
LatLng latLng = new LatLng(mapLocation.location.getLatitude(), mapLocation.location.getLongitude());
return MapUtils.getAddress(view.getContext(), latLng).map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
if (!s.equals(text.getText().toString())) {
text.setText(s);
return s;
}
return "";
}
});
}
Single<String> updateTripDestination(MapTrip mapTrip) {
Trip.Destination destination = mapTrip.trip.getDestination();
if (mapTrip.trip.getStatus().equals("completed")) {
if (destination != null) {
return MapUtils.getAddress(view.getContext(),
new LatLng(destination.getLatitude(), destination.getLongitude()))
.map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
if (!s.equals(title.getText().toString())) {
title.setText(s);
return s;
}
return "";
}
});
}
if (mapTrip.trip.getEndDate() != null) {
String date = TextFormatUtils.getRelativeDateTimeString(view.getContext(), mapTrip.trip.getEndDate().getTime());
String text = view.getContext().getString(R.string.dropoff) + " | " + date;
this.text.setText(text);
}
} else {
if (mapTrip.trip.getEstimate() != null
&& mapTrip.trip.getEstimate().getRoute() != null
&& mapTrip.trip.getEstimate().getRoute().getDuration() != null) {
long estimate = TimeUnit.SECONDS.toMinutes(
mapTrip.trip.getEstimate().getRoute().getDuration()
);
title.setText(String.format(view.getContext().getString(R.string.mins), estimate));
}
if (destination != null) {
LatLng latLng = new LatLng(destination.getLatitude(), destination.getLongitude());
return MapUtils.getAddress(view.getContext(), latLng).map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
if (!s.equals(text.getText().toString())) {
text.setText(s);
return s;
}
return "";
}
});
}
}
return null;
}
Single<String> updateTripOrigin(MapTrip mapTrip) {
if (mapTrip.trip.getStatus().equals("completed")) {
if (mapTrip.trip.getSummary() != null && !mapTrip.trip.getSummary().getLocations().isEmpty()) {
Location location = mapTrip.trip.getSummary().getLocations().get(0);
return MapUtils.getAddress(view.getContext(),
new LatLng(location.getLatitude(), location.getLongitude()))
.map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
if (!s.equals(title.getText().toString())) {
title.setText(s);
return s;
}
return "";
}
});
}
if (mapTrip.trip.getStartDate() != null) {
String date = TextFormatUtils.getRelativeDateTimeString(view.getContext(), mapTrip.trip.getStartDate().getTime());
String text = view.getContext().getString(R.string.dropoff) + " | " + date;
this.text.setText(text);
}
}
return null;
}
}
}
| 43.966507 | 134 | 0.521167 |
1a94cf1e6a3abe2e93e3a336e0f68b8e53859dda | 2,682 | /*
* Copyright 2018 onwards - Sunit Katkar ([email protected])
*
* 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.sunitkatkar.blogspot.util;
/**
* When the end user submits the login form, the tenant id is required to
* determine which database to connect to. This needs to be captured in the
* spring security authentication mechanism, specifically in the
* {@link UsernamePasswordAuthenticationFilter} implemented by
* {@link CustomAuthenticationFilter}. This tenant id is then required by the
* {@link CurrentTenantIdentifierResolver} implemeted by the
* {@link CurrentTenantIdentifierResolverImpl}
*
* <br/>
* <br/>
* <b>Explanation:</b> Thread Local can be considered as a scope of access, like
* a request scope or session scope. It’s a thread scope. You can set any object
* in Thread Local and this object will be global and local to the specific
* thread which is accessing this object. Global and local at the same time? :
*
* <ul>
* <li>Values stored in Thread Local are global to the thread, meaning that they
* can be accessed from anywhere inside that thread. If a thread calls methods
* from several classes, then all the methods can see the Thread Local variable
* set by other methods (because they are executing in same thread). The value
* need not be passed explicitly. It’s like how you use global variables.</li>
* <li>Values stored in Thread Local are local to the thread, meaning that each
* thread will have it’s own Thread Local variable. One thread can not
* access/modify other thread’s Thread Local variables.</li>
* </ul>
*
* @see https://dzone.com/articles/painless-introduction-javas-threadlocal-storage
* @author Sunit Katkar, [email protected]
* (https://sunitkatkar.blogspot.com/)
* @since ver 1.0 (May 2018)
* @version 1.0
*/
public class TenantContextHolder {
private static final ThreadLocal<String> CONTEXT = new ThreadLocal<>();
public static void setTenantId(String tenant) {
CONTEXT.set(tenant);
}
public static String getTenant() {
return CONTEXT.get();
}
public static void clear() {
CONTEXT.remove();
}
} | 40.636364 | 82 | 0.729306 |
27610ff2a212dc72bda38679c629ea57cb8bd319 | 7,438 | package de.rub.bi.inf.baclient.core.actions;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import com.apstex.gui.core.kernel.Kernel;
import com.apstex.gui.core.model.applicationmodel.ApplicationModelNode;
import com.apstex.ifctoolbox.ifcmodel.IfcModel;
import com.apstex.ifctoolbox.ifcmodel.IfcModel.IfcSchema;
import de.rub.bi.inf.baclient.core.ifc.IfcUtil;
import de.rub.bi.inf.baclient.core.model.ChoiceProperty;
import de.rub.bi.inf.baclient.core.model.XPlanungModel;
import de.rub.bi.inf.baclient.core.model.XPlanungModelContainer;
import de.rub.bi.inf.baclient.core.views.ifc.AddXPlanungToIfcModelView;
import de.rub.bi.inf.baclient.core.views.ifc.IfcExtrusionModelCreator;
import javafx.application.Platform;
import net.opengis.gml._3.AbstractFeatureType;
public class XPlanungActionCollection {
public static class SelectAction implements ActionListener {
private Object obj = null;
public SelectAction(Object obj){
this.obj = obj;
}
@Override
public void actionPerformed(ActionEvent e) {
if(obj instanceof ArrayList) {
XPlanungActionUtils.select((ArrayList)obj);
}else {
XPlanungActionUtils.select(obj);
}
}
};
public static class DeselectAction implements ActionListener {
private Object obj = null;
public DeselectAction(Object obj){
this.obj = obj;
}
@Override
public void actionPerformed(ActionEvent e) {
if(obj instanceof ArrayList) {
XPlanungActionUtils.deselect((ArrayList)obj);
}else {
XPlanungActionUtils.deselect(obj);
}
}
};
public static class HideAction implements ActionListener {
private Object obj = null;
public HideAction(Object obj){
this.obj = obj;
}
@Override
public void actionPerformed(ActionEvent e) {
if(obj instanceof ArrayList) {
XPlanungActionUtils.setInvisible((ArrayList)obj);
}else {
XPlanungActionUtils.setInvisible(obj);
}
}
};
public static class ShowAction implements ActionListener {
private Object obj = null;
public ShowAction(Object obj){
this.obj = obj;
}
@Override
public void actionPerformed(ActionEvent e) {
if(obj instanceof ArrayList) {
XPlanungActionUtils.setVisible((ArrayList)obj);
}else {
XPlanungActionUtils.setVisible(obj);
}
}
};
public static class ShowOnlyAction implements ActionListener {
private Object obj = null;
public ShowOnlyAction(Object obj){
this.obj = obj;
}
@Override
public void actionPerformed(ActionEvent e) {
for(XPlanungModel model : XPlanungModelContainer.getInstance().getModels()) {
XPlanungActionUtils.setInvisible(model);
}
if(obj instanceof ArrayList) {
XPlanungActionUtils.setVisible((ArrayList)obj);
}else {
XPlanungActionUtils.setVisible(obj);
}
}
};
public static class TransparencyAction implements ActionListener {
private Object obj = null;
public TransparencyAction(Object obj){
this.obj = obj;
}
@Override
public void actionPerformed(ActionEvent e) {
if(obj instanceof ArrayList) {
XPlanungActionUtils.setTransparent((ArrayList)obj);
}else {
XPlanungActionUtils.setTransparent(obj);
}
}
};
public static class AddToIfcAction implements ActionListener {
private ArrayList<Object> objs = null;
public AddToIfcAction(ArrayList<Object> objs){
this.objs = objs;
}
@Override
public void actionPerformed(ActionEvent e) {
CountDownLatch doneLatch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
@Override
public void run() {
ArrayList<ChoiceProperty<IfcModel>> nodes = new ArrayList<>();
for(ApplicationModelNode node : Kernel.getApplicationModelRoot().getNodes()) {
nodes.add(new ChoiceProperty<IfcModel>((IfcModel)node.getStepModel()) {
@Override
public String toString() {
return node.toString();
}
});
}
ChoiceProperty<IfcModel> newIFC4Model = new ChoiceProperty<IfcModel>(IfcUtil.createEmptyModel(IfcSchema.IFC4)) {
@Override
public String toString() {
return "New IFC4 Model";
}
};
nodes.add(newIFC4Model);
ChoiceProperty<IfcModel> newIFC2x3Model = new ChoiceProperty<IfcModel>(IfcUtil.createEmptyModel(IfcSchema.IFC2X3)) {
@Override
public String toString() {
return "New IFC2x3 Model";
}
};
nodes.add(newIFC2x3Model);
XPlanungModel xModel = null;
ArrayList<AbstractFeatureType> features = new ArrayList<>();
for(Object o : objs) {
xModel = XPlanungActionUtils.findXPlanungModel(o);
if (o instanceof AbstractFeatureType) {
AbstractFeatureType feature = (AbstractFeatureType) o;
features.add(feature);
}else if(o instanceof Entry<?, ?>) {
if(((Entry<?, ?>)o).getKey() instanceof Class) {
features.addAll((ArrayList<AbstractFeatureType>) ((Entry) o).getValue());
}else if(((Entry<?, ?>)o).getKey() instanceof String) {
HashMap<Class, ArrayList<AbstractFeatureType>> featureMaps = (HashMap<Class, ArrayList<AbstractFeatureType>>) ((Entry) o).getValue();
for(ArrayList<AbstractFeatureType> afList : featureMaps.values()) {
features.addAll(afList);
}
}
}
}
if(xModel != null) {
new AddXPlanungToIfcModelView(newIFC4Model, nodes, features, xModel.getLocalTranslation());
}
doneLatch.countDown();
}
});
}
}
public static class CreateExtusionModelAction implements ActionListener {
private ArrayList<Object> objs = null;
public CreateExtusionModelAction(ArrayList<Object> objs){
this.objs = objs;
}
@Override
public void actionPerformed(ActionEvent e) {
CountDownLatch doneLatch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
@Override
public void run() {
XPlanungModel model = null;
ArrayList<AbstractFeatureType> features = new ArrayList<>();
for(Object o : objs) {
model = (XPlanungModel)XPlanungActionUtils.findXPlanungModel(o);
if (o instanceof AbstractFeatureType) {
AbstractFeatureType feature = (AbstractFeatureType) o;
features.add(feature);
}else if(o instanceof Entry<?, ?>) {
if(((Entry<?, ?>)o).getKey() instanceof Class) {
features.addAll((ArrayList<AbstractFeatureType>) ((Entry) o).getValue());
}else if(((Entry<?, ?>)o).getKey() instanceof String) {
HashMap<Class, ArrayList<AbstractFeatureType>> featureMap = (HashMap<Class, ArrayList<AbstractFeatureType>>) ((Entry) o).getValue();
for(ArrayList<AbstractFeatureType> afList : featureMap.values()) {
features.addAll(afList);
}
}
}
}
new IfcExtrusionModelCreator(features, model);
}
});
doneLatch.countDown();
}
}
}
| 26.949275 | 142 | 0.647889 |
68f2546f12560e9bb5e10934bf37ae826968d78d | 913 | package com.tazine.design.cor;
import com.tazine.design.cor.handler.PriceHandler;
import com.tazine.design.cor.handler.PriceHandlerFactory;
import java.util.Random;
/**
* 客户折扣请求
*
* @author frank
* @date 2017/12/27
*/
public class Customer {
// 只关注折扣被处理,而不在乎是被谁处理。
public static void main(String[] args) {
Customer customer = new Customer();
customer.setPriceHandler(PriceHandlerFactory.create());
Random rand = new Random();
// 发出一百次折扣申请
for (int i = 1; i <= 100; i++) {
System.out.print(i + " - ");
customer.requestDiscount(rand.nextFloat());
}
}
private PriceHandler priceHandler;
public void setPriceHandler(PriceHandler priceHandler) {
this.priceHandler = priceHandler;
}
public void requestDiscount(float discount) {
this.priceHandler.processDiscountRequest(discount);
}
}
| 22.825 | 63 | 0.648412 |
088da69b54a7b3437797b9e911d9460d3a62d8be | 2,585 | /*
Copyright 2010, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.google.refine.model;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.google.refine.Jsonizable;
/**
* This represents a type from the reconciliation
* service. It is used when extending data to
* store the (expected) types of new columns.
*/
public class ReconType implements Jsonizable {
public String id;
public String name;
public ReconType(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("id"); writer.value(id);
writer.key("name"); writer.value(name);
writer.endObject();
}
static public ReconType load(JSONObject obj) throws Exception {
if (obj == null) {
return null;
}
ReconType type = new ReconType(
obj.getString("id"),
obj.getString("name")
);
return type;
}
}
| 32.3125 | 80 | 0.723791 |
531f022e953eee90f0421b47cd1e9f57e77cb695 | 947 | package habuma;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.messaging.handler.annotation.SendTo;
@SpringBootApplication
public class TripProcessor {
private static Logger log = LoggerFactory.getLogger(TripProcessor.class);
public static void main(String[] args) {
System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(TripProcessor.class, args);
}
AtomicInteger total = new AtomicInteger();
@RabbitListener(queues = "trips")
@SendTo("itineraries")
public Itinerary handleMessage(TripBooking trip) {
log.info("PROCESSING TRIP. Payment card: " + trip.getPaymentCardNumber());
return trip.getItinerary();
}
}
| 27.852941 | 76 | 0.791975 |
39e58b3418b7d40e521bdd6965902c8d07f21be8 | 965 | package com.cognizant.cognizantits.qcconnection.qcupdation;
import com4j.Com4jObject;
import com4j.DISPID;
import com4j.DefaultMethod;
import com4j.IID;
import com4j.NativeType;
import com4j.ReturnValue;
import com4j.VTID;
@IID("{35DE061D-B934-4DEB-9F53-6A376EB034DF}")
public abstract interface ICommand
extends IParam
{
@DISPID(0)
@VTID(16)
@DefaultMethod
public abstract String commandText();
@DISPID(0)
@VTID(17)
@DefaultMethod
public abstract void commandText(String paramString);
@DISPID(9)
@VTID(18)
@ReturnValue(type=NativeType.Dispatch)
public abstract Com4jObject execute();
@DISPID(10)
@VTID(19)
public abstract String indexFields();
@DISPID(10)
@VTID(20)
public abstract void indexFields(String paramString);
@DISPID(11)
@VTID(21)
public abstract int affectedRows();
}
/* Location: D:\Prabu\jars\QC.jar
* Qualified Name: qcupdation.ICommand
* JD-Core Version: 0.7.0.1
*/ | 20.531915 | 59 | 0.718135 |
2fe53a776033d3c80216c15ef247d624b06fe343 | 1,269 | /*
* Copyright (C) 2009 JavaRosa
*
* 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.javarosa.core.util;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
public class OrderedMap<K,V> extends LinkedHashMap<K,V> {
public String toString () {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (Enumeration e = Collections.enumeration(keySet()); e.hasMoreElements(); ) {
Object key = e.nextElement();
sb.append(key.toString());
sb.append(" => ");
sb.append(get(key).toString());
if (e.hasMoreElements())
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
}
| 31.725 | 88 | 0.64933 |
2f48c8a13d02336948b15582d3233f7c18a82987 | 910 | package com.jacksonleonardo.unpaper.model.services;
import com.jacksonleonardo.unpaper.model.entities.IUser;
import com.jacksonleonardo.unpaper.model.exceptions.NullArgumentException;
public interface IIdentificationService {
/**
* Returns the identified or null user if not found.
*
* @param accessKey of the user to be found.
* @return the identified or null user if not found.
* @throws NullArgumentException if any of the parameters are null.
*/
IUser identifyUser(String accessKey);
/**
* Returns {@code true} if the informed user exists in the system and if the credentials are the same.
*
* @param user to be validated.
* @return {@code true} if the informed user exists in the system and if the credentials are the same.
* @throws NullArgumentException if any of the parameters are null.
*/
boolean isValid(IUser user);
}
| 35 | 106 | 0.713187 |
8f670e4eea63e347852a5a8d4c3bd142e6841627 | 3,613 | /*
* Copyright 2020 Valtech GmbH
*
* 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 de.valtech.avs.core.model.scan;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.PostConstruct;
import javax.jcr.Session;
import javax.servlet.ServletException;
import javax.servlet.http.Part;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.OSGiService;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import de.valtech.avs.api.service.AvsException;
import de.valtech.avs.api.service.AvsService;
import de.valtech.avs.api.service.scanner.ScanResult;
/**
* Sling model for scan tool.
*
* @author Roland Gruber
*/
@Model(adaptables = SlingHttpServletRequest.class)
public class ScanModel {
private static final String FILE_PART = "scanfile";
@SlingObject
private SlingHttpServletRequest request;
@OSGiService
private AvsService avsService;
private boolean scanDone = false;
private String resultOutput;
private boolean scanFailed = false;
private boolean clean = true;
@PostConstruct
protected void init() {
try {
Part filePart = request.getPart(FILE_PART);
if (filePart != null) {
InputStream inputStream = filePart.getInputStream();
if (inputStream != null) {
scanDone = true;
String userId = request.getResourceResolver().adaptTo(Session.class).getUserID();
ScanResult result = avsService.scan(inputStream, userId, filePart.getSubmittedFileName());
clean = result.isClean();
resultOutput = result.getOutput();
}
}
} catch (IOException | ServletException | AvsException e) {
scanFailed = true;
resultOutput = e.getMessage();
}
}
/**
* Returns the scan result text.
*
* @return result
*/
public String getResult() {
return resultOutput;
}
/**
* Returns if a scan was performed.
*
* @return scan done
*/
public boolean isScanDone() {
return scanDone;
}
/**
* Returns if the scan failed.
*
* @return failed
*/
public boolean isScanFailed() {
return scanFailed;
}
/**
* Returns if the file was clean.
*
* @return clean
*/
public boolean isClean() {
return clean;
}
}
| 30.361345 | 110 | 0.672848 |
216d6c6d042496915f9b74f8b022a81a433f1d90 | 763 | package org.solent.com504.oodd.bank.model.dao;
import java.util.List;
import java.util.Optional;
import org.solent.com504.oodd.bank.model.dto.BankTransaction;
import org.springframework.data.repository.CrudRepository;
public interface BankTransactionDAO extends CrudRepository<BankTransaction,Long> {
List<BankTransaction> findBankTransactionsFromCreditCardNumber(String cardnumber);
// from crud repository
long count();
void delete(BankTransaction t);
void deleteAll();
void deleteById(Long id);
boolean existsById(Long id);
List<BankTransaction> findAll();
Optional<BankTransaction> findById(Long id);
BankTransaction getOne(Long id);
<S extends BankTransaction> S save(S s);
}
| 23.84375 | 86 | 0.732634 |
aec4bfa66bc3d31cc95e1be84086d6d1d18330c0 | 2,612 | /*
* 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.arakelian.spring.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.arakelian.spring.test.annotation.WithRunListener;
public class RunListenerSpringJUnit4ClassRunner extends SpringJUnit4ClassRunner {
private final List<RunListener> runListeners = new ArrayList<>();
/**
* Constructs a new {@code SpringJUnit4ClassRunner} and initializes a {@link TestContextManager}
* to provide Spring testing functionality to standard JUnit tests.
*
* @param clazz
* the test class to be run
* @throws InitializationError
* if exceptions occurs registering listeners
*/
public RunListenerSpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
while (clazz != null) {
final WithRunListener annotation = clazz.getAnnotation(WithRunListener.class);
if (annotation != null) {
try {
final RunListener runListener = annotation.value().getConstructor().newInstance();
runListeners.add(runListener);
} catch (final Exception e) {
throw new InitializationError(e);
}
}
clazz = clazz.getSuperclass();
}
}
@Override
public void run(final RunNotifier notifier) {
for (final RunListener runListener : runListeners) {
notifier.addListener(runListener);
}
super.run(notifier);
}
}
| 37.314286 | 102 | 0.693721 |
fb5ba367d3760d073cbd1933a84210a0a0053611 | 1,068 | package com.springraft.persistencememory.state;
import com.springraft.persistence.state.State;
import lombok.*;
import org.springframework.stereotype.Component;
@Component
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@ToString
public class StateImpl implements State {
/* Id of the object */
private Long id;
/* Value for the current term */
private Long currentTerm;
/* Who the vote was for in the current term */
private String votedFor;
/* --------------------------------------------------- */
public StateImpl(StateImpl state) {
this.id = state.getId();
this.currentTerm = state.getCurrentTerm();
this.votedFor = state.getVotedFor();
}
/* --------------------------------------------------- */
@Override
public State State(long id, long currentTerm, String votedFor) {
return new StateImpl(id, currentTerm, votedFor);
}
/* --------------------------------------------------- */
public StateImpl clone() {
return new StateImpl(this);
}
}
| 23.217391 | 68 | 0.567416 |
e2e05126c59ae0867fca81901f9bce0041b217e1 | 2,160 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package com.microsoft.gctoolkit.vertx.jvm;
import com.microsoft.gctoolkit.jvm.Diary;
import com.microsoft.gctoolkit.time.DateTimeStamp;
/* package scope */ class JvmConfigurationImpl implements com.microsoft.gctoolkit.jvm.JvmConfiguration {
private final Diary diary;
/* package scope */
JvmConfigurationImpl(Diary diary) {
this.diary = diary;
}
@Override
public boolean isPrintGCDetails() {
return diary.isPrintGCDetails();
}
@Override
public boolean isPrintTenuringDistribution() {
return diary.isTenuringDistribution();
}
@Override
public boolean hasSafepointEvents() {
return diary.isApplicationStoppedTime() || diary.isApplicationRunningTime();
}
@Override
public boolean hasMaxTenuringThresholdViolation() {
return diary.isMaxTenuringThresholdViolation();
}
@Override
public int getMaxTenuringThreshold() {
return 0; //diary.getMaxTenuringThreshold(); todo: add in command line values.
}
@Override
public boolean isPreJDK17040() {
return diary.isPre70_40();
}
@Override
public boolean isJDK70() {
return diary.isJDK70();
}
@Override
public boolean isJDK80() {
return diary.isJDK80();
}
@Override
public boolean containsGCCause() {
return diary.isGCCause();
}
@Override
public String getCommandLine() {
return null;
}
@Override
public DateTimeStamp getTimeOfFirstEvent() {
return null;
}
@Override
public boolean isUnified() {
return false;
}
@Override
public Diary getDiary() {
return null;
}
@Override
public boolean hasJVMEvents() {
return false;
}
@Override
public boolean completed() {
return false;
}
@Override
public void fillInKnowns() {
}
@Override
public boolean diarize(String line) {
return false;
}
@Override
public boolean isJDKVersionKnown() { return diary.isVersionKnown(); }
}
| 20.769231 | 104 | 0.642593 |
d569f7e66e23c95cfa543802953a387e126378a7 | 63 | import java.util.*;
public class E {
private List<C> e;
}
| 10.5 | 22 | 0.619048 |
dda7930fafe670fbf027677de43af7f07a5498ad | 10,186 | import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JTextField;
public class Calculatrice extends JFrame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 2L;
// Parser = calculation, Equals = answer, JTextField number = number
double number, answer;
int calculation;
// Opérations
private JButton btnAC = new JButton("AC");
private JButton btnNeg = new JButton("+/-");
private JButton btnPerc = new JButton("%");
private JButton btnDiv = new JButton("÷");
private JButton btnMult = new JButton("×");
private JButton btnSous = new JButton("-");
private JButton btnAddi = new JButton("+");
private JButton btnEquals = new JButton("=");
private JButton btnVirg = new JButton(",");
// Nombres
private JButton b0 = new JButton("0");
private JButton b1 = new JButton("1");
private JButton b2 = new JButton("2");
private JButton b3 = new JButton("3");
private JButton b4 = new JButton("4");
private JButton b5 = new JButton("5");
private JButton b6 = new JButton("6");
private JButton b7 = new JButton("7");
private JButton b8 = new JButton("8");
private JButton b9 = new JButton("9");
// JTextField result
private JTextField result = new JTextField("");
// JLabel label (champs de texte)
private JLabel label = new JLabel();
// Font des boutons et des chiffres
private Font font = new Font("SansSerif", Font.PLAIN, 18);
// Constructeur de la classe
public Calculatrice() {
// Fenêtre Attributs
this.setTitle("Calculatrice");
this.setBounds(415, 56, 270, 360);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.getContentPane().setBackground(Color.white);
this.setLayout(null);
//result Attributs
this.result.setBounds(10, 10, 250, 50);
this.add(result);
//btnAc Attributs
this.btnAC.setBounds(10, 61, 53, 53);
this.btnAC.setFont(font);
this.add(btnAC);
//btnNeg Attributs
this.btnNeg.setBounds(74, 61, 53, 53);
this.btnNeg.setFont(font);
this.add(btnNeg);
//btnPerc Attributs
this.btnPerc.setBounds(138, 61, 53, 53);
this.btnPerc.setFont(font);
this.add(btnPerc);
//btnDiv Attributs
this.btnDiv.setBounds(202, 61, 53, 53);
this.btnDiv.setFont(font);
this.add(btnDiv);
//b7 Attributs
this.b7.setBounds(10, 114, 53, 53);
this.b7.setFont(font);
this.add(b7);
//b8 Attributs
this.b8.setBounds(74, 114, 53, 53);
this.b8.setFont(font);
this.add(b8);
//b9 Attributs
this.b9.setBounds(138, 114, 53, 53);
this.b9.setFont(font);
this.add(b9);
//btnMult Attributs
this.btnMult.setBounds(202, 114, 53, 53);
this.btnMult.setFont(font);
this.add(btnMult);
//b4 Attributs
this.b4.setBounds(10, 167, 53, 53);
this.add(b4);
this.b4.setFont(font);
//b5 Attributs
this.b5.setBounds(74, 167, 53, 53);
this.b5.setFont(font);
this.add(b5);
//b6 Attributs
this.b6.setBounds(138, 167, 53, 53);
this.b6.setFont(font);
this.add(b6);
//btnSous Attributs
this.btnSous.setBounds(202, 167, 53, 53);
this.btnSous.setFont(font);
this.add(btnSous);
//b1 Attributs
this.b1.setBounds(10, 220, 53, 53);
this.b1.setFont(font);
this.add(b1);
//b2 Attributs
this.b2.setBounds(74, 220, 53, 53);
this.b2.setFont(font);
this.add(b2);
//b3 Attributs
this.b3.setBounds(138, 220, 53, 53);
this.b3.setFont(font);
this.add(b3);
//btnAddi Attributs
this.btnAddi.setBounds(202, 220, 53, 53);
this.btnAddi.setFont(font);
this.add(btnAddi);
//b0 Attributs
this.b0.setBounds(10, 273, 118, 53);
this.b0.setFont(font);
this.add(b0);
//btnVirg Attributs
this.btnVirg.setBounds(138, 273, 53, 53);
this.btnVirg.setFont(font);
this.add(btnVirg);
//btnEquals Attributs
this.btnEquals.setBounds(202, 273, 53, 53);
this.btnEquals.setFont(font);
this.add(btnEquals);
// JTextField Attributs
this.result.setEditable(false);
this.result.setHorizontalAlignment(JTextField.RIGHT);
this.result.setFont(font);
// ActionListener sur tout les boutons
this.b0.addActionListener(this);
this.b1.addActionListener(this);
this.b2.addActionListener(this);
this.b3.addActionListener(this);
this.b4.addActionListener(this);
this.b5.addActionListener(this);
this.b6.addActionListener(this);
this.b7.addActionListener(this);
this.b8.addActionListener(this);
this.b9.addActionListener(this);
this.btnAC.addActionListener(this);
this.btnNeg.addActionListener(this);
this.btnPerc.addActionListener(this);
this.btnDiv.addActionListener(this);
this.btnMult.addActionListener(this);
this.btnSous.addActionListener(this);
this.btnAddi.addActionListener(this);
this.btnEquals.addActionListener(this);
this.btnVirg.addActionListener(this);
// Afficher la fenêtre
this.setVisible(true);
}
// Fonction sur les boutons rendues écoutables
@Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
/* Try Catch sur l'ensemble des boutons
* de la calculatrice pour récupérer
* les erreurs sur les nombres ou leurs formats */
try {
// Écoute Bouton AC (Clear All)
if(source == btnAC) {
result.setText("");
}
// Écoute Bouton 0
else if (source == b0) {
result.setText(result.getText() + "0");
}
// Écoute Bouton 1
else if (source == b1) {
result.setText(result.getText() + "1");
}
// Écoute Bouton 2
else if (source == b2) {
result.setText(result.getText() + "2");
}
// Écoute Bouton 3
else if (source == b3) {
result.setText(result.getText() + "3");
}
// Écoute Bouton 4
else if (source == b4) {
result.setText(result.getText() + "4");
}
// Écoute Bouton 5
else if (source == b5) {
result.setText(result.getText() + "5");
}
// Écoute Bouton 6
else if (source == b6) {
result.setText(result.getText() + "6");
}
// Écoute Bouton 7
else if (source == b7) {
result.setText(result.getText() + "7");
}
// Écoute Bouton 8
else if (source == b8) {
result.setText(result.getText() + "8");
}
// Écoute Bouton 9
else if (source == b9) {
result.setText(result.getText() + "9");
}
// Écoute Bouton Virgule
else if (source == btnVirg) {
if (result.getText().contains(".")) {
result.setText(".");
} else {
result.setText(result.getText() + ".");
}
}
// Écoute Bouton Addition
else if (source == btnAddi) {
String str = result.getText();
number = Double.parseDouble(result.getText());
result.setText("");
label.setText(str + "+");
calculation = 1;
}
// Écoute Bouton Negative
else if(source == btnNeg) {
if(Float.parseFloat(result.getText()) == 0) {
result.setText("0");
} else if (result.getText().startsWith("-") == true) {
String str = result.getText();
number = Float.parseFloat(result.getText());
result.setText("" + Math.round(number));
label.setText("-" + str);
} else {
String str = result.getText();
number = Float.parseFloat(result.getText());
result.setText("-" + Math.round(number));
label.setText("-" + str);
}
}
// Écoute Bouton Pourcentage
else if(source == btnPerc) {
String str = result.getText();
number = Float.parseFloat(result.getText());
result.setText("" + (double) number / 100);
label.setText("-" + str);
}
// Écoute Bouton Soustraction
else if (source == btnSous) {
String str = result.getText();
number = Double.parseDouble(result.getText());
result.setText("");
label.setText(str + "-");
calculation = 2;
}
// Écoute Bouton Multiplié
else if (source == btnMult) {
String str = result.getText();
number = Double.parseDouble(result.getText());
result.setText("");
label.setText(str + "X");
calculation = 3;
}
// Écoute Bouton Divisé
else if (source == btnDiv) {
String str = result.getText();
number = Double.parseDouble(result.getText());
result.setText("");
label.setText(str + "/");
calculation = 4;
}
//Condition sur le bouton appuyé en fonction de la variable calculation
else if (source == btnEquals) {
switch (calculation) {
// Addition
case 1:
answer = number + Double.parseDouble(result.getText());
if (Double.toString(answer).endsWith(".0")) {
result.setText(Double.toString(answer).replace(".0", ""));
} else {
result.setText(Double.toString(answer));
}
label.setText("");
break;
// Soustraction
case 2:
answer = number - Double.parseDouble(result.getText());
if (Double.toString(answer).endsWith(".0")) {
result.setText(Double.toString(answer).replace(".0", ""));
} else {
result.setText(Double.toString(answer));
}
label.setText("");
break;
// Multiplication
case 3:
answer = number * Double.parseDouble(result.getText());
if (Double.toString(answer).endsWith(".0")) {
result.setText(Double.toString(answer).replace(".0", ""));
} else {
result.setText(Double.toString(answer));
}
label.setText("");
break;
//Division
case 4:
answer = number / Double.parseDouble(result.getText());
boolean bool = false;
if(Double.isInfinite(answer) || Double.isNaN(answer) || answer == 0) {
bool = true;
result.setText("Division impossible");
JOptionPane.showMessageDialog(this, "Divison par zéro sur un double résulte forcément l'Infini ou Not a Number\n"
+"qui est un n'est pas un chriffre éxistant !", "Error", JOptionPane.ERROR_MESSAGE);
if (bool == true) {
result.setText("");
}
} else if (Double.toString(answer).endsWith(".0")) {
result.setText(Double.toString(answer).replace(".0", ""));
} else {
result.setText(Double.toString(answer));
}
label.setText("");
break;
}
}
}catch (NumberFormatException exp) {
System.out.println("Something gone wrong with " + exp);
}
}
} | 29.102857 | 120 | 0.649224 |
b8e535ca6a7ce5bf5fb2c663830d361fd0f607eb | 1,406 | package net.apnic.rdapd.types;
import org.junit.Test;
import static org.junit.Assert.*;
public class TupleTest {
private class Banana {
Banana() {}
}
@Test
public void testEquals() throws Exception {
//noinspection ObjectEqualsNull
assertFalse("A Tuple is never equal to null", new Tuple<>("a", "b").equals(null));
//noinspection EqualsBetweenInconvertibleTypes
assertFalse("A Tuple is never equal to a banana", new Tuple<>("a", "b").equals(new Banana()));
//noinspection EqualsBetweenInconvertibleTypes
assertFalse("Two Tuples are not equal if types do not match", new Tuple<>("a", "b").equals(new Tuple<>(new Banana(), "b")));
assertFalse("Two Tuples are not equal if values do not match", new Tuple<>("a", "b").equals(new Tuple<>("b", "a")));
// We assume that String stands in for all possible types, why not.
assertTrue("Two Tuples are equal if values match", new Tuple<>("a", "b").equals(new Tuple<>("a", "b")));
}
@Test
public void testHashCode() throws Exception {
assertEquals("Two Tuples with the same values have the same hashCode", new Tuple<>("a", "b").hashCode(), new Tuple<>("a", "b").hashCode());
assertNotEquals("Two Tuples with different values _probably_ have different hashCodes", new Tuple<>("b", "a").hashCode(), new Tuple<>("a", "b").hashCode());
}
} | 46.866667 | 164 | 0.642248 |
dca57b3d25dcab16483f46b88e639331a40bcf2f | 2,426 | package org.narrative.network.core.composition.base;
import org.narrative.common.persistence.OID;
import org.narrative.common.persistence.hibernate.HibernateUtil;
import org.narrative.network.core.composition.base.dao.CompositionMentionsDAO;
import org.narrative.network.shared.daobase.NetworkDAOImpl;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Proxy;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Transient;
/**
* Created by IntelliJ IDEA.
* User: jonmark
* Date: 7/26/16
* Time: 1:30 PM
*/
@Entity
@Proxy
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class CompositionMentions extends PostMentionsBase<CompositionMentionsDAO> {
private OID oid;
private Composition composition;
public static final String FIELD__COMPOSITION__NAME = "composition";
/**
* @deprecated For Hibernate use only!
*/
public CompositionMentions() {}
public CompositionMentions(Composition composition) {
this.composition = composition;
}
@Id
@GeneratedValue(generator = HibernateUtil.FOREIGN_GENERIC_GENERATOR_NAME)
@GenericGenerator(name = HibernateUtil.FOREIGN_GENERIC_GENERATOR_NAME, strategy = HibernateUtil.FOREIGN_STRATEGY, parameters = {@Parameter(name = HibernateUtil.FOREIGN_STRATEGY_PROPERTY_NAME, value = FIELD__COMPOSITION__NAME)})
public OID getOid() {
return oid;
}
@Override
public void setOid(OID oid) {
this.oid = oid;
}
@OneToOne(fetch = FetchType.LAZY, optional = false)
@ForeignKey(name = HibernateUtil.NO_FOREIGN_KEY_NAME)
@PrimaryKeyJoinColumn
public Composition getComposition() {
return composition;
}
public void setComposition(Composition composition) {
this.composition = composition;
}
@Override
@Transient
protected PostBase getPostBase() {
return getComposition();
}
public static CompositionMentionsDAO dao() {
return NetworkDAOImpl.getDAO(CompositionMentions.class);
}
}
| 30.708861 | 231 | 0.761336 |
89f5622acbc357fd6b66cdb9a4bb05cb2332904d | 1,809 | package cc.xpcas.nettysocks.proxy.ssocks;
import java.nio.charset.*;
import java.security.*;
import javax.crypto.SecretKey;
import cc.xpcas.nettysocks.utils.DigestUtils;
/**
* @author xp
*/
public class SSocksSecretKey implements SecretKey {
private static final int KEY_LENGTH = 32;
private final int keyLength;
private final byte[] key;
private SSocksSecretKey(int keyLength, byte[] key) {
this.keyLength = keyLength;
this.key = key;
}
@Override
public String getAlgorithm() {
return "ssocks";
}
@Override
public String getFormat() {
return "RAW";
}
@Override
public byte[] getEncoded() {
return key;
}
public int getKeyLength() {
return keyLength;
}
public static SSocksSecretKey of(int keyLength, String password) {
MessageDigest md = DigestUtils.getMD5();
byte[] pass = password.getBytes(StandardCharsets.UTF_8);
byte[] keys = new byte[KEY_LENGTH];
int i = 0;
byte[] hash = null;
byte[] temp = null;
while (i < keys.length) {
if (i == 0) {
hash = md.digest(pass);
temp = new byte[hash.length + pass.length];
} else {
System.arraycopy(hash, 0, temp, 0, hash.length);
System.arraycopy(pass, 0, temp, hash.length, pass.length);
hash = md.digest(temp);
}
System.arraycopy(hash, 0, keys, i, hash.length);
i += hash.length;
}
if (keyLength < keys.length) {
byte[] sliced = new byte[keyLength];
System.arraycopy(keys, 0, sliced, 0, keyLength);
keys = sliced;
}
return new SSocksSecretKey(keyLength, keys);
}
}
| 24.445946 | 74 | 0.565506 |
82a10e47d7af8193bf729255fb28db5a4894a88b | 5,304 | package de.lessvoid.nifty.gdx.render;
import com.badlogic.gdx.Gdx;
import de.lessvoid.nifty.render.batch.BatchRenderBackendInternal;
import de.lessvoid.nifty.render.batch.spi.BatchRenderBackend;
import de.lessvoid.nifty.gdx.render.GdxImage;
import de.lessvoid.nifty.render.BlendMode;
import de.lessvoid.nifty.spi.render.MouseCursor;
import de.lessvoid.nifty.tools.Color;
import de.lessvoid.nifty.tools.resourceloader.NiftyResourceLoader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* This {@link de.lessvoid.nifty.render.batch.spi.BatchRenderBackend} implementation includes full support for multiple
* texture atlases and non-atlas textures.
*
* LibGDX-specific implementation of the {@link de.lessvoid.nifty.render.batch.spi.BatchRenderBackend} interface. This
* implementation will be the most backwards-compatible because it doesn't use any functions beyond
* OpenGL / OpenGL ES 1.1. It is suitable for both mobile & desktop devices.
*
* {@inheritDoc}
*
* @author Aaron Mahan <[email protected]>
*/
public class GdxBatchRenderBackend implements BatchRenderBackend {
@Nonnull
private static final Logger log = Logger.getLogger(BatchRenderBackendInternal.class.getName());
@Nonnull
private final BatchRenderBackend internalBackend;
GdxBatchRenderBackend(@Nonnull final BatchRenderBackendInternal internalBackend) {
this.internalBackend = internalBackend;
}
@Override
public void setResourceLoader(@Nonnull NiftyResourceLoader resourceLoader) {
internalBackend.setResourceLoader(resourceLoader);
}
@Override
public int getWidth() {
log.fine("getWidth()");
return Gdx.graphics.getWidth();
}
@Override
public int getHeight() {
log.fine("getHeight()");
return Gdx.graphics.getHeight();
}
@Override
public void beginFrame() {
internalBackend.beginFrame();
}
@Override
public void endFrame() {
internalBackend.endFrame();
}
@Override
public void clear() {
internalBackend.clear();
}
@Nullable
@Override
public MouseCursor createMouseCursor(@Nonnull String filename, int hotspotX, int hotspotY) throws IOException {
return internalBackend.createMouseCursor(filename, hotspotX, hotspotY);
}
@Override
public void enableMouseCursor(@Nonnull MouseCursor mouseCursor) {
internalBackend.enableMouseCursor(mouseCursor);
}
@Override
public void disableMouseCursor() {
internalBackend.disableMouseCursor();
}
@Override
public int createTextureAtlas(int atlasWidth, int atlasHeight) {
return internalBackend.createTextureAtlas(atlasWidth, atlasHeight);
}
@Override
public void clearTextureAtlas(int atlasTextureId) {
internalBackend.clearTextureAtlas(atlasTextureId);
}
@Nonnull
@Override
public Image loadImage(@Nonnull String filename) {
log.fine("loadImage()");
return new GdxImage(filename);
}
@Nullable
@Override
public Image loadImage(@Nonnull ByteBuffer imageData, int imageWidth, int imageHeight) {
return internalBackend.loadImage(imageData, imageWidth, imageHeight);
}
@Override
public void addImageToAtlas(Image image, int atlasX, int atlasY, int atlasTextureId) {
internalBackend.addImageToAtlas(image, atlasX, atlasY, atlasTextureId);
}
@Override
public int createNonAtlasTexture(@Nonnull Image image) {
return internalBackend.createNonAtlasTexture(image);
}
@Override
public void deleteNonAtlasTexture(int textureId) {
internalBackend.deleteNonAtlasTexture(textureId);
}
@Override
public boolean existsNonAtlasTexture(int textureId) {
return internalBackend.existsNonAtlasTexture(textureId);
}
@Override
public void addQuad(
float x,
float y,
float width,
float height,
@Nonnull Color color1,
@Nonnull Color color2,
@Nonnull Color color3,
@Nonnull Color color4,
float textureX,
float textureY,
float textureWidth,
float textureHeight,
int textureId) {
internalBackend.addQuad(
x,
y,
width,
height,
color1,
color2,
color3,
color4,
textureX,
textureY,
textureWidth,
textureHeight,
textureId);
}
@Override
public void beginBatch(@Nonnull BlendMode blendMode, int textureId) {
internalBackend.beginBatch(blendMode, textureId);
}
@Override
public int render() {
return internalBackend.render();
}
@Override
public void removeImageFromAtlas(
@Nonnull Image image,
int atlasX,
int atlasY,
int imageWidth,
int imageHeight,
int atlasTextureId) {
internalBackend.removeImageFromAtlas(image, atlasX, atlasY, imageWidth, imageHeight, atlasTextureId);
}
@Override
public void useHighQualityTextures(boolean shouldUseHighQualityTextures) {
internalBackend.useHighQualityTextures(shouldUseHighQualityTextures);
}
@Override
public void fillRemovedImagesInAtlas(boolean shouldFill) {
internalBackend.fillRemovedImagesInAtlas(shouldFill);
}
}
| 27.340206 | 119 | 0.717006 |
fd0e1e7ec43d2505860e4c2273f20348405f9be5 | 1,409 | /*
* Copyright 2017-2021 original 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 io.micronaut.security.token.jwt.signature.jwks;
import io.micronaut.core.annotation.NonNull;
import java.util.List;
import java.util.Optional;
/**
* Designates a class which caches a Json Web Key Set which may typically be fetched from a remote authorization server.
* @author Sergio del Amo
* @since 3.2.0
*/
public interface JwksCache {
/**
*
* @return Whether the cache has been populated.
*/
boolean isPresent();
/**
*
* @return Whether the cache is expired or empty optional if JWKS still not cached
*/
boolean isExpired();
/**
* Clears the JWK Set cache.
*/
void clear();
/*
* @return Key IDs for JWK Set or empty optional if JWKS still not cached
*/
@NonNull
Optional<List<String>> getKeyIds();
}
| 27.627451 | 120 | 0.69127 |
ce8b0afe223112c23dfb0dce2b43103a9883b594 | 963 | package com.rainng.coursesystem.dao.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rainng.coursesystem.model.entity.StudentEntity;
import com.rainng.coursesystem.model.vo.response.StudentInfoVO;
import com.rainng.coursesystem.model.vo.response.table.StudentItemVO;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentMapper extends BaseMapper<StudentEntity> {
Integer getDepartmentIdById(Integer studentId);
Integer getGradeById(Integer studentId);
Integer count(@Param("majorName")String majorName,@Param("className") String className, @Param("name")String name);
IPage<StudentItemVO> getPage(IPage<StudentItemVO> page, @Param("majorName")String majorName,@Param("className") String className,@Param("name") String name);
StudentInfoVO getStudentInfoById(Integer studentId);
}
| 41.869565 | 161 | 0.812046 |
f1f6deca895f0d93f60e8ddbb0843554cf14db0f | 1,016 | package com.thiyagu_7.adventofcode.year2020.day17;
import org.junit.Test;
import static com.thiyagu_7.adventofcode.FileUtils.readFile;
import static org.junit.Assert.*;
public class SolutionDay17Test {
private static final String FILE_PATH_SAMPLE = "/year2020/day17/sample-input.txt";
private static final String FILE_PATH = "/year2020/day17/input.txt";
private SolutionDay17 solutionDay17 = new SolutionDay17();
private SolutionDay17Part2 solutionDay17Part2 = new SolutionDay17Part2();
@Test
public void part1_simple_test() {
assertEquals(112, solutionDay17.part1(readFile(FILE_PATH_SAMPLE)));
}
@Test
public void test_part1() {
assertEquals(211, solutionDay17.part1(readFile(FILE_PATH)));
}
@Test
public void part2_simple_test() {
assertEquals(848, solutionDay17Part2.part2(readFile(FILE_PATH_SAMPLE)));
}
@Test
public void test_part2() {
assertEquals(1952, solutionDay17Part2.part2(readFile(FILE_PATH)));
}
} | 29.028571 | 86 | 0.726378 |
b6de22aa5b4a0a908beea417183636af28a8ac1f | 792 | package ute.nms.v1_16_R2;
import ute.nms.ActionBarManager;
import net.minecraft.server.v1_16_R2.ChatComponentText;
import net.minecraft.server.v1_16_R2.ChatMessageType;
import net.minecraft.server.v1_16_R2.EntityPlayer;
import net.minecraft.server.v1_16_R2.PacketPlayOutChat;
import org.bukkit.craftbukkit.v1_16_R2.entity.CraftPlayer;
import org.bukkit.entity.Player;
import java.util.UUID;
public class ActionBarManagerImpl extends ActionBarManager {
private static final UUID ZERO = new UUID(0, 0);
@Override
protected void sendActionBar0(Player player, String line) {
EntityPlayer player1 = ((CraftPlayer) player).getHandle();
player1.playerConnection.sendPacket(new PacketPlayOutChat(new ChatComponentText(line), ChatMessageType.GAME_INFO, ZERO));
}
}
| 36 | 129 | 0.795455 |
240caacc09c34a7a27fcfc68423bdf7c3179326a | 3,537 | package com.dyc.factorymode;
import android.util.Log;
import com.dyc.factorymode.R;
public class TestItem {
private int indexInAll;
private int result;
// add status for test item
public static final int FAIL = 2;
public static final int SUCCESS = 1;
public static final int DEFAULT = 0;
//Redmine165183 chenghao add for factorytest fingerprinttest 2019-02-23 begin
public static final int[] ALL_TEST_ITEM_STRID1 = {
R.string.test_usb,
R.string.test_imei,
R.string.test_ctp,
R.string.test_sensor,
R.string.test_compass,
R.string.test_audio,
R.string.test_refaudio,
R.string.test_headset,
R.string.test_fm,
R.string.test_loud,
R.string.test_lcd,
R.string.test_camera,
R.string.test_rec,
R.string.test_gps,
R.string.test_key,
R.string.test_fingerprint,
R.string.other_test
};
public static final int[] ALL_TEST_ITEM_STRID2 = {
R.string.test_usb,
R.string.test_imei,
R.string.test_ctp,
R.string.test_sensor,
R.string.test_audio,
R.string.test_refaudio,
R.string.test_headset,
R.string.test_fm,
R.string.test_loud,
R.string.test_lcd,
R.string.test_camera,
R.string.test_rec,
R.string.test_gps,
R.string.test_key,
R.string.test_fingerprint,
R.string.other_test
};
public static final int[] ALL_TEST_ITEM_STRID3 = {
R.string.test_usb,
R.string.test_imei,
R.string.test_ctp,
R.string.test_sensor,
R.string.test_compass,
R.string.test_audio,
R.string.test_headset,
R.string.test_fm,
R.string.test_loud,
R.string.test_lcd,
R.string.test_camera,
R.string.test_rec,
R.string.test_gps,
R.string.test_key,
R.string.test_fingerprint,
R.string.other_test
};
public static final int[] ALL_TEST_ITEM_STRID4 = {
R.string.test_usb,
R.string.test_imei,
R.string.test_ctp,
R.string.test_sensor,
R.string.test_audio,
R.string.test_headset,
R.string.test_fm,
R.string.test_loud,
R.string.test_lcd,
R.string.test_camera,
R.string.test_rec,
R.string.test_gps,
R.string.test_key,
R.string.test_fingerprint,
R.string.other_test
};
//Redmine165183 chenghao add for factorytest fingerprinttest 2019-02-23 end
public TestItem(int indexInAll) {
this.indexInAll = indexInAll;
}
public int getTestTitle() {
if (!FeatureOption.MTK_DUAL_MIC_SUPPORT && !FeatureOption.SAGEREAL_FACTORYTEST_COMPASS) {
return ALL_TEST_ITEM_STRID4[indexInAll];
} else if(!FeatureOption.MTK_DUAL_MIC_SUPPORT) {
return ALL_TEST_ITEM_STRID3[indexInAll];
}else if(!FeatureOption.SAGEREAL_FACTORYTEST_COMPASS){
return ALL_TEST_ITEM_STRID2[indexInAll];
}else{
return ALL_TEST_ITEM_STRID1[indexInAll];
}
}
public void setResult(int result) {
this.result = result;
}
public int getResult() {
return result;
}
}
| 29.974576 | 97 | 0.57676 |
87474219a33f9f8691d044dc064168787d3b7208 | 540 | package de.ableitner.vlcapi.response;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import de.ableitner.vlcapi.exceptions.VlcApiException;
import de.ableitner.vlcapi.response.playlist.IPlaylist;
import de.ableitner.vlcapi.response.status.IStatus;
public interface IResponseHandler {
public IStatus createVlcStatusFromResponse(String response) throws VlcApiException;
public IPlaylist createVlcPlaylistFromResponse(String response) throws VlcApiException;
}
| 27 | 88 | 0.844444 |
dea2b9ce2cef0c2bd020b55a064856642352aac1 | 481 | package basic.arrayList;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Title: </p>
* <p>Description: </p>
*
* @Author haipeng.wang
* @Date 2021/4/13 13:27
* @Version 1
*/
public class arrayListTest {
@Test
void arrayTest(){
List<String> stringList = new ArrayList<>(100);
for (int i = 0; i < 10; i++) {
stringList.add("sss");
}
System.out.println(stringList);
}
}
| 17.814815 | 55 | 0.582121 |
c17da9115fdc5bb2fdfdfd190d0eb6f980922d1f | 23,106 | package me.andy5.util.concurrent.test;
import org.junit.Test;
import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.TimeUnit;
import me.andy5.util.concurrent.PriorityThreadPoolExecutor;
import me.andy5.util.concurrent.PriorityThreadPoolExecutor.Priority;
import me.andy5.util.concurrent.PriorityThreadPoolExecutor.PriorityCallable;
import me.andy5.util.concurrent.PriorityThreadPoolExecutor.PriorityFuture;
import me.andy5.util.concurrent.PriorityThreadPoolExecutor.PriorityRunnable;
/**
* PriorityThreadPoolExecutor测试
* PriorityThreadPoolExecutor test
*
* @author andy(Andy)
* @datetime 2019-01-22 10:42 GMT+8
* @email [email protected]
*/
public class PriorityThreadPoolExecutorTest {
private static Log log = Log.getLog(PriorityThreadPoolExecutorTest.class);
@Test
public void testPriorityRunnable() {
long start = System.currentTimeMillis();
log.debug("--------testPriorityRunnable begin--------");
final PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<>();
final PriorityThreadPoolExecutor executor = new PriorityThreadPoolExecutor(2, 5, 60, TimeUnit.NANOSECONDS,
workQueue);
// Runnable
final PriorityRunnable r1 = getPriorityRunnable("r1", 1);
final PriorityRunnable r2 = getPriorityRunnable("r2", 2);
final PriorityRunnable r3 = getPriorityRunnable("r3", 3);
final PriorityRunnable r4 = getPriorityRunnable("r4", 4);
final PriorityRunnable r5 = getPriorityRunnable("r5", 5);
final PriorityRunnable r6 = getPriorityRunnable("r6", 6);
final PriorityRunnable r7 = getPriorityRunnable("r7", 7);
final PriorityRunnable r8 = getPriorityRunnable("r8", 8);
final PriorityRunnable r9 = getPriorityRunnable("r9", 9);
final PriorityRunnable r10 = getPriorityRunnable("r10", 10);
final Runnable runnable = getRunnable("runnable");
final Runnable _r11 = getRunnable("r11");
final Runnable _r12 = getRunnable("r12");
PriorityRunnable r11;
PriorityFuture r12;
final Runnable r13 = getTestRunnableImplPriority("r13", 13);
final Runnable r14 = getTestRunnableImplPriority("r14", 14);
executor.execute(r3);
log.debug("==== add r3 ====");
executor.execute(r4);
log.debug("==== add r4 ====");
executor.execute(runnable);
log.debug("==== add runnable ====");
executor.execute(r1);
log.debug("==== add r1 ====");
executor.submit(r2);
log.debug("==== add r2 ====");
executor.execute(r5);
log.debug("==== add r5 ====");
r11 = executor.execute(_r11, 11);
log.debug("==== add r11 ====");
r12 = executor.submit(_r12, 12);
log.debug("==== add r12 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
r1.priority(111);
log.debug("-------- r1.priority(111) --------");
r2.priority(222);
log.debug("-------- r2.priority(222) --------");
executor.submit(r8);
log.debug("==== add r8 ====");
executor.execute(r13);
log.debug("==== add r13 ====");
executor.submit(r14);
log.debug("==== add r14 ====");
executor.execute(r10);
log.debug("==== add r10 ====");
executor.execute(r6);
log.debug("==== add r6 ====");
executor.submit(r7);
log.debug("==== add r7 ====");
executor.execute(r9);
log.debug("==== add r9 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
r11.priority(1111);
log.debug("-------- r11.priority(1111) --------");
r12.priority(1222);
log.debug("-------- r12.priority(1222) --------");
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
log.debug("--------testPriorityRunnable end, time consuming=" + (end - start) + "--------");
}
@Test
public void testPriorityCallable() {
long start = System.currentTimeMillis();
log.debug("--------testPriorityCallable begin--------");
final PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<>(10);
final PriorityThreadPoolExecutor executor = new PriorityThreadPoolExecutor(2, 5, 60, TimeUnit.NANOSECONDS,
workQueue);
// Callable
final PriorityCallable c1 = getPriorityCallable("c1", 1);
final PriorityCallable c2 = getPriorityCallable("c2", 2);
final PriorityCallable c3 = getPriorityCallable("c3", 3);
final PriorityCallable c4 = getPriorityCallable("c4", 4);
final PriorityCallable c5 = getPriorityCallable("c5", 5);
final PriorityCallable c6 = getPriorityCallable("c6", 6);
final PriorityCallable c7 = getPriorityCallable("c7", 7);
final PriorityCallable c8 = getPriorityCallable("c8", 8);
final PriorityCallable c9 = getPriorityCallable("c9", 9);
final PriorityCallable c10 = getPriorityCallable("c10", 10);
final Callable callable = getCallable("callable");
final Callable _c11 = getCallable("c11");
PriorityFuture c11;
final Callable c12 = getTestCallableImplPriority("c12", 12);
executor.submit(c3);
log.debug("==== add c3 ====");
executor.submit(c4);
log.debug("==== add c4 ====");
executor.submit(c8);
log.debug("==== add c8 ====");
executor.submit(c2);
log.debug("==== add c2 ====");
executor.submit(c1);
log.debug("==== add c1 ====");
executor.submit(c5);
log.debug("==== add c5 ====");
c11 = executor.submit(_c11, 11);
log.debug("==== add c11 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
c1.priority(111);
log.debug("-------- c1.priority(111) --------");
c2.priority(222);
log.debug("-------- c2.priority(222) --------");
executor.submit(c12);
log.debug("==== add c12 ====");
executor.submit(callable);
log.debug("==== add callable ====");
executor.submit(c10);
log.debug("==== add c10 ====");
executor.submit(c6);
log.debug("==== add c6 ====");
executor.submit(c7);
log.debug("==== add c7 ====");
executor.submit(c9);
log.debug("==== add c9 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
c11.priority(1111);
log.debug("-------- c11.priority(1111) --------");
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
log.debug("--------testPriorityCallable end, time consuming=" + (end - start) + "--------");
}
@Test
public void testPriorityThreadPoolExecutor() {
long start = System.currentTimeMillis();
log.debug("--------testPriorityThreadPoolExecutor begin--------");
// 自定义排序适配器
// Custom sort adapter
final Comparator<Runnable> comparator = new Comparator<Runnable>() {
@Override
public int compare(Runnable o1, Runnable o2) {
if (o1 instanceof Priority && o2 instanceof Priority) {
// 自定义优先级实现,希望优先级【低】的在前面
// Custom priority implementation, hope the priority [low] is in front
return ((Priority) o1).priority() - ((Priority) o2).priority();
}
return 0;
}
};
// final PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<>(10);
final PriorityBlockingQueue<Runnable> workQueue = new PriorityBlockingQueue<>(10, comparator);
final PriorityThreadPoolExecutor executor = new PriorityThreadPoolExecutor(2, 5, 60, TimeUnit.NANOSECONDS,
workQueue);
// Runnable
final PriorityRunnable r1 = getPriorityRunnable("r1", 1);
final PriorityRunnable r2 = getPriorityRunnable("r2", 2);
final PriorityRunnable r3 = getPriorityRunnable("r3", 3);
final PriorityRunnable r4 = getPriorityRunnable("r4", 4);
final PriorityRunnable r5 = getPriorityRunnable("r5", 5);
final PriorityRunnable r6 = getPriorityRunnable("r6", 6);
final PriorityRunnable r7 = getPriorityRunnable("r7", 7);
final PriorityRunnable r8 = getPriorityRunnable("r8", 8);
final PriorityRunnable r9 = getPriorityRunnable("r9", 9);
final PriorityRunnable r10 = getPriorityRunnable("r10", 10);
final Runnable runnable = getRunnable("runnable");
final Runnable _r11 = getRunnable("r11");
final Runnable _r12 = getRunnable("r12");
PriorityRunnable r11;
PriorityFuture r12;
final Runnable r13 = getTestRunnableImplPriority("r13", 13);
final Runnable r14 = getTestRunnableImplPriority("r14", 14);
final PriorityRunnable r16 = getPriorityRunnable("r16", 16);
final PriorityRunnable r18 = getPriorityRunnable("r18", 18);
final PriorityRunnable r20 = getPriorityRunnable("r20", 20);
// Callable
final PriorityCallable c1 = getPriorityCallable("c1", 1);
final PriorityCallable c2 = getPriorityCallable("c2", 2);
final PriorityCallable c3 = getPriorityCallable("c3", 3);
final PriorityCallable c4 = getPriorityCallable("c4", 4);
final PriorityCallable c5 = getPriorityCallable("c5", 5);
final PriorityCallable c6 = getPriorityCallable("c6", 6);
final PriorityCallable c7 = getPriorityCallable("c7", 7);
final PriorityCallable c8 = getPriorityCallable("c8", 8);
final PriorityCallable c9 = getPriorityCallable("c9", 9);
final PriorityCallable c10 = getPriorityCallable("c10", 10);
final Callable callable = getCallable("callable");
final Callable _c11 = getCallable("c11");
PriorityFuture c11;
final Callable c12 = getTestCallableImplPriority("c12", 12);
final PriorityCallable c13 = getPriorityCallable("c13", 13);
final PriorityCallable c15 = getPriorityCallable("c15", 15);
final PriorityCallable c17 = getPriorityCallable("c17", 17);
final PriorityCallable c19 = getPriorityCallable("c19", 19);
executor.execute(r3);
log.debug("==== add r3 ====");
executor.submit(c9);
log.debug("==== add c9 ====");
executor.execute(r18);
log.debug("==== add r18 ====");
executor.execute(r4);
log.debug("==== add r4 ====");
executor.submit(c6);
log.debug("==== add c6 ====");
executor.submit(c7);
log.debug("==== add c7 ====");
executor.submit(r2);
log.debug("==== add r2 ====");
executor.execute(r1);
log.debug("==== add r1 ====");
executor.submit(c3);
log.debug("==== add c3 ====");
r11 = executor.execute(_r11, 11);
log.debug("==== add r11 ====");
r12 = executor.submit(_r12, 12);
log.debug("==== add r12 ====");
executor.execute(r14);
log.debug("==== add r14 ====");
executor.submit(c15);
log.debug("==== add c15 ====");
executor.submit(callable);
log.debug("==== add callable ====");
executor.submit(c4);
log.debug("==== add c4 ====");
executor.submit(r13);
log.debug("==== add r13 ====");
c11 = executor.submit(_c11, 11);
log.debug("==== add c11 ====");
executor.execute(r16);
log.debug("==== add r16 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
r1.priority(111);
log.debug("-------- r1.priority(111) --------");
final PriorityRunnable r11f = r11;
new Thread() {
@Override
public void run() {
// 在新线程中操作优先级
// Operation priority in a new thread
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
r2.priority(222);
log.debug("-------- r2.priority(222) --------");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
r11f.priority(1111);
log.debug("-------- r11.priority(1111) --------");
}
}.start();
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
r12.priority(1222);
log.debug("-------- r12.priority(1222) --------");
executor.submit(c2);
log.debug("==== add c2 ====");
executor.execute(r5);
log.debug("==== add r5 ====");
executor.execute(runnable);
log.debug("==== add runnable ====");
executor.submit(r8);
log.debug("==== add r8 ====");
executor.submit(c12);
log.debug("==== add c12 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
c11.priority(1111);
log.debug("-------- c11.priority(1111) --------");
executor.submit(c17);
log.debug("==== add c17 ====");
executor.execute(r10);
log.debug("==== add r10 ====");
executor.submit(c19);
log.debug("==== add c19 ====");
executor.submit(c1);
log.debug("==== add c1 ====");
executor.submit(c5);
log.debug("==== add c5 ====");
executor.submit(c8);
log.debug("==== add c8 ====");
executor.execute(r20);
log.debug("==== add r20 ====");
executor.submit(c13);
log.debug("==== add c13 ====");
executor.submit(c10);
log.debug("==== add c10 ====");
executor.submit(c17);
log.debug("==== add c17 ====");
executor.submit(r7);
log.debug("==== add r7 ====");
// 动态调整不会影响PriorityThreadPoolExecutor.corePoolSize内正在执行的任务
// Dynamic adjustment will not affect the tasks being executed in PriorityThreadPoolExecutor.corePoolSize
c5.priority(555);
log.debug("-------- c5.priority(555) --------");
executor.execute(r9);
log.debug("==== add r9 ====");
executor.execute(r6);
log.debug("==== add r6 ====");
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long end = System.currentTimeMillis();
log.debug("--------testPriorityThreadPoolExecutor end, time consuming=" + (end - start) + "--------");
}
private static class TestRunnableImplPriority implements Runnable, Priority {
private String name;
private int priority;
public TestRunnableImplPriority(String name, int priority) {
this.name = name;
this.priority = priority;
}
@Override
public int priority() {
return priority;
}
@Override
public void priority(int priority) {
this.priority = priority;
}
@Override
public void run() {
try {
// 模拟处理任务
// Simulate processing tasks
Thread.sleep(1456);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("execute " + name + ", priority=" + priority());
}
@Override
public String toString() {
return "PriorityThreadPoolExecutorTest.TestRunnableImplPriority{" + "name=" + name + ",priority=" + priority() + '}';
}
}
private static class TestCallableImplPriority implements Callable, Priority {
private String name;
private int priority;
public TestCallableImplPriority(String name, int priority) {
this.name = name;
this.priority = priority;
}
@Override
public int priority() {
return priority;
}
@Override
public void priority(int priority) {
this.priority = priority;
}
@Override
public String call() throws Exception {
try {
// 模拟处理任务
// Simulate processing tasks
Thread.sleep(1738);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("execute " + name + ", priority=" + priority());
return name;
}
@Override
public String toString() {
return "PriorityThreadPoolExecutorTest.TestCallableImplPriority{" + "name=" + name + ",priority=" + priority() + '}';
}
}
private final static Runnable getTestRunnableImplPriority(final String name, final int priority) {
return new TestRunnableImplPriority(name, priority);
}
private final static Callable getTestCallableImplPriority(final String name, final int priority) {
return new TestCallableImplPriority(name, priority);
}
private final static Runnable getRunnable(final String name) {
return new Runnable() {
@Override
public void run() {
try {
// 模拟处理任务
// Simulate processing tasks
Thread.sleep(1739);
} catch (InterruptedException e) {
e.printStackTrace();
}
Integer priority = getPriority(this);
if (priority != null) {
log.debug("execute " + name + ", priority=" + priority);
} else {
log.debug("execute " + name);
}
}
@Override
public String toString() {
return "PriorityThreadPoolExecutorTest.Runnable{" + "name=" + name + '}';
}
};
}
private final static Callable getCallable(final String name) {
return new Callable<String>() {
@Override
public String call() throws Exception {
try {
// 模拟处理任务
// Simulate processing tasks
Thread.sleep(1924);
} catch (InterruptedException e) {
e.printStackTrace();
}
Integer priority = getPriority(this);
if (priority != null) {
log.debug("execute " + name + ", priority=" + priority);
} else {
log.debug("execute " + name);
}
return name;
}
@Override
public String toString() {
return "PriorityThreadPoolExecutorTest.Callable{" + "name=" + name + '}';
}
};
}
private final static PriorityRunnable getPriorityRunnable(final String name, final int priority) {
return new PriorityRunnable() {
private int p = priority;
@Override
public void run() {
try {
// 模拟处理任务
// Simulate processing tasks
Thread.sleep(1693);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("execute " + name + ", priority=" + priority());
}
@Override
public int priority() {
return p;
}
@Override
public void priority(int priority) {
p = priority;
}
@Override
public String toString() {
return "PriorityThreadPoolExecutorTest.PriorityRunnable{" + "name=" + name + ",priority=" + priority() + '}';
}
};
}
private final static PriorityCallable getPriorityCallable(final String name, final int priority) {
return new PriorityCallable() {
private int p = priority;
@Override
public String call() throws Exception {
try {
// 模拟处理任务
// Simulate processing tasks
Thread.sleep(1874);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("execute " + name + ", priority=" + priority());
return name;
}
@Override
public int priority() {
return p;
}
@Override
public void priority(int priority) {
p = priority;
}
@Override
public String toString() {
return "PriorityThreadPoolExecutorTest.PriorityCallable{" + "name=" + name + ",priority=" + priority() + '}';
}
};
}
private final static Integer getPriority(Object o) {
if (o instanceof Priority) {
return ((Priority) o).priority();
}
return null;
}
}
| 36.910543 | 129 | 0.550766 |
ca2f2799e9a7903be1c4072edd6aa6084b1b7711 | 6,420 | /*
* Copyright 2016 Parasoft Corporation
*
* 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.parasoft.environmentmanager.jenkins;
import java.io.IOException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import com.parasoft.dtp.client.api.Services;
import com.parasoft.dtp.client.impl.ServicesImpl;
import com.parasoft.em.client.api.Environments;
import com.parasoft.em.client.impl.EnvironmentsImpl;
import hudson.Extension;
import hudson.model.Job;
import hudson.model.JobProperty;
import hudson.model.JobPropertyDescriptor;
import hudson.util.FormValidation;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
public class EnvironmentManagerPlugin extends JobProperty<Job<?, ?>> {
@Override
public EnvironmentManagerPluginDescriptor getDescriptor() {
Jenkins instance = Jenkins.getInstance();
if (instance == null) {
return null;
}
return (EnvironmentManagerPluginDescriptor) instance.getDescriptor(getClass());
}
public static EnvironmentManagerPluginDescriptor getEnvironmentManagerPluginDescriptor() {
Jenkins instance = Jenkins.getInstance();
if (instance == null) {
return null;
}
return (EnvironmentManagerPluginDescriptor) instance.getDescriptor(EnvironmentManagerPlugin.class);
}
@Extension
public static final class EnvironmentManagerPluginDescriptor extends JobPropertyDescriptor {
private String emUrl;
private String username;
private Secret password;
private String dtpUrl;
private String dtpUsername;
private Secret dtpPassword;
public EnvironmentManagerPluginDescriptor() {
super(EnvironmentManagerPlugin.class);
load();
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
String oldEmUrl = emUrl;
String oldUsername = username;
Secret oldPassword = password;
String oldDtpUrl = dtpUrl;
String oldDtpUsername = dtpUsername;
Secret oldDtpPassword = dtpPassword;
emUrl = formData.getString("emUrl");
username = formData.getString("username");
password = Secret.fromString(formData.getString("password"));
dtpUrl = formData.getString("dtpUrl");
dtpUsername = formData.getString("dtpUsername");
dtpPassword = Secret.fromString(formData.getString("dtpPassword"));
if (emUrl.equals(oldEmUrl) &&
username.equals(oldUsername) &&
password.equals(oldPassword) &&
dtpUrl.equals(oldDtpUrl) &&
dtpUsername.equals(oldDtpUsername) &&
dtpPassword.equals(oldDtpPassword))
{
// nothing changed so don't test connection and don't save anything
return true;
}
// Test the emUrl, appending "/em" if necessary
try {
Environments environments = new EnvironmentsImpl(emUrl, username, password.getPlainText());
environments.getEnvironments();
} catch (IOException e) {
// First try to re-run while appending the default context path /em
String testUrl = emUrl;
if (testUrl.endsWith("/")) {
testUrl += "em";
} else {
testUrl += "/em";
}
try {
Environments environments = new EnvironmentsImpl(testUrl, username, password.getPlainText());
environments.getEnvironments();
emUrl = testUrl;
} catch (IOException e2) {
throw new FormException("Unable to connect to the Continuous Testing Platform at " + emUrl, "emUrl");
}
}
req.bindJSON(this, formData);
save();
return super.configure(req,formData);
}
@DataBoundConstructor
public EnvironmentManagerPluginDescriptor(String emUrl, String username, Secret password) {
this.emUrl = emUrl;
this.username = username;
this.password = password;
}
@Override
public String getDisplayName() {
return "Parasoft Continuous Testing Platform";
}
public String getEmUrl() {
return emUrl;
}
public String getUsername() {
return username;
}
public Secret getPassword() {
return password;
}
public String getDtpUrl() {
return dtpUrl;
}
public String getDtpUsername() {
return dtpUsername;
}
public Secret getDtpPassword() {
return dtpPassword;
}
public FormValidation doTestConnection(@QueryParameter String emUrl, @QueryParameter String username, @QueryParameter String password) {
boolean emApiV1 = false;
Secret secret = Secret.fromString(password);
try {
Environments environments = new EnvironmentsImpl(emUrl, username, secret.getPlainText());
environments.getEnvironmentsV1();
emApiV1 = true;
environments.getEnvironments();
} catch (IOException e) {
// First try to re-run while appending /em
if (emUrl.endsWith("/")) {
emUrl += "em";
} else {
emUrl += "/em";
}
try {
Environments environments = new EnvironmentsImpl(emUrl, username, secret.getPlainText());
environments.getEnvironmentsV1();
emApiV1 = true;
environments.getEnvironments();
return FormValidation.ok("Successfully connected to Continuous Testing Platform");
} catch (IOException e2) {
// return the original exception
}
if (emApiV1) {
return FormValidation.error("Continuous Testing Platform version 3.0 or higher is required.");
}
return FormValidation.error(e, "Unable to connect to Continuous Testing Platform");
}
return FormValidation.ok("Successfully connected to Continuous Testing Platform");
}
public FormValidation doDtpTestConnection(@QueryParameter String dtpUrl, @QueryParameter String dtpUsername, @QueryParameter String dtpPassword) {
Secret secret = Secret.fromString(dtpPassword);
try {
Services services = new ServicesImpl(dtpUrl, dtpUsername, secret.getPlainText());
services.getServices();
} catch (IOException e) {
return FormValidation.error(e, "Unable to connect to DTP");
}
return FormValidation.ok("Successfully connected to DTP");
}
}
}
| 31.625616 | 148 | 0.731153 |
c62cac0bbcffab8856b880005617c199fd7b31f9 | 2,798 | package com.ssafy.d204;
import com.ssafy.d204.chat.controller.ChatSessionController;
import com.ssafy.d204.chat.dto.AssignSessionRequest;
import com.ssafy.d204.chat.dto.ChatSession;
import com.ssafy.d204.chat.dto.ChatSessionCreateReq;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.List;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class ChatSessionControllerTest {
@Autowired
ChatSessionController csc;
@Test
void createChatSession(){
ResponseEntity<?> roomResponse = csc.findAllSessions();
Assertions.assertEquals(200,roomResponse.getStatusCodeValue());
List<ChatSession> sessionsBefore = (List<ChatSession>) roomResponse.getBody();
ChatSession createSessionRequest = new ChatSession();
createSessionRequest.setFk_created_by_idx(1);
createSessionRequest.setFk_client_idx(1);
ChatSession newSession =
(ChatSession) csc.createChatSession(new ChatSessionCreateReq(1,1, "/")).getBody();
// MatcherAssert(sessionsBefore.size(), isGreater);
ResponseEntity<?> roomResponse2 = csc.findAllSessions();
Assertions.assertEquals(200,roomResponse2.getStatusCodeValue());
List<ChatSession> sessionsAfter =
(List<ChatSession>) roomResponse2.getBody();
Assertions.assertTrue(sessionsBefore.size() < sessionsAfter.size());
AssignSessionRequest asr = new AssignSessionRequest();
asr.setAdmin_pk_idx(2);
csc.assignSessionToMe(newSession.getSession_id(), asr);
// 상담사가 직접 방을 닫도록 해야한다.
// 만약 상담사가 아닌 사람이 종료요청을 하면 forbidden 먹는지 여부 테스트
ResponseEntity<?> closeWithoutAuthorityResponse
= csc.closeSession(newSession.getSession_id(), new AssignSessionRequest(1));
System.out.println(closeWithoutAuthorityResponse.getStatusCodeValue()+ " " + HttpStatus.FORBIDDEN.value());
Assertions.assertTrue(
closeWithoutAuthorityResponse.getStatusCodeValue()
== HttpStatus.FORBIDDEN.value());
System.out.println("1");
ResponseEntity<?> closeWithAuthorityResponse
= csc.closeSession(newSession.getSession_id(), new AssignSessionRequest(2));
System.out.println("1");
Assertions.assertTrue(
closeWithAuthorityResponse.getStatusCodeValue()
== HttpStatus.OK.value());
System.out.println("1");
ResponseEntity<?> noSuchRoomExists =
csc.getMessagesBySessionId("I'm not the valid id! hahaha");
System.out.println("1");
Assertions.assertTrue(
noSuchRoomExists.getStatusCodeValue()
== HttpStatus.NO_CONTENT.value());
}
} | 38.861111 | 109 | 0.786276 |
a59995a9a6d183103d31bfafa9b4867141dbed88 | 9,282 | /*
* Copyright 2012 AT&T
*
* 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.att.aro.model;
import java.io.Serializable;
import java.net.InetAddress;
import com.att.aro.pcap.IPPacket;
import com.att.aro.pcap.Packet;
import com.att.aro.pcap.TCPPacket;
/**
* A bean class that contains information about a packet in a TCP Session.
*/
public class PacketInfo implements Comparable<PacketInfo>, Serializable {
private static final long serialVersionUID = 1L;
/**
* ENUM to maintain the Packet Direction.
*/
public enum Direction {
/**
* The packet direction is unknown.
*/
UNKNOWN,
/**
* The packet is traveling in the up link (Request) direction.
*/
UPLINK,
/**
* The packet is traveling in the down link (Response) direction.
*/
DOWNLINK
}
/**
* ENUM to maintain the Packets TCP state information.
*/
public enum TcpInfo {
/**
* TCP data information.
*/
TCP_DATA,
/**
* TCP acknowledge.
*/
TCP_ACK,
/**
* TCP establish.
*/
TCP_ESTABLISH,
/**
* TCP close packet.
*/
TCP_CLOSE,
/**
* TCP reset packet.
*/
TCP_RESET,
/**
* TCP duplicate data.
*/
TCP_DATA_DUP,
/**
* TCP duplicate acknowledge.
*/
TCP_ACK_DUP,
/**
* TCP keep alive.
*/
TCP_KEEP_ALIVE,
/**
* TCP keep alive acknowledge.
*/
TCP_KEEP_ALIVE_ACK,
/**
* TCP zero window.
*/
TCP_ZERO_WINDOW,
/**
* TCP window update.
*/
TCP_WINDOW_UPDATE,
/**
* TCP data recover.
*/
TCP_DATA_RECOVER,
/**
* TCP acknowledge recover.
*/
TCP_ACK_RECOVER
}
private int id; // 1-based
private double timestamp;
private Direction dir; // UPLINK / DOWNLINK direction
private TCPSession session;
private TcpInfo tcpInfo; // ********was DWORD
private Burst burst;
private String appName;
// state machine inference
private RRCState stateMachine; // ********was DWORD
private Packet packet;
private String strTcpFlags = "";
private HttpRequestResponseInfo httpRequestResponseInfo = null;
/**
* Initializes an instance of the PacketInfo class, using the specified packet data.
*
* @param packet A com.att.aro.pcap.Packet object containing the packet data.
*/
public PacketInfo(Packet packet) {
this(null, packet);
}
/**
* Initializes an instance of the PacketInfo class, using the specified packet data.
*
* @param appName The name of the application that produced the packet
* @param packet A com.att.aro.pcap.Packet object containing the packet data.
*/
public PacketInfo(String appName, Packet packet) {
this.appName = appName;
this.packet = packet;
this.timestamp = packet.getTimeStamp();
if (packet instanceof TCPPacket) {
setTcpFlagString((TCPPacket) packet);
}
}
public void clearAnalysis() {
setBurst(null);
setRequestResponseInfo(null);
setSession(null);
setStateMachine(null);
setTcpInfo(null);
}
/**
* Sets the packet id.
*
* @param id The packet id.
*/
public void setId(int id) {
this.id = id;
}
/**
* Returns the current packet.
*
* @return A com.att.aro.pcap.Packet object containing the packet data.
*/
public Packet getPacket() {
return packet;
}
/**
* Returns the packet id.
*
* @return An int that is the id of the packet.
*/
public int getId() {
return id;
}
/**
* Setting the HTTP request/response information for the packet.
*
* @param httpRequestResponseInfo - The HTTP request/response information to set.
*/
public void setRequestResponseInfo(HttpRequestResponseInfo httpRequestResponseInfo) {
this.httpRequestResponseInfo = httpRequestResponseInfo;
}
/**
* Returns the packet request/response information.
*
* @return An HTTPRequestResponse object containing the packet request/response information.
*/
public HttpRequestResponseInfo getRequestResponseInfo() {
return httpRequestResponseInfo;
}
/**
* Compares the specified PacketInfo object to this one.
*/
@Override
public int compareTo(PacketInfo o) {
return Double.valueOf(this.timestamp).compareTo(o.timestamp);
}
/**
* Sets the packet timestamp.
*
* @param timestamp The timestamp to set.
*
*/
public void setTimestamp(double timestamp) {
this.timestamp = timestamp;
}
/**
* Returns the timestamp of the packet.
*
* @return The packet timestamp.
*/
public double getTimeStamp() {
return timestamp;
}
/**
* Returns the direction of the packet (uplink, downlink, or unknown).
*
* @return The packet direction. One of the values of the PacketInfo.Direction enumeration.
*/
public Direction getDir() {
return dir;
}
/**
* Returns the remote IP address if this packet represents an IP packet and
* a direction for the packet has been identified.
* @return The remote IP address, or null if it cannot be determined.
*/
public InetAddress getRemoteIPAddress() {
if (packet instanceof IPPacket && dir != null) {
IPPacket ip = (IPPacket) packet;
switch (dir) {
case UPLINK :
return ip.getDestinationIPAddress();
case DOWNLINK :
return ip.getSourceIPAddress();
}
}
return null;
}
/**
* Sets the packet direction.
*
* @param dir A PacketInfo.Direction enumeration value that indicates the packet direction.
*/
public void setDir(Direction dir) {
this.dir = dir;
}
/**
* Returns the length (in bytes) of the packet, including both the header and the data.
*
* @return The length (in bytes) of the packet.
*/
public int getLen() {
// Because the ethernet portion of the header does not go through the 3G
// RAN, we exclude it from the len
return packet.getLen() - packet.getDatalinkHeaderSize();
}
/**
* Returns the length of the payload data.
*
* @return The payload length, in bytes.
*/
public int getPayloadLen() {
return packet.getPayloadLen();
}
/**
* Sets the TCP information for the packet.
*
* @param tcpInfo The TCP information to set.
*/
public void setTcpInfo(TcpInfo tcpInfo) {
this.tcpInfo = tcpInfo;
}
/**
* Returns the TCP information for the packet.
*
* @return A PacketInfo.TcpInfo enumeration value.
*/
public TcpInfo getTcpInfo() {
return tcpInfo;
}
/**
* Sets the burst information for the packet burst.
*
* @param burst The burst information to set.
*/
public void setBurst(Burst burst) {
this.burst = burst;
}
/**
* Returns the burst information from the packet.
*
* @return A Burst object containing the burst information.
*/
public Burst getBurst() {
return burst;
}
/**
* Sets the RRC state machine for the packet.
*
* @param stateMachine The RRC state machine value.
*/
public void setStateMachine(RRCState stateMachine) {
this.stateMachine = stateMachine;
}
/**
* Returns the RRC state machine for this packet.
*
* @return An RRCState enumeration value.
*/
public RRCState getStateMachine() {
return stateMachine;
}
/**
* Returns the application name.
*
* @return A string containing the application name.
*/
public String getAppName() {
return appName;
}
/**
* Sets the application name for the packet.
*
* @param appName - The application name to set.
*/
public void setAppName(String appName) {
this.appName = appName;
}
/**
* Returns the TCP session that contains this packet.
*
* @return A TCPSession object that containing this packet.
*/
public TCPSession getSession() {
return session;
}
/**
* Sets the TCP session that is associated with this packet.
*
* @param session - The TCP session to set.
*/
public void setSession(TCPSession session) {
this.session = session;
}
/**
* Sets a TCP flag as per TCPPacket type.
*
* @param tcpPacket
*/
private void setTcpFlagString(TCPPacket tcpPacket) {
StringBuilder strBuf = new StringBuilder();
if (tcpPacket.isACK()) {
strBuf.append("A");
}
if (tcpPacket.isPSH()) {
strBuf.append("P");
}
if (tcpPacket.isRST()) {
strBuf.append("R");
}
if (tcpPacket.isSYN()) {
strBuf.append("S");
}
if (tcpPacket.isFIN()) {
strBuf.append("F");
}
strTcpFlags = strBuf.toString();
}
/**
* Returns the TCP flag that indicates the TCPPacket type.
*
* @return A string containing the TCP flag for the packet.
*/
public String getTcpFlagString() {
return strTcpFlags;
}
}
| 22.529126 | 94 | 0.643396 |
fcd5a50fb4c211162fd2961dc99a2baa838b9670 | 4,487 | package org.broadinstitute.hellbender.utils.genotyper;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.*;
/**
* Test {@link org.broadinstitute.gatk.utils.genotyper.AlleleListUtils}.
*
* @author Valentin Ruano-Rubio <[email protected]>
*/
public final class SampleListUnitTest {
@Test(dataProvider = "singleSampleListData")
public void testAsList(final List<String> samples) {
final SampleList sampleList = new IndexedSampleList(samples);
final List<String> asList = sampleList.asListOfSamples();
Assert.assertEquals(samples, asList);
}
@Test(dataProvider = "singleSampleListData")
public void testAsSet(final List<String> samples) {
final SampleList sampleList = new IndexedSampleList(samples);
final Set<String> asSet = sampleList.asSetOfSamples();
Assert.assertEquals(new HashSet<>(samples), asSet);
}
@Test
public void testEmpty() {
final SampleList sampleList = SampleList.emptySampleList();
Assert.assertEquals(sampleList.numberOfSamples(), 0);
Assert.assertTrue(sampleList.indexOfSample("bozo") < 0);
final List<String> asList = sampleList.asListOfSamples();
Assert.assertEquals(asList, Collections.emptyList());
final Set<String> asSet = sampleList.asSetOfSamples();
Assert.assertEquals(asSet, Collections.emptySet());
}
@Test
public void testSingleton() {
final String s = "fred";
final SampleList sampleList = SampleList.singletonSampleList(s);
final List<String> asList = sampleList.asListOfSamples();
Assert.assertEquals(asList, Arrays.asList(s));
Assert.assertEquals(sampleList.getSample(0), s);
Assert.assertEquals(sampleList.indexOfSample(s), 0);
Assert.assertNotEquals(sampleList.indexOfSample("bozo"), 0);
Assert.assertTrue(asList.contains(s));
Assert.assertTrue(!asList.contains("bozo"));
final Set<String> asSet = sampleList.asSetOfSamples();
Assert.assertEquals(asSet, new HashSet<>(Arrays.asList(s)));
Assert.assertTrue(asSet.contains(s));
Assert.assertTrue(! asSet.contains("bozo"));
}
@Test(dataProvider = "twoSampleListData", dependsOnMethods={"testAsList"})
public void testEquals(final List<String> sample2, final List<String> samples2) {
final SampleList sampleList1 = new IndexedSampleList(sample2);
final SampleList sampleList2 = new IndexedSampleList(samples2);
Assert.assertTrue(SampleList.equals(sampleList1, sampleList1));
Assert.assertTrue(SampleList.equals(sampleList2, sampleList2));
Assert.assertEquals(SampleList.equals(sampleList1, sampleList2),
Arrays.equals(sampleList1.asListOfSamples().toArray(new String[sampleList1.numberOfSamples()]),
sampleList2.asListOfSamples().toArray(new String[sampleList2.numberOfSamples()]))
);
Assert.assertEquals(SampleList.equals(sampleList1, sampleList2),
SampleList.equals(sampleList2, sampleList1));
}
private List<String>[] sampleLists;
@BeforeClass
@SuppressWarnings({"unchecked", "rawtypes"})
public void setUp() {
sampleLists = (List<String>[])new List[SAMPLE_COUNT.length];
int nextIndex = 0;
for (int i = 0; i < SAMPLE_COUNT.length; i++) {
final List<String> sampleList = new ArrayList<>(SAMPLE_COUNT[i]);
sampleList.add("SAMPLE_" + i);
sampleLists[nextIndex++] = sampleList;
}
}
private static final int[] SAMPLE_COUNT = { 0, 1, 5, 10, 20};
@DataProvider(name="singleSampleListData")
public Object[][] singleSampleListData() {
final Object[][] result = new Object[sampleLists.length][];
for (int i = 0; i < sampleLists.length; i++)
result[i] = new Object[] { sampleLists[i]};
return result;
}
@DataProvider(name="twoSampleListData")
public Object[][] twoAlleleListData() {
final Object[][] result = new Object[sampleLists.length * sampleLists.length][];
int index = 0;
for (int i = 0; i < sampleLists.length; i++)
for (int j = 0; j < sampleLists.length; j++)
result[index++] = new Object[] { sampleLists[i], sampleLists[j]};
return result;
}
}
| 37.705882 | 111 | 0.665924 |
4a091c4173e3f283a622fe306add9c644fa1fcd3 | 2,092 | package com.jn.langx.distributed.cluster.loadbalance;
import com.jn.langx.annotation.Nullable;
import com.jn.langx.util.Emptys;
import com.jn.langx.util.collection.Pipeline;
import com.jn.langx.util.function.Predicate;
import com.jn.langx.util.logging.Loggers;
import org.slf4j.Logger;
import java.util.List;
public abstract class AbstractLoadBalanceStrategy<NODE extends Node, INVOCATION> implements LoadBalanceStrategy<NODE, INVOCATION> {
private String name;
@Nullable
private Weighter weighter;
private LoadBalancer<NODE, INVOCATION> loadBalancer;
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
public void setWeighter(Weighter weighter) {
this.weighter = weighter;
}
@Override
public LoadBalancer<NODE, INVOCATION> getLoadBalancer() {
return loadBalancer;
}
public void setLoadBalancer(LoadBalancer loadBalancer) {
this.loadBalancer = loadBalancer;
}
/**
* 获取node的权重
*/
public int getWeight(NODE node, INVOCATION invocation) {
if (weighter != null) {
return weighter.getWeight(node, invocation);
}
return 0;
}
protected abstract NODE doSelect(List<NODE> reachableNodes, INVOCATION invocation);
@Override
public NODE select(List<NODE> reachableNodes, INVOCATION invocation) {
// 过滤掉没有注册的 node
reachableNodes = Pipeline.of(reachableNodes).filter(new Predicate<NODE>() {
@Override
public boolean test(NODE node) {
return getLoadBalancer().hasNode(node);
}
}).asList();
if (Emptys.isEmpty(reachableNodes) || getLoadBalancer().isEmpty()) {
Logger logger = Loggers.getLogger(getClass());
logger.warn("Can't find any reachable nodes");
return null;
}
if (reachableNodes.size() == 1) {
return reachableNodes.get(0);
}
return doSelect(reachableNodes, invocation);
}
}
| 27.893333 | 131 | 0.649618 |
f62dda23924b15e84d2e7ab521537bd3b5ab7166 | 704 |
package com.yhy.common.constants;
/**
* @author : yingmu on 15-1-19.
* @email : [email protected].
* handler 通讯常量类
*
* todo EventBus 事件驱动是否能代替
*/
public class HandlerConstant {
/**
* 消息相关
*/
public static final int HANDLER_RECORD_FINISHED = 0x01; // 录音结束
public static final int HANDLER_STOP_PLAY = 0x02;// Speex 通知主界面停止播放
public static final int RECEIVE_MAX_VOLUME = 0x03;
public static final int RECORD_AUDIO_TOO_LONG = 0x04;
public static final int MSG_RECEIVED_MESSAGE = 0x05;
// 通讯录tab “全部/部门” 切换
public static final int HANDLER_CHANGE_CONTACT_TAB = 0x10;
/**
* 直播相关
*/
public static final int NEED_STOP_PUSH = 0x1800001;
}
| 22.709677 | 71 | 0.677557 |
a03cf4e9c911513f0089911a65548317ce2ea36d | 4,074 | /*
* Copyright 2020 Andi.
*
* 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 StrukturData13;
/**
* @author Andi
*
*/
class ArrayIns
{
private long[] theArray; // ref to array theArray
private int nElems; // number of data items
//--------------------------------------------------
public ArrayIns(int max)
{
theArray = new long[max]; // constructor
nElems = 0; // number of data items
}
//---------------------------------------------------
public void insert(long value) // displays array contents
{
theArray[nElems] = value; // insert it
nElems++; // increment size
}
//---------------------------------------------------
public void display() // displays array contents
{
System.out.println("A=");
for (int j = 0; j < nElems; j++)
System.out.print(theArray[j] + " "); // display it
System.out.println();
}
//---------------------------------------------------
public void quickSort()
{
recQuickSort(0, nElems-1);
}
//--------------------------------------------------
public void recQuickSort(int left, int right)
{
if (right-left <= 0) // if size <= 1,
return; // already sorted
else
{
long pivot = theArray[right]; // rightmost item
// partition range
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition-1); // sort left side
recQuickSort(partition+1, right); // sort right side
}
}// end recQuickSort()
//--------------------------------------------------
public int partitionIt(int left, int right, long pivot)
{
int leftPtr = left-1; // left (after++)
int rightPtr = right; // right-1 (after--)
while (true) {
while(theArray[++leftPtr] < pivot )
; // (nop)
while(rightPtr > 0 && theArray[--rightPtr] > pivot)
; // (nop)
if (leftPtr >= rightPtr) // if pointers cross,
break; // partition odone
else // not crossed, so
swap(leftPtr, rightPtr); // swap elements
} // end while(true)
swap(leftPtr, rightPtr); // restore pivot
return leftPtr; // return pivot location
} // end partitionIt()
//---------------------------------------------------
public void swap(int dex1, int dex2) // swap two elements
{
long temp = theArray[dex1]; // A into temp
theArray[dex1] = theArray[dex2]; // B into A
theArray[dex2] = temp; // temp into B
} // end swap()
}
public class QuickSort1App {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
int maxSize = 16; // array size
ArrayIns arr;
arr = new ArrayIns(maxSize); // create array
for (int j = 0; j < maxSize; j++) {
long n = (int)(java.lang.Math.random()*99);
arr.insert(n);
}
arr.display(); // display items
arr.quickSort(); // quicksort them
arr.display(); // display them again
} // end main()
} // end class QuickSort1App
| 35.426087 | 75 | 0.472509 |
ce97fed7416aeb2cdede760da88210400a62a91a | 2,229 | package com.PT.service.impl;
import com.PT.dao.ReceiveRecordMapper;
import com.PT.dao.SettleAccRecordMapper;
import com.PT.entity.SettleAccRecord;
import com.PT.entity.SettleAccRecordExample;
import com.PT.service.ReceiveRecordService;
import com.PT.tools.QueryToMap;
import com.PT.tools.YkatCommonUtil;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ReceiveRecordDServiceImpl implements ReceiveRecordService{
@Autowired
private ReceiveRecordMapper receiveRecordMapper;
/**
* 查询收账记录
* @param userId 唯一用户请求
* @param page 页码
* @param ipp 没有数据量
* @param queryCondition 查询条件
* @return
* @throws Exception
*/
@Override
public Map<String, Object> listReceiveRecord(int userId, int page, int ipp, String queryCondition) throws Exception{
SettleAccRecordExample settleAccRecordExample = new SettleAccRecordExample();
settleAccRecordExample.createCriteria().andCreatedAtIsNotNull();
Map factors = new HashMap();
if(queryCondition!=null && !"".equals(queryCondition)) { //有搜索条件时
factors = QueryToMap.stringToMap(queryCondition);
if (factors.containsKey("time")) {
YkatCommonUtil.putFromAndToDate(factors, (String) factors.get("time"));
}
}
factors.put("userId", userId);
PageHelper.startPage(page,ipp);
List<Map<String, Object> > receiveRecords = receiveRecordMapper.selectByFactors(factors);
int maxPage = ( receiveRecordMapper.countByFactors(factors) -1)/ipp+1;
Map<String, Object> map = new HashMap<String, Object>();
map.put("records",receiveRecords);
map.put("maxPage",maxPage);
return map;
}
/**
* 删除收账记录
* @param userId
* @param ids
* @throws Exception
*/
@Transactional
@Override
public void deleteReceiveRecord(int userId, List<Integer> ids) throws Exception{
}
}
| 28.948052 | 120 | 0.698071 |
a811099792354bf89350f66064f0a827c6570a19 | 1,799 | package org.jetbrains.plugins.clojure.config;
import com.intellij.facet.ui.libraries.LibraryInfo;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.plugins.clojure.utils.ClojureUtils;
import static org.jetbrains.plugins.clojure.config.util.ClojureMavenLibraryUtil.createJarDownloadInfo;
/**
* @author ilyas
*/
public enum ClojureVersion {
Clojure_1_0("1.0", new LibraryInfo[]{
createJarDownloadInfo(true, "clojure.jar", "", ClojureUtils.CLOJURE_MAIN),
createJarDownloadInfo(true, "clojure-contrib.jar", ""),
}),
Clojure_1_1_0("1.1.0", new LibraryInfo[]{
createJarDownloadInfo(true, "clojure.jar", "1.1.0", ClojureUtils.CLOJURE_MAIN),
}),
Clojure_1_2("1.2", new LibraryInfo[]{
createJarDownloadInfo(true, "clojure.jar", "1.2", ClojureUtils.CLOJURE_MAIN),
}),
Clojure_1_3("1.3.0", new LibraryInfo[]{
createJarDownloadInfo(false, "clojure.jar", "1.3.0", ClojureUtils.CLOJURE_MAIN),
}),
Clojure_1_4("1.4.0", new LibraryInfo[]{
createJarDownloadInfo(false, "clojure.jar", "1.4.0", ClojureUtils.CLOJURE_MAIN),
}),
Clojure_1_5_0("1.5.0", new LibraryInfo[]{
createJarDownloadInfo(false, "clojure.jar", "1.5.0", ClojureUtils.CLOJURE_MAIN),
}),
Clojure_1_5_1("1.5.1", new LibraryInfo[]{
createJarDownloadInfo(false, "clojure.jar", "1.5.1", ClojureUtils.CLOJURE_MAIN),
}),
Clojure_1_6_0("1.6.0", new LibraryInfo[]{
createJarDownloadInfo(false, "clojure.jar", "1.6.0", ClojureUtils.CLOJURE_MAIN),
});
private final String myName;
private final LibraryInfo[] myJars;
private ClojureVersion(@NonNls String name, LibraryInfo[] infos) {
myName = name;
myJars = infos;
}
public LibraryInfo[] getJars() {
return myJars;
}
public String toString() {
return myName;
}
}
| 27.676923 | 102 | 0.699277 |
90656eaef23b27814a5381e1b7f37a14844d55e3 | 19,869 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* add_patient.java
*
* Created on 25 Jul, 2018, 11:02:31 AM
*/
package hosptal;
import java.sql.*;
import javax.swing.JOptionPane;
/**
*
* @author owner
*/
public class add_patient extends javax.swing.JInternalFrame {
/** Creates new form add_patient */
public add_patient() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jRadioButton1 = new javax.swing.JRadioButton();
jRadioButton2 = new javax.swing.JRadioButton();
jLabel11 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jTextField3 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jTextField6 = new javax.swing.JTextField();
jTextField7 = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
setTitle("Add Patient Details");
jLabel2.setText("Patient ID");
jLabel3.setText("Name");
jLabel4.setText("Age");
jLabel5.setText("blood grp");
jLabel6.setText("Cause");
jLabel7.setText("date of admission");
jLabel9.setText("contact no.");
jLabel10.setText("sex");
jRadioButton1.setText("male");
jRadioButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRadioButton1MouseClicked(evt);
}
});
jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jRadioButton1ActionPerformed(evt);
}
});
jRadioButton2.setText("female");
jRadioButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jRadioButton2MouseClicked(evt);
}
});
jLabel11.setText("address");
jTextField2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField2ActionPerformed(evt);
}
});
jTextField4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTextField4ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton1.setText("Add");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Clear");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Exit");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel8.setFont(new java.awt.Font("Arial Black", 0, 12));
jLabel8.setText("Add Patient Details");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(jLabel6)
.addComponent(jLabel4)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jTextField4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jTextField3, javax.swing.GroupLayout.DEFAULT_SIZE, 93, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(36, 36, 36)
.addComponent(jButton1)))
.addGap(63, 63, 63)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(jLabel10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jTextField6, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE)
.addComponent(jTextField7, javax.swing.GroupLayout.DEFAULT_SIZE, 84, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jRadioButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jRadioButton2)))
.addGap(34, 34, 34))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel11)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2)
.addGap(18, 18, 18)
.addComponent(jButton3))))
.addGroup(layout.createSequentialGroup()
.addGap(178, 178, 178)
.addComponent(jLabel8))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jTextField1, jTextField2, jTextField3, jTextField4, jTextField5, jTextField6, jTextField7});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel8)
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
.addComponent(jButton1)
.addGap(6, 6, 6))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(7, 7, 7)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(9, 9, 9)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jRadioButton2)
.addComponent(jRadioButton1)))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(2, 2, 2)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton3)))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField2ActionPerformed
private void jTextField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField4ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextField4ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
this.setVisible(false);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
jTextField7.setText("");
jTextArea1.setText("");
jRadioButton1.setSelected(false);
jRadioButton2.setSelected(false);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/hospital", "root", "dps123");
String toid = jTextField1.getText();
String tname = jTextField2.getText();
String tgender = "";
if (jRadioButton1.isSelected() == true) {
tgender = "M";
}
if (jRadioButton2.isSelected() == true) {
tgender = "F";
}
int tage = Integer.parseInt(jTextField3.getText());
String tbldgrp = jTextField4.getText();
String tcause = jTextField5.getText();
String tdoa = jTextField6.getText();
int tcontact = Integer.parseInt(jTextField7.getText());
String taddress = jTextArea1.getText();
String nstatus = "Y";
String strSQL = "insert into patient(patient_id,name,gender,age,blood_group,cause,date_of_admission,contact_no,address,status) values('" + (toid) + "','" + (tname) + "','" + (tgender) + "','" + (tage) + "','" + (tbldgrp) + "',' " + (tcause) + " ','" + (tdoa) + "','" + (tcontact) + "','" + (taddress) + "','" + (nstatus) + "')";
int re = con.createStatement().executeUpdate(strSQL);
JOptionPane.showMessageDialog(this, "Record Added");
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Record Not Added");
JOptionPane.showMessageDialog(this, e.getMessage(), "Error!", JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
jRadioButton1.setSelected(true);
jRadioButton2.setSelected(false);
}//GEN-LAST:event_jRadioButton1ActionPerformed
private void jRadioButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButton1MouseClicked
}//GEN-LAST:event_jRadioButton1MouseClicked
private void jRadioButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jRadioButton2MouseClicked
jRadioButton2.setSelected(true);
jRadioButton1.setSelected(false);
}//GEN-LAST:event_jRadioButton2MouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JRadioButton jRadioButton1;
private javax.swing.JRadioButton jRadioButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
private javax.swing.JTextField jTextField7;
// End of variables declaration//GEN-END:variables
}
| 54.435616 | 340 | 0.610197 |
5b2f2b61db0964df753089532a7f3c1794bbf665 | 4,492 | package org.xmlcml.cml.converters.compchem.nwchem;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import nu.xom.Builder;
import nu.xom.Element;
import nu.xom.Nodes;
import org.apache.log4j.Logger;
import org.xmlcml.cml.attribute.DictRefAttribute;
import org.xmlcml.cml.base.CMLBuilder;
import org.xmlcml.cml.base.CMLElements;
import org.xmlcml.cml.element.CMLDictionary;
import org.xmlcml.cml.element.CMLEntry;
public class DictionaryEditor {
private static Logger LOG = Logger.getLogger(DictionaryEditor.class);
private CMLDictionary dictionary;
private List<Element> templateElementList;
private Map<String, List<Element>> commentByDictRefMap;
private String prefix;
private Map<String, CMLEntry> entryMap;
public static void main(String[] args) {
String dictionaryName = (args.length >= 1) ? args[0] :
"src/main/resources/org/xmlcml/cml/converters/compchem/nwchem/nwchemDict.xml";
String templateDirname = (args.length >= 2) ? args[1] :
"src/main/resources/org/xmlcml/cml/converters/compchem/nwchem/log/templates";
String outdict = (args.length >= 3) ? args[2] : "out/nwchemDict.xml";
String prefix = (args.length >= 4) ? args[3] : "n";
DictionaryEditor editor = new DictionaryEditor();
editor.readDictionary(prefix, dictionaryName);
editor.readTemplateDirectory(templateDirname);
editor.editDictionary();
editor.writeDictionary(outdict);
}
private void readDictionary(String prefix, String dictionaryFilename) {
this.prefix = prefix;
try {
dictionary = (CMLDictionary) new CMLBuilder().build(new FileInputStream(dictionaryFilename)).getRootElement().getChildElements().get(0);
} catch (Exception e) {
throw new RuntimeException("cannot read dictionary "+dictionaryFilename, e);
}
entryMap = new HashMap<String, CMLEntry>();
CMLElements<CMLEntry> entries = dictionary.getEntryElements();
for (CMLEntry entry : entries) {
String id = entry.getId();
entryMap.put(id, entry);
}
}
private void readTemplateDirectory(String templateDirname) {
File templateDir = new File(templateDirname);
File[] templateFiles = templateDir.listFiles();
if (templateFiles != null) {
templateElementList = new ArrayList<Element>();
for (File templateFile : templateFiles) {
try {
if (templateFile.getPath().endsWith(".xml")) {
Element templateElement = new Builder().build(templateFile).getRootElement();
templateElementList.add(templateElement);
}
} catch (Exception e) {
LOG.warn("cannot read template "+templateFile, e);
}
}
}
}
private void writeDictionary(String string) {
List<String> keys = new ArrayList<String>(commentByDictRefMap.keySet());
Collections.sort(keys);
int count = 0;
for (String dictRefValue : keys) {
if (dictRefValue.startsWith(prefix+":")) {
String localId = DictRefAttribute.getLocalName(dictRefValue);
List<Element> commentList = commentByDictRefMap.get(dictRefValue);
int size = commentList.size();
if (size > 1) {
System.out.println(">>>"+size+">>>"+dictRefValue);
}
// for (Element comment : commentList) {
// CMLUtil.debug(comment, "XXX");
// }
count++;
}
}
System.out.println("Final count: "+count);
}
private void editDictionary() {
commentByDictRefMap = new HashMap<String, List<Element>>();
for (Element templateElement : templateElementList) {
Nodes inCommentNodes = templateElement.query("comment[starts-with(@class,'example.input')]");
Nodes outCommentNodes = templateElement.query("comment[starts-with(@class,'example.output')]");
if (inCommentNodes.size() == 1 && outCommentNodes.size() == 1) {
Element inComment = (Element) inCommentNodes.get(0);
Element outComment = (Element) outCommentNodes.get(0);
Nodes outDictRefs = outComment.query(".//@dictRef");
for (int i = 0; i < outDictRefs.size(); i++) {
String dictRefValue = outDictRefs.get(i).getValue();
List<Element> commentList = commentByDictRefMap.get(dictRefValue);
if (commentList == null) {
commentList = new ArrayList<Element>();
commentByDictRefMap.put(dictRefValue, commentList);
}
commentList.add(inComment);
}
}
}
}
}
| 35.650794 | 140 | 0.696126 |
ba8ec376dd31e02a0ef58281516d739e114fef0d | 1,629 | package com.travel.sibar.sibartravel;
import java.util.ArrayList;
/**
* Created by ibrahim on 21/07/16.
*/
public class SearchResultsModel {
ArrayList<String> name;
ArrayList<String> imgURL;
ArrayList<String> price;
ArrayList<String> coordinates;
ArrayList<String> placeID;
ArrayList<String> distance;
public SearchResultsModel(){
name = new ArrayList<String>();
imgURL = new ArrayList<String>();
price = new ArrayList<String>();
placeID = new ArrayList<String>();
distance = new ArrayList<String>();
coordinates = new ArrayList<String>();
}
public ArrayList<String> getImgURL() {
return imgURL;
}
public void setImgURL(ArrayList<String> imgURL) {
this.imgURL = imgURL;
}
public ArrayList<String> getCoordinates(){
return this.coordinates;
}
public ArrayList<String> getName() {
return name;
}
public void setName(ArrayList<String> name) {
this.name = name;
}
public ArrayList<String> getPlaceID() {
return placeID;
}
public void setPlaceID(ArrayList<String> placeID) {
this.placeID = placeID;
}
public ArrayList<String> getPrice() {
return price;
}
public void setPrice(ArrayList<String> price) {
this.price = price;
}
public ArrayList<String> getDistance() {
return distance;
}
public void setCoordinates(ArrayList<String> c){
this.coordinates = c;
}
public void setDistance(ArrayList<String> distance) {
this.distance = distance;
}
}
| 21.434211 | 57 | 0.622468 |
cad76ffc01d2db148be5b470430bd4a70e1cbc01 | 855 | package kotlin.reflect.jvm.internal.impl.resolve.constants;
import kotlin.jvm.internal.Intrinsics;
import kotlin.reflect.jvm.internal.impl.descriptors.ModuleDescriptor;
import kotlin.reflect.jvm.internal.impl.types.SimpleType;
/* compiled from: constantValues.kt */
public final class DoubleValue extends ConstantValue<Double> {
public DoubleValue(double d) {
super(Double.valueOf(d));
}
public SimpleType getType(ModuleDescriptor moduleDescriptor) {
Intrinsics.checkNotNullParameter(moduleDescriptor, "module");
SimpleType doubleType = moduleDescriptor.getBuiltIns().getDoubleType();
Intrinsics.checkNotNullExpressionValue(doubleType, "module.builtIns.doubleType");
return doubleType;
}
public String toString() {
return ((Number) getValue()).doubleValue() + ".toDouble()";
}
}
| 35.625 | 89 | 0.739181 |
da55c610903fe23ee2d1f67c7f5495261d9cdb8a | 975 | package dev.sheldan.abstracto.webservices.urban.exception;
import dev.sheldan.abstracto.core.exception.AbstractoRunTimeException;
import dev.sheldan.abstracto.core.templating.Templatable;
import dev.sheldan.abstracto.webservices.urban.model.exception.UrbanDictionaryRequestExceptionModel;
public class UrbanDictionaryRequestException extends AbstractoRunTimeException implements Templatable {
private final UrbanDictionaryRequestExceptionModel model;
public UrbanDictionaryRequestException(Integer responseCode) {
super(String.format("Request failure towards urban dictionary %s.", responseCode));
this.model = UrbanDictionaryRequestExceptionModel
.builder()
.responseCode(responseCode)
.build();
}
@Override
public String getTemplateName() {
return "urban_dictionary_request_exception";
}
@Override
public Object getTemplateModel() {
return model;
}
}
| 33.62069 | 103 | 0.746667 |
39fa7b1f37c62b3c5e67b8bd89b82c6a65f87bfc | 231 | package com.maven.extend;
public class ExtendsTest {
public static Employee getEmployee(){
return new Employee();
}
public static Manager getManager(){
Manager manager = (Manager) getEmployee();
return manager;
}
}
| 15.4 | 44 | 0.714286 |
788af69dc8aa72d70a77f61e69410adeefb70129 | 715 | package dmurra47.wheels;
/**
* Set of functions needed in a class that behaves like a "wheel".
*
* @author Darryl Murray
* @version 1.0, 01-30-2016
*/
public interface Rollable<T> {
/**
* Resets the wheel to the starting position.
*/
void reset();
/**
* Increases the wheel position to the next valid item. Rolls over if there are no more valid items.
*/
void increase();
/**
* Returns whether or not the wheel had rolled over on the last increase() call.
*
* @return wheel roll-over state
*/
boolean lastRolledOver();
/**
* Returns the current value of the wheel.
*
* @return value of wheel
*/
T getValue();
}
| 19.324324 | 104 | 0.598601 |
c0c7ad52925d5f9d8d2a061975ae467f8c895732 | 989 | package com.db.hack.controllers;
import com.db.hack.data.save.UserRegistrationSave;
import com.db.hack.databse.DatabaseConnectionFactory;
import com.db.hack.service.LoginService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.db.hack.beans.*;
@Controller
public class UserRegistrationController {
@RequestMapping(method = RequestMethod.POST, value="/register")
@ResponseBody
Boolean registerUser(@RequestBody UserRegistration userReg) {
System.out.println("In register user");
DatabaseConnectionFactory dc = new DatabaseConnectionFactory("team7User", "HAckCaryTeam7");
UserRegistrationSave register = new UserRegistrationSave(dc);
return register.registerUser(userReg);
}
}
| 31.903226 | 99 | 0.79272 |
eaece3a32d257652bb52b13bcbb87d410b88334b | 13,458 | package pt.rupeal.invoicexpress.fragments;
import pt.rupeal.invoicexpress.MainActivity;
import pt.rupeal.invoicexpress.R;
import pt.rupeal.invoicexpress.enums.FragmentTagsEnum;
import pt.rupeal.invoicexpress.enums.RoleEnum;
import pt.rupeal.invoicexpress.fragments.DocumentsListFragment.DocumentFilterFragment;
import pt.rupeal.invoicexpress.layouts.SubTitleLayout;
import pt.rupeal.invoicexpress.layouts.ValueLabelImageLayout;
import pt.rupeal.invoicexpress.listeners.EmailListener;
import pt.rupeal.invoicexpress.listeners.PhoneCallListener;
import pt.rupeal.invoicexpress.model.ContactModel;
import pt.rupeal.invoicexpress.model.DocumentModel;
import pt.rupeal.invoicexpress.server.ContactDetailsRestHandler;
import pt.rupeal.invoicexpress.server.DocumentsRestHandler;
import pt.rupeal.invoicexpress.server.InvoiceXpress;
import pt.rupeal.invoicexpress.utils.ScreenLayoutUtil;
import pt.rupeal.invoicexpress.widgets.TextViewInvoiceXpress;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class ContactDetailsFragment extends Fragment {
private View view;
private ContactModel contact;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// enable option menu
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// inflate view
view = inflater.inflate(R.layout.contact_details, container, false);
// attach info to view
attachView();
return view;
}
private void attachView() {
// get contact
contact = (ContactModel) getArguments().getSerializable(ContactModel.CONTACT);
// contact title name
TextViewInvoiceXpress titleNameTextView = ((TextViewInvoiceXpress) view.findViewById(R.id.contact_details_title_name));
// calculate margin values
int margin = titleNameTextView.getPaddingLeft();
margin += titleNameTextView.getPaddingRight();
margin += ((ImageView) view.findViewById(R.id.contact_details_title_name_image)).getPaddingRight();
margin += ScreenLayoutUtil.convertDpToPixels(getActivity(), 80);
// set text
titleNameTextView.setText(getActivity(), contact.getName(), margin, TextViewInvoiceXpress.BREAK);
Button getInvoicesButton = ((Button) view.findViewById(R.id.contact_details_button));
getInvoicesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// vibrate - time in milliseconds
((Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE)).vibrate(50);
// debug log
if(InvoiceXpress.DEBUG) {
Log.d(this.getClass().getCanonicalName(), "Get invoices clicked for contact: " + contact.getName());
}
// check if the progress bar is visible to disable clicks
if(!InvoiceXpress.isInvoiceXpressClickable(getActivity())) {
return;
}
// verify if the user can consult invoices according his roles
if(!RoleEnum.isAllowToConsultInvoices(InvoiceXpress.getInstance().getActiveAccount().getRoles())) {
Toast.makeText(getActivity(), R.string.error_documents_roles, Toast.LENGTH_LONG).show();
return;
}
// call server if there are no documents in cache
if(InvoiceXpress.getInstance().getContacts().containsKey(contact.getId())
&& InvoiceXpress.getInstance().getContacts().get(contact.getId()).existsDocuments()) {
// set extra contact id. this will be read in DocumentsListFragment
Bundle args = new Bundle();
args.putString(DocumentModel.DOC_TYPE, "");
args.putString(ContactModel.ID, contact.getId());
// call fragment
((MainActivity) getActivity()).addFragment(DocumentsListFragment.class,
FragmentTagsEnum.DOCUMENTS_LIST,
args);
} else {
// get data from server
// set parameters
String[] params = new String[]{"", contact.getId(),
String.valueOf(DocumentFilterFragment.NO_FILTER), ""};
// execute web service
DocumentsRestHandler resthandler = new DocumentsRestHandler(getActivity());
InvoiceXpress.getInstance().setAsyncTaskActive(resthandler);
resthandler.execute(params);
}
}
});
if(contact.hasContactPreferredInfo()) {
((SubTitleLayout) view.findViewById(R.id.contact_details_preferred_subtitle)).setVisibility(View.VISIBLE);
((SubTitleLayout) view.findViewById(R.id.contact_details_preferred_subtitle)).setTextToTextViewLeft(R.string.contact_details_preferred_title);
} else {
((SubTitleLayout) view.findViewById(R.id.contact_details_preferred_subtitle)).setVisibility(View.GONE);
}
if(contact.hasPreferredName()) {
((LinearLayout) view.findViewById(R.id.contact_details_preferred_name_layout)).setVisibility(LinearLayout.VISIBLE);
((View) view.findViewById(R.id.contact_details_preferred_name_layout_line)).setVisibility(View.VISIBLE);
TextViewInvoiceXpress preferredNameTextView = ((TextViewInvoiceXpress) view.findViewById(R.id.contact_details_preferred_name));
margin = ((ViewGroup.MarginLayoutParams) preferredNameTextView.getLayoutParams()).leftMargin;
margin += ((ViewGroup.MarginLayoutParams) preferredNameTextView.getLayoutParams()).rightMargin;
preferredNameTextView.setText(getActivity(), contact.getPreferredName(), margin, TextViewInvoiceXpress.RESIZE);
} else {
((LinearLayout) view.findViewById(R.id.contact_details_preferred_name_layout)).setVisibility(LinearLayout.GONE);
((View) view.findViewById(R.id.contact_details_preferred_name_layout_line)).setVisibility(View.GONE);
}
if(contact.hasPreferredPhone()) {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_phone)).setVisibility(View.VISIBLE);
((View) view.findViewById(R.id.contact_details_preferred_phone_line)).setVisibility(View.VISIBLE);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_phone)).setText(getActivity(), contact.getPreferredPhone());
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_phone)).setLabel(R.string.details_phone);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_phone)).setImage(R.drawable.ic_device_access_call);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_phone)).setOnClickListener(
new PhoneCallListener(getActivity(), contact.getPreferredPhone()));
} else {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_phone)).setVisibility(View.GONE);
((View) view.findViewById(R.id.contact_details_preferred_phone_line)).setVisibility(View.GONE);
}
if(contact.hasPreferredEmail()) {
ValueLabelImageLayout preferredEmailLayout = ((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_email));
// set layout visible
preferredEmailLayout.setVisibility(View.VISIBLE);
((View) view.findViewById(R.id.contact_details_preferred_email_line)).setVisibility(View.VISIBLE);
// set values
preferredEmailLayout.setText(getActivity(), contact.getPreferredEmail());
preferredEmailLayout.setLabel(R.string.details_email);
preferredEmailLayout.setImage(R.drawable.ic_content_email);
preferredEmailLayout.setOnClickListener(new EmailListener(getActivity(), contact.getPreferredEmail()));
} else {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_preferred_email)).setVisibility(View.GONE);
((View) view.findViewById(R.id.contact_details_preferred_email_line)).setVisibility(View.GONE);
}
if(contact.hasContactInfo()) {
((SubTitleLayout) view.findViewById(R.id.contact_details_general_subtitle)).setVisibility(View.VISIBLE);
((SubTitleLayout) view.findViewById(R.id.contact_details_general_subtitle)).setTextToTextViewLeft(R.string.details_general_subTitle);
} else {
((SubTitleLayout) view.findViewById(R.id.contact_details_general_subtitle)).setVisibility(View.GONE);
}
if(!contact.hasAddress() && !contact.hasPostalCode() && !contact.hasCountry()) {
((LinearLayout) view.findViewById(R.id.contact_details_address_layout)).setVisibility(LinearLayout.GONE);
((View) view.findViewById(R.id.contact_details_address_layout_line)).setVisibility(View.GONE);
} else {
((LinearLayout) view.findViewById(R.id.contact_details_address_layout)).setVisibility(LinearLayout.VISIBLE);
((View) view.findViewById(R.id.contact_details_address_layout_line)).setVisibility(View.VISIBLE);
}
if(contact.hasPostalCode()) {
((TextView) view.findViewById(R.id.contact_details_postal_code)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.contact_details_postal_code)).setText(contact.getPostalCode());
} else {
((TextView) view.findViewById(R.id.contact_details_postal_code)).setVisibility(View.GONE);
}
if(contact.hasCountry()) {
((TextView) view.findViewById(R.id.contact_details_country)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.contact_details_country)).setText(contact.getCountry());
} else {
((TextView) view.findViewById(R.id.contact_details_country)).setVisibility(View.GONE);
}
if(contact.hasAddress()) {
((TextView) view.findViewById(R.id.contact_details_address)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.contact_details_address)).setText(contact.getAddress());
} else {
((TextView) view.findViewById(R.id.contact_details_address)).setVisibility(View.GONE);
}
if(contact.hasPhone()) {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_phone)).setVisibility(View.VISIBLE);
((View) view.findViewById(R.id.contact_details_phone_line)).setVisibility(View.VISIBLE);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_phone)).setText(getActivity(), contact.getPhone());
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_phone)).setLabel(R.string.details_phone);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_phone)).setImage(R.drawable.ic_device_access_call);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_phone)).setOnClickListener(
new PhoneCallListener(getActivity(), contact.getPhone()));
} else {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_phone)).setVisibility(View.GONE);
((View) view.findViewById(R.id.contact_details_phone_line)).setVisibility(View.GONE);
}
if(contact.hasFax()) {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_fax)).setVisibility(View.VISIBLE);
((View) view.findViewById(R.id.contact_details_fax_line)).setVisibility(View.VISIBLE);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_fax)).setText(getActivity(), contact.getFax());
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_fax)).setLabel(R.string.details_fax);
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_fax)).setImage(R.drawable.ic_device_access_call);
} else {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_fax)).setVisibility(View.GONE);
((View) view.findViewById(R.id.contact_details_fax_line)).setVisibility(View.GONE);
}
if(contact.hasEmail()) {
ValueLabelImageLayout emailLayout = ((ValueLabelImageLayout) view.findViewById(R.id.contact_details_email));
emailLayout.setVisibility(View.VISIBLE);
((View) view.findViewById(R.id.contact_details_email_line)).setVisibility(View.VISIBLE);
emailLayout.setText(getActivity(), contact.getEmail());
emailLayout.setLabel(R.string.details_email);
emailLayout.setImage(R.drawable.ic_content_email);
emailLayout.setOnClickListener(new EmailListener(getActivity(), contact.getEmail()));
} else {
((ValueLabelImageLayout) view.findViewById(R.id.contact_details_email)).setVisibility(View.GONE);
((View) view.findViewById(R.id.contact_details_email_line)).setVisibility(View.GONE);
}
if(contact.hasFiscalId()) {
((LinearLayout) view.findViewById(R.id.contact_details_nif_layout)).setVisibility(LinearLayout.VISIBLE);
((View) view.findViewById(R.id.contact_details_nif_layout_line)).setVisibility(View.VISIBLE);
((TextView) view.findViewById(R.id.contact_details_nif)).setText(contact.getFiscalId());
} else {
((LinearLayout) view.findViewById(R.id.contact_details_nif_layout)).setVisibility(LinearLayout.GONE);
((View) view.findViewById(R.id.contact_details_nif_layout_line)).setVisibility(View.GONE);
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.action_bar_contact_details, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh_tab:
// refresh and get contact details from server
String[] params = new String[] {contact.getId(), "true"};
new ContactDetailsRestHandler(getActivity()).execute(params);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
| 47.893238 | 145 | 0.773369 |
ba50886610d98d7590c2a43ce0056aab1d32afc3 | 4,078 | /**
* Copyright 2012-2015 Gunnar Morling (http://www.gunnarmorling.de/)
* and/or other contributors as indicated by the @authors tag. See the
* copyright.txt file in the distribution for a full listing of all
* contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mapstruct.ap.model;
import java.util.List;
import java.util.Set;
import javax.tools.Diagnostic;
import org.mapstruct.ap.model.assignment.Assignment;
import org.mapstruct.ap.model.common.ConversionContext;
import org.mapstruct.ap.model.common.Type;
import org.mapstruct.ap.model.source.Method;
import org.mapstruct.ap.model.source.SourceMethod;
import org.mapstruct.ap.model.source.builtin.BuiltInMethod;
import org.mapstruct.ap.model.source.selector.MethodSelectors;
/**
* Factory class for creating all types of assignments
*
* @author Sjaak Derksen
*/
public class AssignmentFactory {
private AssignmentFactory() {
}
public static Assignment createTypeConversion(Set<Type> importTypes, List<Type> exceptionTypes, String expression) {
return new TypeConversion( importTypes, exceptionTypes, expression );
}
public static Assignment createMethodReference(Method method, MapperReference declaringMapper,
Type targetType) {
return new MethodReference( method, declaringMapper, targetType );
}
public static Assignment createMethodReference(BuiltInMethod method, ConversionContext contextParam) {
return new MethodReference( method, contextParam );
}
public static Direct createDirect(String sourceRef) {
return new Direct( sourceRef );
}
public static MethodReference createFactoryMethod( Type returnType, MappingBuilderContext ctx ) {
MethodReference result = null;
for ( SourceMethod method : ctx.getSourceModel() ) {
if ( !method.overridesMethod() && !method.isIterableMapping() && !method.isMapMapping()
&& method.getSourceParameters().isEmpty() ) {
List<Type> parameterTypes = MethodSelectors.getParameterTypes(
ctx.getTypeFactory(),
method.getParameters(),
null,
returnType
);
if ( method.matches( parameterTypes, returnType ) ) {
if ( result == null ) {
MapperReference mapperReference = findMapperReference( ctx.getMapperReferences(), method );
result = new MethodReference( method, mapperReference, null );
}
else {
ctx.getMessager().printMessage(
Diagnostic.Kind.ERROR,
String.format(
"Ambiguous factory methods: \"%s\" conflicts with \"%s\".",
result,
method
),
method.getExecutable()
);
}
}
}
}
return result;
}
private static MapperReference findMapperReference( List<MapperReference> mapperReferences, SourceMethod method ) {
for ( MapperReference ref : mapperReferences ) {
if ( ref.getType().equals( method.getDeclaringMapper() ) ) {
return ref;
}
}
return null;
}
}
| 38.471698 | 120 | 0.607406 |
dfe8d34b88a702a3a33e3b5ba227c28746ab900c | 1,416 | /**
*
*/
package gov.noaa.pmel.dashboard.server.db.dao;
import java.sql.SQLException;
import java.util.List;
import gov.noaa.pmel.dashboard.server.model.InsertUser;
import gov.noaa.pmel.dashboard.server.model.User;
/**
* @author kamb
*
*/
public interface UsersDao {
public void addAccessRole(String username) throws SQLException;
// also adds access role in transaction
public int addUser(InsertUser newUser) throws SQLException;
public List<User> retrieveAll() throws SQLException;
public User retrieveUser(String username) throws SQLException;
public User retrieveUserById(Integer userDbId) throws SQLException;
public User retrieveUserByEmail(String email) throws SQLException;
public void updateUser(User changedUser) throws SQLException;
public void setUserPassword(int userId, String newAuthString) throws SQLException;
public String retrieveUserAuthString(int userId) throws SQLException;
public void userLogin(User user) throws SQLException;
public void deleteUserByUsername(String username) throws SQLException;
public void removeAccessRole(String userid);
/**
* Sets user password, also sets need to change flag.
* @param intValue
* @param newCryptPasswd
* @throws SQLException
*/
public void resetUserPassword(int userid, String newCryptPasswd) throws SQLException;
}
| 27.764706 | 89 | 0.739407 |
c5723b8a79fc5bea3d35cd160550fd16c94e72eb | 4,098 | package android.coolweather.user.coolweather.service;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.coolweather.user.coolweather.gson.Weather;
import android.coolweather.user.coolweather.util.HttpUtil;
import android.coolweather.user.coolweather.util.JsonUtil;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AutoUpdateService extends Service {
public AutoUpdateService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 1.更新天气信息
updateWeather();
// 2.更新每日一图
updateBingPic();
// 3.服务定时器定时更新
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
// 初始化时长
int anHour = 8 * 60 * 60 * 1000; // 8小时
long triggerAtTime = SystemClock.elapsedRealtime() + anHour; // 延时到的时间
// 初始化意图
Intent i = new Intent(this, AutoUpdateService.class);
PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return super.onStartCommand(intent, flags, startId);
}
/**
* 更新每日一图
*/
private void updateBingPic() {
String bingPicUrl = "http://guolin.tech/api/bing_pic";
HttpUtil.sendOkHttpRequest(bingPicUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 1.获取响应的图片链接
String bingPic = response.body().string();
// 2.保存到 SharedPreferences 缓存中
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
edit.putString("bing_pic", bingPic);
edit.apply();
}
});
}
/**
* 更新天气信息
*/
private void updateWeather() {
// 1.获取缓存的天气 Json 数据
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String weatherJson = prefs.getString("weather", null);
if (weatherJson != null) {
// 1.有缓存时解析成 Weather 对象
Weather weather = JsonUtil.handleWeatherResponse(weatherJson);
// 2.获取天气 id ,拼接天气 URL
String weatherId = weather.getBasic().getWeatherId();
String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId + "&key=9a74fd6fc92c4663ba089d52da699b8e";
// 3.访问网络请求天气信息
HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 1.获取响应
String newWeatherJson = response.body().string();
// 2.解析 json
Weather newWeather = JsonUtil.handleWeatherResponse(newWeatherJson);
// 3.如果网络访问成功的操作
if (newWeather != null && "ok".equals(newWeather.getStatus())) {
// 存储缓存
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
edit.putString("weather", newWeatherJson);
edit.apply();
}
}
});
}
}
}
| 37.254545 | 133 | 0.609078 |
552a29d47b0e9950849895c37e34fa6ffaaf7f60 | 741 |
package com.technicise;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for VaginalFoam.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="VaginalFoam">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="VAGFOAM"/>
* <enumeration value="VAGFOAMAPL"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "VaginalFoam")
@XmlEnum
public enum VaginalFoam {
VAGFOAM,
VAGFOAMAPL;
public String value() {
return name();
}
public static VaginalFoam fromValue(String v) {
return valueOf(v);
}
}
| 19 | 95 | 0.649123 |
ad0fbb5af62bf78ceca5083ca756ba2e33221264 | 304 | package minds.behavior;
import java.util.ArrayList;
import entity.mind.ExternalPerceptionInterface;
public class BehaviorEat extends SequenceBehaviorImpl {
@Override
protected void setBehavior() {
this.actionsForStep.add("EAT");
}
@Override
public String getName() {
return "EAT";
}
}
| 14.47619 | 55 | 0.746711 |
e302e6695ff44b9b9b640ccba085fcfb99699b51 | 1,684 | package com.mcxtzhang.chapter15;
import java.lang.reflect.Array;
/**
* Intro:
* Author: zhangxutong
* E-mail: [email protected]
* Home Page: http://blog.csdn.net/zxt0601
* Created: 2017/4/5.
* History:
*/
public class GenericsClearTest<TYPE> {
Class<TYPE> holder;
//运行时使用 会出错
TYPE[] arrays;
//运行时使用 不会出错
TYPE[] arrays2;
public GenericsClearTest(Class<TYPE> holder) {
this.holder = holder;
//new TYPE();
//new TYPE[5];
int[] ints = new int[5];
//运行时使用 会出错
arrays = (TYPE[]) new Object[5];
//运行时使用 不会出错
arrays2 = (TYPE[]) Array.newInstance(String.class, 5);
TYPE a = (TYPE) "aaa";
}
public static void main(String[] args) {
GenericsClearTest<String> class1 = new GenericsClearTest<>(String.class);
System.out.println(class1.holder);
System.out.println((class1.holder == String.class) + "");
//System.out.println((class1.holder == Object.class) + "");
System.out.println(class1.holder.isInstance("aa"));
System.out.println(class1.holder.isInstance(new Object()));
//运行时使用 会出错
//class1.arrays[0] = "s";
//运行时使用 不会出错
class1.arrays2[0] = "s";
System.out.println(class1.arrays2[0]);
GenericsClearTest<Object> class2 = new GenericsClearTest<>(Object.class);
System.out.println(class2.holder);
//System.out.println((class2.holder == String.class) + "");
System.out.println((class2.holder == Object.class) + "");
System.out.println(class2.holder.isInstance("aa"));
System.out.println(class2.holder.isInstance(new Object()));
}
}
| 28.066667 | 81 | 0.602138 |
42fddab8f60cd5f2f7c073375d9633c00856ec42 | 19,178 | /* */ package com.ibm.ism.script.webclient.beans.autoscript;
/* */
/* */ import com.ibm.tivoli.maximo.script.ScriptDriver;
/* */ import com.ibm.tivoli.maximo.script.ScriptDriverFactory;
/* */ import com.ibm.tivoli.maximo.script.ScriptParamInfo;
/* */ import java.io.ByteArrayOutputStream;
/* */ import java.rmi.RemoteException;
/* */ import java.util.HashMap;
/* */ import java.util.List;
/* */ import java.util.Map;
/* */ import psdi.mbo.MboRemote;
/* */ import psdi.mbo.MboSetRemote;
/* */ import psdi.util.MXApplicationException;
/* */ import psdi.util.MXApplicationYesNoCancelException;
/* */ import psdi.util.MXException;
/* */ import psdi.util.logging.MXLogger;
/* */ import psdi.util.logging.MXLoggerFactory;
/* */ import psdi.webclient.system.beans.DataBean;
/* */ import psdi.webclient.system.beans.ResultsBean;
/* */ import psdi.webclient.system.controller.AppInstance;
/* */ import psdi.webclient.system.controller.UploadFile;
/* */ import psdi.webclient.system.controller.WebClientEvent;
/* */ import psdi.webclient.system.runtime.WebClientRuntime;
/* */ import psdi.webclient.system.session.WebClientSession;
/* */
/* */ public abstract class ScriptWizardBean extends DataBean
/* */ {
/* 52 */ private int processTabOrder = 0;
/* */
/* */ protected abstract String[] getAllTabs();
/* */
/* */ public int nexttab()
/* */ throws MXException, RemoteException
/* */ {
/* 65 */ int nextTabOrder = 0;
/* */ try
/* */ {
/* 68 */ nextTabOrder = getNextTabOrder(this.processTabOrder);
/* */ }
/* */ catch (MXException e)
/* */ {
/* 73 */ this.clientSession.showMessageBox(e);
/* 74 */ WebClientEvent event = new WebClientEvent("changetab", getTabGroupName(), getAllTabs()[this.processTabOrder], this.clientSession);
/* 75 */ event.setSourceControl(this.app);
/* 76 */ this.clientSession.queueEvent(event);
/* 77 */ return 1;
/* */ }
/* 79 */ fireDataChangedEvent();
/* 80 */ fireStructureChangedEvent();
/* 81 */ WebClientEvent event = new WebClientEvent("changetab", getTabGroupName(), getAllTabs()[nextTabOrder], this.clientSession);
/* 82 */ event.setSourceControl(this.app);
/* 83 */ this.clientSession.queueEvent(event);
/* 84 */ this.processTabOrder = nextTabOrder;
/* 85 */ return 1;
/* */ }
/* */
/* */ protected abstract String getTabGroupName();
/* */
/* */ protected void validateMoveTab(int currentTabOrder) throws MXException, RemoteException {
/* 92 */ if (currentTabOrder == 0)
/* */ {
/* 94 */ if (getMbo().isNull("launchpointname"))
/* */ {
/* 96 */ throw new MXApplicationException("script", "missinglpname");
/* */ }
/* 98 */ if ((!getMbo().isNull("scriptorigin")) && (getMbo().getString("scriptorigin").equals("EXISTING")) && (getMbo().isNull("autoscriptnp")))
/* */ {
/* 101 */ throw new MXApplicationException("script", "missingscriptnp");
/* */ }
/* */ }
/* 104 */ else if (currentTabOrder == 1)
/* */ {
/* 109 */ MboRemote lpMbo = getMbo();
/* 110 */ if ((lpMbo != null) && (lpMbo.getName().equals("SCRIPTLAUNCHPOINT")))
/* */ {
/* 112 */ MboSetRemote lpVarSet = lpMbo.getMboSet("LAUNCHPOINTVARS");
/* 113 */ MboSetRemote autoSet = getMbo().getMboSet("AUTOSCRIPT");
/* 114 */ MboRemote autoScriptMbo = autoSet.getMbo(0);
/* 115 */ if (autoScriptMbo != null)
/* */ {
/* 117 */ if (autoScriptMbo.isNull("autoscript"))
/* */ {
/* 119 */ String[] params = { " " };
/* 120 */ throw new MXApplicationException("script", "invalidscript", params);
/* */ }
/* */
/* 123 */ lpMbo.setValue("autoscript", autoScriptMbo.getString("autoscript"), 11L);
/* */
/* 125 */ MboSetRemote varsSet = autoScriptMbo.getMboSet("AUTOSCRIPTVARS");
/* */
/* 127 */ MboRemote var = null;
/* 128 */ for (int i = 0; ; i++)
/* */ {
/* 130 */ var = varsSet.getMbo(i);
/* 131 */ if (var == null)
/* */ {
/* */ break;
/* */ }
/* 135 */ if (var.toBeDeleted())
/* */ continue;
/* 137 */ String bindType = var.getString("varbindingtype");
/* 138 */ if ((!var.isNull("attributevaluenp")) && (bindType.equalsIgnoreCase("ATTRIBUTE")))
/* */ {
/* 140 */ var.setValue("lpvarbindval", var.getString("attributevaluenp"), 11L);
/* */ }
/* */
/* 143 */ if ((!var.isNull("lpvarbindval")) || (!bindType.equalsIgnoreCase("ATTRIBUTE"))) {
/* */ continue;
/* */ }
/* 146 */ String[] params = { var.getString("varname") };
/* 147 */ throw new MXApplicationException("script", "missinglpbindvalue", params);
/* */ }
/* */
/* 151 */ int lpVarsCount = lpVarSet.count();
/* 152 */ Map mapOfLpVarsMbo = new HashMap();
/* 153 */ if (lpVarSet.count() > 0)
/* */ {
/* 155 */ for (int i = 0; i < lpVarsCount; i++)
/* */ {
/* 157 */ mapOfLpVarsMbo.put(lpVarSet.getMbo(i).getString("varname"), lpVarSet.getMbo(i));
/* */ }
/* */ }
/* 160 */ for (int i = 0; ; i++)
/* */ {
/* 162 */ var = varsSet.getMbo(i);
/* 163 */ if (var == null)
/* */ {
/* */ break;
/* */ }
/* 167 */ if (var.toBeDeleted()) {
/* */ continue;
/* */ }
/* 170 */ if (var.isNull("lpvarbindval"))
/* */ continue;
/* 172 */ MboRemote launchVarMbo = null;
/* 173 */ if (mapOfLpVarsMbo.containsKey(var.getString("varname")))
/* */ {
/* 175 */ launchVarMbo = (MboRemote)mapOfLpVarsMbo.get(var.getString("varname"));
/* */ }
/* */ else
/* */ {
/* 179 */ launchVarMbo = lpVarSet.addAtEnd();
/* */ }
/* 181 */ launchVarMbo.setValue("varname", var.getString("varname"), 11L);
/* */
/* 183 */ launchVarMbo.setValue("varbindingvalue", var.getString("lpvarbindval"), 2L);
/* */
/* 185 */ launchVarMbo.setValue("overridden", true, 11L);
/* */
/* 187 */ launchVarMbo.setValue("varbindingtype", var.getString("varbindingtype"), 2L);
/* 188 */ launchVarMbo.setValue("literaldatatype", var.getString("literaldatatype"), 2L);
/* */ }
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* */ protected void actionMoveTab(int currentTabOrder)
/* */ throws MXException, RemoteException
/* */ {
/* 201 */ if (currentTabOrder == 0)
/* */ {
/* 203 */ MboSetRemote scriptSet = getMbo().getMboSet("AUTOSCRIPT");
/* 204 */ if (scriptSet.getApp() == null)
/* */ {
/* 206 */ scriptSet.setApp("AUTOSCRIPT");
/* */ }
/* 208 */ if (!getMbo().isNull("autoscriptnp"))
/* */ {
/* 210 */ MboRemote scriptMbo = null;
/* 211 */ if (scriptSet.count() == 1)
/* */ {
/* 213 */ MboRemote scriptMbo2 = scriptSet.getMbo(0);
/* 214 */ if (scriptMbo2.getString("autoscript").equals(getMbo().getString("autoscriptnp")))
/* */ {
/* 216 */ scriptMbo = scriptMbo2;
/* */ }
/* */ else
/* */ {
/* 220 */ scriptSet.reset();
/* */ }
/* */ }
/* 223 */ if (scriptMbo == null)
/* */ {
/* 225 */ scriptSet.setQbeExactMatch(true);
/* 226 */ scriptSet.setQbe("autoscript", getMbo().getString("autoscriptnp"));
/* 227 */ scriptSet.reset();
/* */
/* 229 */ if (scriptSet.isEmpty())
/* */ {
/* 231 */ String[] params = { getMbo().getString("autoscriptnp") };
/* 232 */ throw new MXApplicationException("script", "invalidscript", params);
/* */ }
/* 234 */ scriptSet.getMbo();
/* */ }
/* */
/* */ }
/* 240 */ else if (scriptSet.count() == 1)
/* */ {
/* 242 */ MboRemote scriptMbo = scriptSet.getMbo(0);
/* 243 */ if (!scriptMbo.toBeAdded())
/* */ {
/* 245 */ scriptSet.reset();
/* 246 */ scriptSet.add();
/* */ }
/* */ }
/* */ else
/* */ {
/* 251 */ scriptSet.add();
/* */ }
/* */ }
/* */ }
/* */
/* */ private int getNextTabOrder(int currentTabOrder)
/* */ throws MXException, RemoteException
/* */ {
/* 271 */ validateMoveTab(currentTabOrder);
/* 272 */ actionMoveTab(currentTabOrder);
/* 273 */ return currentTabOrder + 1;
/* */ }
/* */
/* */ public int prevtab()
/* */ throws MXException, RemoteException
/* */ {
/* 283 */ int prevTabOrder = getPreviousTabOrder(this.processTabOrder);
/* 284 */ fireDataChangedEvent();
/* 285 */ fireStructureChangedEvent();
/* 286 */ WebClientEvent event = new WebClientEvent("changetab", getTabGroupName(), getAllTabs()[prevTabOrder], this.clientSession);
/* 287 */ event.setSourceControl(this.app);
/* 288 */ this.clientSession.queueEvent(event);
/* 289 */ this.processTabOrder = prevTabOrder;
/* 290 */ return 1;
/* */ }
/* */
/* */ private int getPreviousTabOrder(int currentTabOrder)
/* */ throws MXException, RemoteException
/* */ {
/* 302 */ return currentTabOrder - 1;
/* */ }
/* */
/* */ protected void setDefaultValues(MboRemote wizMbo)
/* */ throws MXException, RemoteException
/* */ {
/* */ }
/* */
/* */ public synchronized void insert()
/* */ throws MXException, RemoteException
/* */ {
/* 316 */ super.insert();
/* 317 */ setDefaultValues(getMbo());
/* */ }
/* */
/* */ public int complete()
/* */ throws MXException, RemoteException
/* */ {
/* 327 */ save();
/* 328 */ WebClientRuntime.sendEvent(new WebClientEvent("dialogclose", this.app.getCurrentPageId(), null, this.clientSession));
/* 329 */ String[] params = { "" };
/* 330 */ this.clientSession.showMessageBox(this.clientSession.getCurrentEvent(), "script", "lpcomplete", params);
/* 331 */ reset();
/* 332 */ fireDataChangedEvent();
/* 333 */ structureChangedEvent(this);
/* */
/* 335 */ this.app.getResultsBean().recHasChanged();
/* 336 */ return 1;
/* */ }
/* */
/* */ public int cancelchanges()
/* */ throws MXException, RemoteException
/* */ {
/* 349 */ WebClientEvent event = this.clientSession.getCurrentEvent();
/* 350 */ int msgRet = event.getMessageReturn();
/* */
/* 352 */ if (msgRet < 0)
/* */ {
/* 354 */ throw new MXApplicationException("script", "cancelchanges");
/* */ }
/* 356 */ if (msgRet == 8)
/* */ {
/* 358 */ getMboSet().rollback();
/* 359 */ this.clientSession.getCurrentApp().put("forcereload", "true");
/* 360 */ this.clientSession.queueEvent(new WebClientEvent("changeapp", this.app.getId(), "autoscript", this.clientSession));
/* */ } else {
/* 362 */ if (msgRet == 16) {
/* 363 */ return 1;
/* */ }
/* 365 */ return 1;
/* */ }
/* 367 */ return 1;
/* */ }
/* */
/* */ public int loadData()
/* */ throws MXException, RemoteException
/* */ {
/* 379 */ UploadFile file = (UploadFile)this.app.get("importfile");
/* */
/* 381 */ if (file == null) {
/* 382 */ throw new MXApplicationException("designer", "noimportfile");
/* */ }
/* 384 */ MboSetRemote autoSet = getMbo().getMboSet("AUTOSCRIPT");
/* 385 */ MboRemote autoScriptMbo = autoSet.getMbo(0);
/* 386 */ boolean bWarning = false;
/* */ try
/* */ {
/* 389 */ if (autoScriptMbo != null)
/* */ {
/* 391 */ if (!autoScriptMbo.toBeAdded())
/* */ {
/* 393 */ MboSetRemote lpSet = autoScriptMbo.getMboSet("SCRIPTLAUNCHPOINT");
/* 394 */ MboRemote lpMbo = lpSet.getMbo(0);
/* 395 */ if ((lpMbo != null) && (lpMbo.toBeAdded()))
/* */ {
/* 397 */ this.app.remove("importfile");
/* 398 */ throw new MXApplicationException("script", "no_import_on_existing_script");
/* */ }
/* */ }
/* */
/* 402 */ String scriptLang = autoScriptMbo.getString("scriptlanguage");
/* 403 */ ScriptDriver scriptDriver = ScriptDriverFactory.getInstance().getScriptDriverForLanguage(scriptLang);
/* 404 */ boolean binaryScript = scriptDriver.isBinaryScript();
/* 405 */ byte[] scriptBytes = file.getFileOutputStream().toByteArray();
/* 406 */ if (!binaryScript)
/* */ {
/* 409 */ autoScriptMbo.setValue("source", new String(scriptBytes, "UTF-8"), 2L);
/* */ }
/* */ else
/* */ {
/* 415 */ autoScriptMbo.setValue("binaryscriptsource", scriptBytes, 2L);
/* */ }
/* */
/* 419 */ if (scriptDriver.supportsPublishedParams())
/* */ {
/* 421 */ List listParams = scriptDriver.parseScriptForParams(scriptBytes);
/* */ MboSetRemote varMboSet;
/* 422 */ if (autoScriptMbo.toBeAdded())
/* */ {
/* 424 */ autoScriptMbo.getMboSet("AUTOSCRIPTVARS").reset();
/* 425 */ varMboSet = autoScriptMbo.getMboSet("AUTOSCRIPTVARS");
/* 426 */ if ((listParams != null) && (listParams.size() > 0))
/* */ {
/* 428 */ for (ScriptParamInfo param : listParams)
/* */ {
/* 430 */ if (scriptDriver.isVarNameMatchesKeyWord(param.getName()))
/* */ {
/* 432 */ MXLoggerFactory.getLogger("maximo.script").info("skipped var " + param.getName() + " from the script definition as thats an implicit vaiable");
/* 433 */ continue;
/* */ }
/* 435 */ MboRemote varMbo = varMboSet.add();
/* 436 */ varMbo.setValue("varname", param.getName());
/* 437 */ varMbo.setValue("vartype", param.getInoutType());
/* 438 */ varMbo.setValue("allowoverride", true);
/* */ }
/* */ }
/* */ }
/* */ else
/* */ {
/* */ MboSetRemote varMboSet;
/* */ Map mapMbos;
/* 444 */ if ((listParams != null) && (listParams.size() > 0))
/* */ {
/* 446 */ varMboSet = autoScriptMbo.getMboSet("AUTOSCRIPTVARS");
/* 447 */ mapMbos = new HashMap();
/* 448 */ int pos = 0;
/* 449 */ while (varMboSet.getMbo(pos) != null)
/* */ {
/* 451 */ String varName = varMboSet.getMbo(pos).getString("varname");
/* 452 */ boolean deleteVar = true;
/* 453 */ for (ScriptParamInfo param : listParams)
/* */ {
/* 455 */ if (param.getName().equals(varName))
/* */ {
/* 457 */ deleteVar = false;
/* */ }
/* */ }
/* 460 */ if (deleteVar)
/* */ {
/* 462 */ varMboSet.getMbo(pos).delete();
/* */ }
/* 464 */ mapMbos.put(varName, varMboSet.getMbo(pos));
/* 465 */ pos++;
/* */ }
/* 467 */ for (ScriptParamInfo param : listParams)
/* */ {
/* 469 */ if (scriptDriver.isVarNameMatchesKeyWord(param.getName()))
/* */ {
/* 471 */ MXLoggerFactory.getLogger("maximo.script").info("skipped var " + param.getName() + " from the script definition as thats an implicit vaiable");
/* 472 */ continue;
/* */ }
/* 474 */ if (!mapMbos.containsKey(param.getName()))
/* */ {
/* 476 */ MboRemote varMbo = varMboSet.add();
/* 477 */ varMbo.setValue("varname", param.getName());
/* 478 */ varMbo.setValue("vartype", param.getInoutType());
/* 479 */ varMbo.setValue("allowoverride", true);
/* */ }
/* 483 */ else if (((MboRemote)mapMbos.get(param.getName())).toBeDeleted())
/* */ {
/* 485 */ ((MboRemote)mapMbos.get(param.getName())).undelete();
/* */ }
/* */
/* */ }
/* */
/* */ }
/* */ else
/* */ {
/* 493 */ autoScriptMbo.getMboSet("AUTOSCRIPTVARS").deleteAll();
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* */ }
/* */ catch (MXApplicationYesNoCancelException mxae)
/* */ {
/* 502 */ bWarning = true;
/* 503 */ throw mxae;
/* */ }
/* */ catch (MXException mxe)
/* */ {
/* 507 */ throw mxe;
/* */ }
/* */ catch (Exception e)
/* */ {
/* 512 */ String[] params = { autoScriptMbo.getString("autoscript") };
/* 513 */ throw new MXApplicationException("script", "invalidscript", params, e);
/* */ }
/* */ finally
/* */ {
/* 517 */ if (!bWarning)
/* 518 */ this.app.remove("importfile");
/* 519 */ structureChangedEvent(this);
/* */ }
/* 521 */ return 1;
/* */ }
/* */
/* */ public boolean hasSigOptionAccess(int row, String sigOption)
/* */ throws RemoteException, MXException
/* */ {
/* 528 */ if (sigOption != null)
/* */ {
/* 531 */ if (sigOption.equalsIgnoreCase("HIDEIMP"))
/* */ {
/* 533 */ MboRemote mbo = getMbo(row);
/* 534 */ MboRemote scriptMbo = mbo.getMboSet("AUTOSCRIPT").getMbo();
/* */
/* 538 */ return (scriptMbo == null) || (scriptMbo.toBeAdded());
/* */ }
/* */
/* 543 */ return super.hasSigOptionAccess(row, sigOption);
/* */ }
/* 545 */ return false;
/* */ }
/* */ }
/* Location: D:\maxapp\MAXIMO.ear\maximouiweb.war\WEB-INF\classes\
* Qualified Name: com.ibm.ism.script.webclient.beans.autoscript.ScriptWizardBean
* JD-Core Version: 0.6.0
*/ | 41.873362 | 171 | 0.480603 |
0505f30e7daee701562cceae049d8571c5c661fd | 1,036 | package br.com.badrequest.insporte.rest;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import br.com.badrequest.insporte.rest.model.Response;
import br.com.badrequest.insporte.rest.model.email.EmailForm;
import br.com.badrequest.insporte.service.EmailService;
import com.google.gson.Gson;
/**
* JAX-RS Email Service Rest
*
* This class produces a RESTful service to send emails
*/
@Path("/email")
@RequestScoped
@SuppressWarnings("unchecked")
public class EmailRest {
@Inject
private EmailService emailService;
@POST
@Path("/send")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public String send(String json) {
EmailForm form = new Gson().fromJson(json, EmailForm.class);
emailService.send(form.nome, form.email, form.assunto, form.mensagem);
return new Gson().toJson(new Response(Response.OK));
}
}
| 24.093023 | 72 | 0.766409 |
6dc42bd90ff3b8b29b4d489fbaf2cedc72049745 | 2,649 | /*
* Copyright [2017] Wikimedia Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.solr.ltr.feature;
import com.solr.ltr.LtrQueryContext;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.IntStream;
public class PrebuiltFeatureSet implements FeatureSet {
private final List<Query> features;
private final String name;
public PrebuiltFeatureSet(@Nullable String name, List<PrebuiltFeature> features) {
this.name = name;
this.features = new ArrayList<>(Objects.requireNonNull(features));
}
@Override
public String name() {
return name;
}
/**
* Parse and build lucene queries
*/
@Override
public List<Query> toQueries(LtrQueryContext context, Map<String, Object> params) {
return features;
}
@Override
public int featureOrdinal(String featureName) {
int ord = findFeatureIndexByName(featureName);
if (ord < 0) {
throw new IllegalArgumentException("Unknown feature [" + featureName + "]");
}
return ord;
}
@Override
public Feature feature(int ord) {
return (PrebuiltFeature) features.get(ord);
}
@Override
public PrebuiltFeature feature(String name) {
return (PrebuiltFeature) features.get(featureOrdinal(name));
}
@Override
public boolean hasFeature(String name) {
return findFeatureIndexByName(name) >= 0;
}
@Override
public int size() {
return features.size();
}
private int findFeatureIndexByName(String featureName) {
// slow, not meant for runtime usage, mostly needed for tests
// would make sense to implement a Map to do this once
// feature names are mandatory and unique.
return IntStream.range(0, features.size())
.filter(i -> Objects.equals(((PrebuiltFeature)features.get(i)).name(), featureName))
.findFirst()
.orElse(-1);
}
}
| 29.433333 | 100 | 0.671952 |
84ffd30520752018145ec13cf63563589368b4e4 | 2,996 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.impl.protocol.jabber;
import java.io.*;
import net.java.sip.communicator.service.protocol.*;
import org.jivesoftware.smackx.filetransfer.*;
/**
* The Jabber protocol extension of the <tt>AbstractFileTransfer</tt>.
*
* @author Yana Stamcheva
*/
public class IncomingFileTransferJabberImpl
extends AbstractFileTransfer
{
private final String id;
private final Contact sender;
private final File file;
/**
* The Jabber incoming file transfer.
*/
private IncomingFileTransfer jabberTransfer;
/**
* Creates an <tt>IncomingFileTransferJabberImpl</tt>.
*
* @param id the identifier of this transfer
* @param sender the sender of the file
* @param file the file
* @param jabberTransfer the Jabber file transfer object
*/
public IncomingFileTransferJabberImpl( String id,
Contact sender,
File file,
IncomingFileTransfer jabberTransfer)
{
this.id = id;
this.sender = sender;
this.file = file;
this.jabberTransfer = jabberTransfer;
}
/**
* Cancels the file transfer.
*/
@Override
public void cancel()
{
this.jabberTransfer.cancel();
}
/**
* Returns the number of bytes already received from the recipient.
*
* @return the number of bytes already received from the recipient
*/
@Override
public long getTransferedBytes()
{
return jabberTransfer.getAmountWritten();
}
/**
* The direction is incoming.
*
* @return IN
*/
public int getDirection()
{
return IN;
}
/**
* Returns the sender of the file.
*
* @return the sender of the file
*/
public Contact getContact()
{
return sender;
}
/**
* Returns the identifier of this file transfer.
*
* @return the identifier of this file transfer
*/
public String getID()
{
return id;
}
/**
* Returns the local file that is being transferred or to which we transfer.
*
* @return the file
*/
public File getLocalFile()
{
return file;
}
}
| 24.16129 | 80 | 0.615821 |
8ffa63d8e1645e4d4a108f8e99af8e782f3b4851 | 4,403 | package com.ucar.datalink.manager.core.utils.timer;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Consumer;
/**
* Created by lubiao on 2016/12/12.
*/
class TimerTaskList implements Delayed {
// TimerTaskList forms a doubly linked cyclic list using a dummy root entry
// root.next points to the head
// root.prev points to the tail
private final TimerTaskEntry root = new TimerTaskEntry(null, -1);
private final AtomicLong expiration = new AtomicLong(-1L);
private final AtomicInteger taskCounter;
TimerTaskList(AtomicInteger taskCounter) {
root.setNext(root);
root.setPrev(root);
this.taskCounter = taskCounter;
}
// Apply the supplied function to each of tasks in this list
void foreach(Consumer<TimerTask> f) {
synchronized (this) {
TimerTaskEntry entry = root.getNext();
while (entry != root) {
final TimerTaskEntry nextEntry = entry.getNext();
if (!entry.cancelled()) {
f.accept(entry.getTimerTask());
}
entry = nextEntry;
}
}
}
// Add a timer task entry to this list
void add(TimerTaskEntry timerTaskEntry) {
boolean done = false;
while (!done) {
// Remove the timer task entry if it is already in any other list
// We do this outside of the sync block below to avoid deadlocking.
// We may retry until timerTaskEntry.list becomes null.
timerTaskEntry.remove();
synchronized (this) {
synchronized (timerTaskEntry) {
if (timerTaskEntry.getList() == null) {
// updateStatus the timer task entry to the end of the list. (root.prev points to the tail entry)
final TimerTaskEntry tail = root.getPrev();
timerTaskEntry.setNext(root);
timerTaskEntry.setPrev(tail);
timerTaskEntry.setList(this);
tail.setNext(timerTaskEntry);
root.setPrev(timerTaskEntry);
taskCounter.incrementAndGet();
done = true;
}
}
}
}
}
// Remove the specified timer task entry parseFrom this list
void remove(TimerTaskEntry timerTaskEntry) {
synchronized (this) {
synchronized (timerTaskEntry) {
if (timerTaskEntry.getList() == this) {
timerTaskEntry.getNext().setPrev(timerTaskEntry.getPrev());
timerTaskEntry.getPrev().setNext(timerTaskEntry.getNext());
timerTaskEntry.setNext(null);
timerTaskEntry.setPrev(null);
timerTaskEntry.setList(null);
taskCounter.decrementAndGet();
}
}
}
}
// Remove all task entries and apply the supplied function to each of them
void flush(Consumer<TimerTaskEntry> f) {
synchronized (this) {
TimerTaskEntry head = root.getNext();
while (head != root) {
remove(head);
f.accept(head);
head = root.getNext();
}
expiration.set(-1L);
}
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(
Math.max(getExpiration() - TimeUnit.NANOSECONDS.toMillis(System.nanoTime()), 0),
TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
TimerTaskList other = (TimerTaskList) o;
if (getExpiration() < other.getExpiration()) {
return -1;
} else if (getExpiration() > other.getExpiration()) {
return 1;
} else {
return 0;
}
}
// Get the bucket's expiration time
Long getExpiration() {
return expiration.get();
}
// Set the bucket's expiration time
// Returns true if the expiration time is changed
boolean setExpiration(Long expirationMs) {
return expiration.getAndSet(expirationMs) != expirationMs;
}
}
| 33.356061 | 121 | 0.568022 |
fd3ce3124a8964ae9e8ee1d79895dd9b120f12e4 | 8,852 | package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.commands.CommandTestUtil.ADDRESS_DESC_DANIEL;
import static seedu.address.logic.commands.CommandTestUtil.ADDRESS_DESC_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.EMAIL_DESC_DANIEL;
import static seedu.address.logic.commands.CommandTestUtil.EMAIL_DESC_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_ADDRESS_DESC;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_EMAIL_DESC;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_NAME_DESC;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_PHONE_DESC;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_STAFF_ID_DESC;
import static seedu.address.logic.commands.CommandTestUtil.INVALID_TAG_DESC;
import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_DANIEL;
import static seedu.address.logic.commands.CommandTestUtil.NAME_DESC_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.PHONE_DESC_DANIEL;
import static seedu.address.logic.commands.CommandTestUtil.PHONE_DESC_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.PREAMBLE_NON_EMPTY;
import static seedu.address.logic.commands.CommandTestUtil.PREAMBLE_WHITESPACE;
import static seedu.address.logic.commands.CommandTestUtil.STAFF_ID_DESC_DANIEL;
import static seedu.address.logic.commands.CommandTestUtil.STAFF_ID_DESC_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_CHEF;
import static seedu.address.logic.commands.CommandTestUtil.TAG_DESC_SENIOR_STAFF;
import static seedu.address.logic.commands.CommandTestUtil.VALID_ADDRESS_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_EMAIL_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_NAME_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_PHONE_ELLE;
import static seedu.address.logic.commands.CommandTestUtil.VALID_STAFF_TAG;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_CHEF;
import static seedu.address.logic.commands.CommandTestUtil.VALID_TAG_SENIOR_STAFF;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseFailure;
import static seedu.address.logic.parser.CommandParserTestUtil.assertParseSuccess;
import static seedu.address.testutil.TypicalPersons.DANIEL_STAFF;
import org.junit.jupiter.api.Test;
import seedu.address.logic.commands.AddCommand;
import seedu.address.model.person.Address;
import seedu.address.model.person.Email;
import seedu.address.model.person.Name;
import seedu.address.model.person.Person;
import seedu.address.model.person.Phone;
import seedu.address.model.person.StaffId;
import seedu.address.model.tag.Tag;
import seedu.address.testutil.StaffBuilder;
public class AddCommandParserTest {
private AddCommandParser parser = new AddCommandParser();
@Test
public void parse_allFieldsPresent_success() {
Person expectedPerson = new StaffBuilder(DANIEL_STAFF).withTags(VALID_TAG_CHEF, VALID_STAFF_TAG).build();
// whitespace only preamble
assertParseSuccess(parser, PREAMBLE_WHITESPACE + NAME_DESC_DANIEL + PHONE_DESC_DANIEL + EMAIL_DESC_DANIEL
+ ADDRESS_DESC_DANIEL + TAG_DESC_CHEF + STAFF_ID_DESC_DANIEL, new AddCommand(expectedPerson));
// multiple names - last name accepted
assertParseSuccess(parser, NAME_DESC_ELLE + NAME_DESC_DANIEL + PHONE_DESC_DANIEL + EMAIL_DESC_DANIEL
+ ADDRESS_DESC_DANIEL + TAG_DESC_CHEF + STAFF_ID_DESC_DANIEL, new AddCommand(expectedPerson));
// multiple phones - last phone accepted
assertParseSuccess(parser, NAME_DESC_DANIEL + PHONE_DESC_ELLE + PHONE_DESC_DANIEL + EMAIL_DESC_DANIEL
+ ADDRESS_DESC_DANIEL + TAG_DESC_CHEF + STAFF_ID_DESC_DANIEL, new AddCommand(expectedPerson));
// multiple emails - last email accepted
assertParseSuccess(parser, NAME_DESC_DANIEL + PHONE_DESC_DANIEL + EMAIL_DESC_ELLE + EMAIL_DESC_DANIEL
+ ADDRESS_DESC_DANIEL + TAG_DESC_CHEF + STAFF_ID_DESC_DANIEL, new AddCommand(expectedPerson));
// multiple addresses - last address accepted
assertParseSuccess(parser, NAME_DESC_DANIEL + PHONE_DESC_DANIEL + EMAIL_DESC_DANIEL + ADDRESS_DESC_ELLE
+ ADDRESS_DESC_DANIEL + TAG_DESC_CHEF + STAFF_ID_DESC_DANIEL, new AddCommand(expectedPerson));
// multiple tags - all accepted
Person expectedPersonMultipleTags = new StaffBuilder(DANIEL_STAFF).withTags(VALID_TAG_CHEF,
VALID_TAG_SENIOR_STAFF, VALID_STAFF_TAG).build();
assertParseSuccess(parser, NAME_DESC_DANIEL + PHONE_DESC_DANIEL + EMAIL_DESC_DANIEL + ADDRESS_DESC_DANIEL
+ TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + STAFF_ID_DESC_DANIEL,
new AddCommand(expectedPersonMultipleTags));
}
@Test
public void parse_optionalFieldsMissing_success() {
// zero tags
Person expectedPerson = new StaffBuilder(DANIEL_STAFF).withTags(VALID_STAFF_TAG).build();
assertParseSuccess(parser, NAME_DESC_DANIEL + PHONE_DESC_DANIEL + EMAIL_DESC_DANIEL
+ ADDRESS_DESC_DANIEL + STAFF_ID_DESC_DANIEL,
new AddCommand(expectedPerson));
}
@Test
public void parse_compulsoryFieldMissing_failure() {
String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE);
// missing name prefix
assertParseFailure(parser, VALID_NAME_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + ADDRESS_DESC_ELLE
+ STAFF_ID_DESC_ELLE, expectedMessage);
// missing phone prefix
assertParseFailure(parser, NAME_DESC_ELLE + VALID_PHONE_ELLE + EMAIL_DESC_ELLE + ADDRESS_DESC_ELLE
+ STAFF_ID_DESC_ELLE, expectedMessage);
// missing email prefix
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + VALID_EMAIL_ELLE + ADDRESS_DESC_ELLE
+ STAFF_ID_DESC_ELLE, expectedMessage);
// missing address prefix
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + VALID_ADDRESS_ELLE
+ STAFF_ID_DESC_ELLE, expectedMessage);
// missing staff id prefix
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + VALID_ADDRESS_ELLE
+ STAFF_ID_DESC_ELLE, expectedMessage);
// all prefixes missing
assertParseFailure(parser, VALID_NAME_ELLE + VALID_PHONE_ELLE + VALID_EMAIL_ELLE + VALID_ADDRESS_ELLE,
expectedMessage);
}
@Test
public void parse_invalidValue_failure() {
// invalid name
assertParseFailure(parser, INVALID_NAME_DESC + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + ADDRESS_DESC_ELLE
+ TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + STAFF_ID_DESC_ELLE, Name.MESSAGE_CONSTRAINTS);
// invalid phone
assertParseFailure(parser, NAME_DESC_ELLE + INVALID_PHONE_DESC + EMAIL_DESC_ELLE + ADDRESS_DESC_ELLE
+ TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + STAFF_ID_DESC_ELLE, Phone.MESSAGE_CONSTRAINTS);
// invalid email
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + INVALID_EMAIL_DESC + ADDRESS_DESC_ELLE
+ TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + STAFF_ID_DESC_ELLE, Email.MESSAGE_CONSTRAINTS);
// invalid address
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + INVALID_ADDRESS_DESC
+ TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + STAFF_ID_DESC_ELLE, Address.MESSAGE_CONSTRAINTS);
// invalid tag
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + ADDRESS_DESC_ELLE
+ INVALID_TAG_DESC + TAG_DESC_CHEF + STAFF_ID_DESC_ELLE, Tag.MESSAGE_CONSTRAINTS);
// invalid staff id
assertParseFailure(parser, NAME_DESC_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + ADDRESS_DESC_ELLE
+ TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + INVALID_STAFF_ID_DESC, StaffId.MESSAGE_CONSTRAINTS);
// two invalid values, only first invalid value reported
assertParseFailure(parser, INVALID_NAME_DESC + PHONE_DESC_ELLE + EMAIL_DESC_ELLE + INVALID_ADDRESS_DESC
+ STAFF_ID_DESC_ELLE, Name.MESSAGE_CONSTRAINTS);
// non-empty preamble
assertParseFailure(parser, PREAMBLE_NON_EMPTY + NAME_DESC_ELLE + PHONE_DESC_ELLE + EMAIL_DESC_ELLE
+ ADDRESS_DESC_ELLE + TAG_DESC_SENIOR_STAFF + TAG_DESC_CHEF + STAFF_ID_DESC_ELLE,
String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
}
}
| 54.981366 | 113 | 0.766042 |
7c6fd8c52d1c0a022ab2c87d1192120b92ed5985 | 4,955 | package com.hongliangjie.fugue.distributions;
import com.hongliangjie.fugue.utils.MathExp;
import com.hongliangjie.fugue.utils.MathLog;
import com.hongliangjie.fugue.utils.RandomUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by liangjie on 3/3/16.
*/
public class MultinomialDistributionTest {
@Test
public void testSet() throws Exception {
MultinomialDistribution theta = new MultinomialDistribution(3);
double[] p = new double[3];
p[0] = 0.2; p[1] = 0.5; p[2] = 0.3;
double[] accu_p = theta.setProbabilities(p);
assertEquals("Testing Accumulate Distribution:", true, (accu_p[2] >= accu_p[1]) && (accu_p[1] >= accu_p[0]));
MultinomialDistribution theta1 = new MultinomialDistribution(3, new MathLog(0), new MathExp(1), "normal");
MultinomialDistribution theta2 = new MultinomialDistribution(3, new MathLog(1), new MathExp(0), "log");
double[] p1 = new double[3];
p1[0] = 0.2; p1[1] = 0.5; p1[2] = 0.3;
double[] logp = new double[3];
logp[0] = Math.log(0.2); logp[1] = Math.log(0.5); logp[2] = Math.log(0.3);
double[] accu_p2 = theta1.setProbabilities(p1);
double[] accu_logp = theta2.setProbabilities(logp);
for (int i = 0; i < 3; i++) {
double e = Math.abs(accu_p2[i] - Math.exp(accu_logp[i]));
assertEquals("Testing Accumulate Distribution:", true, e < 1e-10);
}
}
private int[] sampleHistogram(MultinomialDistribution dist, int sampleSize) {
RandomUtils r = new RandomUtils(1);
int localSampleSize = 1;
if (sampleSize <= 0) {
localSampleSize = 1;
}
else{
localSampleSize = sampleSize;
}
int[] localHistogram = new int[dist.dimensions()];
for (int i=0; i < localSampleSize; i++){
int currentIndex = dist.sample(r.nextDouble());
localHistogram[currentIndex] ++;
}
return localHistogram;
}
@Test
public void testSample() throws Exception {
MultinomialDistribution theta = new MultinomialDistribution(3, new MathLog(0), new MathExp(0), "normal");
MultinomialDistribution thetaBin = new MultinomialDistribution(3, new MathLog(0), new MathExp(0), "binary");
double[] p = new double[3];
p[0] = 0.0; p[1] = 0.0; p[2] = 1.0;
theta.setProbabilities(p);
thetaBin.setProbabilities(p);
double randomRV = new RandomUtils(0).nextDouble();
int oneSample = theta.sample(randomRV);
int oneSample2 = thetaBin.sample(randomRV);
assertEquals("Testing Sample's Boundaries:", true, ((oneSample < p.length) && (oneSample >= 0)));
assertEquals("Testing Sample's Boundaries:", true, ((oneSample2 < p.length) && (oneSample2 >= 0)));
assertEquals("Testing Equal", true, oneSample == oneSample2);
int[] h1 = sampleHistogram(theta, 1000);
assertEquals("Testing Extreme Samples 0:", 0, h1[0]);
assertEquals("Testing Extreme Samples 1:", 0, h1[1]);
assertEquals("Testing Extreme Samples 2:", 1000, h1[2]);
p[0] = 0.33; p[1] = 0.33; p[2] = 0.34;
theta.setProbabilities(p);
thetaBin.setProbabilities(p);
int N = 1000000;
int[] h2 = sampleHistogram(theta, N);
int[] hBin = sampleHistogram(thetaBin, N);
for(int k = 0; k < h2.length; k ++){
assertEquals("Binary Equal to Linear", true, h2[k] == hBin[k]);
}
double e1 = Math.abs(h2[0]/(double)N - p[0]);
double e2 = Math.abs(h2[1]/(double)N - p[1]);
double e3 = Math.abs(h2[2]/(double)N - p[2]);
assertEquals("Testing Error 1:", true, e1 < 0.001);
assertEquals("Testing Error 2:", true, e2 < 0.001);
assertEquals("Testing Error 3:", true, e3 < 0.001);
MultinomialDistribution theta1 = new MultinomialDistribution(3, new MathLog(0), new MathExp(0), "normal");
MultinomialDistribution theta2 = new MultinomialDistribution(3, new MathLog(0), new MathExp(0), "log");
MultinomialDistribution theta3 = new MultinomialDistribution(3, new MathLog(0), new MathExp(0), "binary");
double[] p2 = new double[3];
p2[0] = 1.2; p2[1] = 2.3; p2[2] = 11.5;
double[] logp = new double[3];
for(int i = 0; i < p2.length; i++)
logp[i] = Math.log(p2[i]);
theta1.setProbabilities(p2);
theta2.setProbabilities(logp);
theta3.setProbabilities(p2);
N = 10000;
RandomUtils ru = new RandomUtils(1);
for (int i = 0; i < N; i++) {
double r = ru.nextDouble();
int i1 = theta1.sample(r);
int i2 = theta2.sample(r);
int i3 = theta3.sample(r);
assertEquals("Testing Log Sampling Accuracy", i1, i2);
assertEquals("Testing Log Sampling Accuracy", i1, i3);
}
}
} | 41.291667 | 117 | 0.596973 |
1835102e12aa373565f1a713f1587a6da3fa8313 | 258 | package com.example.cli.utils.cache;
public interface CacheClient<T> {
T get(String key);
boolean isExist(String key);
void set(String key, T value);
void set(final String key, T value, int millSeconds);
void remove(String key);
}
| 16.125 | 57 | 0.678295 |
dfb9aaaf591378b3fdbd42233a9abd9b3da18230 | 641 | package quick.pager.shop.goods.service;
import java.util.List;
import quick.pager.shop.goods.model.GoodsBrand;
import quick.pager.shop.goods.request.brand.GoodsBrandPageRequest;
import quick.pager.shop.goods.request.brand.GoodsBrandSaveRequest;
import quick.pager.shop.response.Response;
/**
* 商品品牌
*
* @author siguiyang
*/
public interface GoodsBrandService {
/**
* 品牌列表
*/
Response<List<GoodsBrand>> queryPage(GoodsBrandPageRequest request);
/**
* 新增
*/
Response<Long> create(GoodsBrandSaveRequest request);
/**
* 修改
*/
Response<Long> modify(GoodsBrandSaveRequest request);
}
| 20.677419 | 72 | 0.706708 |
90ea6456b3f2deb54772402292ba7b905961536b | 297 | package net.evendanan.pushingpixels;
/**
* Created by menny on 11/6/13.
*/
public interface Passengerable {
void setItemExpandExtraData(float originateViewCenterX, float originateViewCenterY,
float originateViewWidthScale, float originateViewHeightScale);
}
| 29.7 | 95 | 0.720539 |
8bb61f1a23704eaed40719c238a9a5fafcb6613c | 867 | import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
testClient();
}
public static void testClient() {
String host = "localhost";
int port = 8080;
System.out.println("连接到主机:" + host + " ,端口号:" + port);
try {
Socket client = new Socket(host, port);
System.out.println("远程主机地址:" + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("服务器响应:" + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 27.967742 | 67 | 0.696655 |
0544fa4287c4645a33031039aa746a28130db965 | 2,466 | package org.innovateuk.ifs.management.competition.setup.application.validator;
import org.innovateuk.ifs.competition.publiccontent.resource.FundingType;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionSetupQuestionResource;
import org.innovateuk.ifs.management.competition.setup.application.form.QuestionForm;
import org.junit.Before;
import org.junit.Test;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import static junit.framework.TestCase.assertEquals;
import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource;
import static org.innovateuk.ifs.competition.builder.CompetitionSetupQuestionResourceBuilder.newCompetitionSetupQuestionResource;
import static org.junit.Assert.assertTrue;
public class CompetitionSetupApplicationQuestionValidatorTest {
private CompetitionSetupApplicationQuestionValidator validator;
private BindingResult bindingResult;
@Before
public void setup() {
validator = new CompetitionSetupApplicationQuestionValidator();
}
@Test
public void invalidApplicationQuestion() {
long questionId = 1l;
CompetitionResource competitionResource = newCompetitionResource()
.withFundingType(FundingType.GRANT)
.build();
CompetitionSetupQuestionResource competitionSetupQuestionResource = newCompetitionSetupQuestionResource().build();
QuestionForm form = new QuestionForm();
form.setQuestion(competitionSetupQuestionResource);
DataBinder dataBinder = new DataBinder(form);
bindingResult = dataBinder.getBindingResult();
validator.validate(form, bindingResult, questionId, competitionResource);
assertTrue(bindingResult.hasErrors());
assertEquals(4, bindingResult.getErrorCount());
assertEquals("This field cannot be left blank.", bindingResult.getFieldError("numberOfUploads").getDefaultMessage());
assertEquals("This field cannot be left blank.", bindingResult.getFieldError("question.templateDocument").getDefaultMessage());
assertEquals("This field cannot be left blank.", bindingResult.getFieldError("question.writtenFeedback").getDefaultMessage());
assertEquals("This field cannot be left blank.", bindingResult.getFieldError("question.scored").getDefaultMessage());
}
}
| 46.528302 | 135 | 0.786699 |
85f8f683dd39207500a500a53c09647c214599b0 | 1,279 | package com.fund.system.service;
import java.util.Date;
import java.util.List;
import com.fund.system.domain.Holiday;
/**
* 节假日信息Service接口
*
* @author liulebin
* @date 2021-12-16
*/
public interface IHolidayService {
/**
* 查询节假日信息
*
* @param id 节假日信息主键
* @return 节假日信息
*/
public Holiday selectHolidayById(Long id);
/**
* 是否是假期
*
* @param date
* @return
*/
boolean isHoliday(Date date);
/**
* 查询节假日信息列表
*
* @param holiday 节假日信息
* @return 节假日信息集合
*/
public List<Holiday> selectHolidayList(Holiday holiday);
/**
* 新增节假日信息
*
* @param holiday 节假日信息
* @return 结果
*/
public int insertHoliday(Holiday holiday);
/**
* 修改节假日信息
*
* @param holiday 节假日信息
* @return 结果
*/
public int updateHoliday(Holiday holiday);
/**
* 批量删除节假日信息
*
* @param ids 需要删除的节假日信息主键集合
* @return 结果
*/
public int deleteHolidayByIds(Long[] ids);
/**
* 删除节假日信息信息
*
* @param id 节假日信息主键
* @return 结果
*/
public int deleteHolidayById(Long id);
/**
* 批量新增节假日信息
*
* @param holidays
* @return
*/
public int batchHolidays(List<Holiday> holidays);
}
| 16.189873 | 60 | 0.551212 |
f07f66c549fe35b0c7c2f45d119310988b0187dd | 6,861 | package com.articulate.sigma.nlg;
import com.articulate.sigma.KB;
import com.articulate.sigma.wordNet.WordNet;
import com.articulate.sigma.wordNet.WordNetUtilities;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multisets;
import com.google.common.collect.Sets;
/**
* Handles verb functionality for a SUMO process.
*/
public class SumoProcess {
private final String verb;
private VerbProperties.Polarity polarity = VerbProperties.Polarity.AFFIRMATIVE;
private final KB kb;
public SumoProcess(SumoProcess process, KB kb) {
this.verb = process.getVerb();
this.polarity = process.getPolarity();
this.kb = kb;
}
private String surfaceForm;
public SumoProcess(String verb, KB kb) {
this.verb = verb;
this.kb = kb;
}
/**************************************************************************************************************
* Indirectly invoked by SumoProcessCollector.toString( ).
* @return
*/
@Override
public String toString() {
return verb;
}
/**************************************************************************************************************
*
* @return
*/
public String getSurfaceForm() {
return surfaceForm;
}
/**************************************************************************************************************
*
* @param surfaceForm
*/
void setSurfaceForm(String surfaceForm) {
this.surfaceForm = surfaceForm;
}
/**************************************************************************************************************
* Try to phrase the verb into natural language, setting this object's internal state appropriately.
* @param sentence
*/
public void formulateNaturalVerb(Sentence sentence) {
String verbSurfaceForm = SumoProcess.getVerbRootForm(this.verb);
if (verbSurfaceForm == null || verbSurfaceForm.isEmpty()) {
setVerbAndDirectObject(sentence);
}
else {
// Prefix "doesn't" or "don't" for negatives.
String polarityPrefix = SumoProcess.getPolarityPrefix(this.polarity, sentence.getSubject().getSingularPlural());
if (sentence.getSubject().getSingularPlural().equals(SVOElement.NUMBER.SINGULAR) &&
this.polarity.equals(VerbProperties.Polarity.AFFIRMATIVE)) {
verbSurfaceForm = SumoProcess.verbRootToThirdPersonSingular(verbSurfaceForm);
}
setSurfaceForm(polarityPrefix + verbSurfaceForm);
}
}
/**************************************************************************************************************
* Return the correct prefix for negative sentences--"don't" or "doesn't". For affirmatives return empty string.
* @param polarity
* @param singularPlural
* @return
*/
private static String getPolarityPrefix(VerbProperties.Polarity polarity, SVOElement.NUMBER singularPlural) {
if (polarity.equals(VerbProperties.Polarity.AFFIRMATIVE)) {
return "";
}
// Singular negative.
if (singularPlural.equals(SVOElement.NUMBER.SINGULAR)) {
return "doesn't ";
}
// Plural negative
return "don't ";
}
/**************************************************************************************************************
* For a process which does not have a language representation, get a reasonable way of paraphrasing it.
* Sets both verb and direct object of the sentence.
*/
void setVerbAndDirectObject(Sentence sentence) {
// Prefix "doesn't" or "don't" for negatives.
String polarityPrefix = SumoProcess.getPolarityPrefix(this.polarity, sentence.getSubject().getSingularPlural());
// Set the verb, depending on the subject's case role and number.
String surfaceForm = "experience";
Multiset<CaseRole> experienceSubjectCaseRoles = HashMultiset.create(Sets.newHashSet(CaseRole.AGENT));
if(! Multisets.intersection(sentence.getSubject().getConsumedCaseRoles(), experienceSubjectCaseRoles).isEmpty()) {
surfaceForm = "perform";
}
if (sentence.getSubject().getSingularPlural().equals(SVOElement.NUMBER.SINGULAR) &&
this.getPolarity().equals(VerbProperties.Polarity.AFFIRMATIVE)) {
surfaceForm = surfaceForm + "s";
}
setSurfaceForm(polarityPrefix + surfaceForm);
// Now determine and set the direct object (which may end up displacing what would otherwise have been a
// direct object for this sentence).
// Turn, e.g. "IntentionalProcess" into "intentional process".
String formattedTerm = this.kb.getTermFormatMap("EnglishLanguage").get(this.verb);
String phrase = "";
if (formattedTerm != null && ! formattedTerm.isEmpty()) {
if (!kb.isSubclass(this.verb, "Substance")) {
String article = Noun.aOrAn(formattedTerm);
phrase = phrase + article + " ";
}
phrase = phrase + formattedTerm;
}
else {
phrase = phrase + "a " + this.verb.toLowerCase();
}
sentence.getDirectObject().setSurfaceForm(phrase);
sentence.getDirectObject().addConsumedCaseRole(CaseRole.PATIENT);
}
/**************************************************************************************************************
*
* @return
*/
public String getVerb() {
return verb;
}
/**************************************************************************************
* Getter and setter for polarity field.
*
*/
VerbProperties.Polarity getPolarity() {
return polarity;
}
public void setPolarity(VerbProperties.Polarity polarity) {
this.polarity = polarity;
}
/**************************************************************************************************************
*
* @param verbRoot
* @return
*/
public static String verbRootToThirdPersonSingular(String verbRoot) {
// FIXME: verbPlural is a misnomer; it finds the simple present singular form
return WordNetUtilities.verbPlural(verbRoot);
}
/**************************************************************************************************************
* Get the root of the given verb.
* @param gerund
* the verb in gerund (-ing) form.
* @return
* the root of the given verb, or null if not found
*/
public static String getVerbRootForm(String gerund) {
return WordNet.wn.verbRootForm(gerund, gerund.toLowerCase());
}
}
| 36.494681 | 125 | 0.535345 |
731c78ffc5e2e30d32a22f67900b9fc924af9fbb | 6,124 | package uk.lgl.modmenu;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Process;
import android.provider.Settings;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileOutputStream;
public class StaticActivity {
private static final String TAG = "Mod Menu";
public static String cacheDir;
public static void Start(final Context context) {
getIDoi(context);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(context)) {
AlertDialog alertDialog = new AlertDialog.Builder(context, 1)
.setTitle("No overlay permission")
.setMessage("Overlay permission is required in order to display the mod menu on top of the screen. Do you want to open the settings?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
context.startActivity(new Intent("android.settings.action.MANAGE_OVERLAY_PERMISSION",
Uri.parse("package:" + context.getPackageName())));
Process.killProcess(Process.myPid());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).setCancelable(false)
.create();
alertDialog.show();
} else {
// When you change the lib name, change also on Android.mk file
// Both must have same name
System.loadLibrary("MyLibName");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
context.startService(new Intent(context, MainActivity.class));
context.startService(new Intent(context, FloatingModMenuService.class));
}
}, 2000);
cacheDir = context.getCacheDir().getPath() + "/";
writeToFile("OpenMenu.ogg", Sounds.OpenMenu());
writeToFile("Back.ogg", Sounds.Back());
writeToFile("Select.ogg", Sounds.Select());
writeToFile("SliderIncrease.ogg", Sounds.SliderIncrease());
writeToFile("SliderDecrease.ogg", Sounds.SliderDecrease());
writeToFile("On.ogg", Sounds.On());
writeToFile("Off.ogg", Sounds.Off());
}
}
public static void getIDoi(final Context context) {
final String str = DeviceID.getDeviceId(context);
if (str == "permission error")
{
Toast.makeText(context, "You need phone permission in order to read device ID", Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(1);
}
}, 5000);
return;
}
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://example.000webhostapp.com/api.php", null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
String list = response.getString("customer");
Log.d("myapp", "Everything is good and dicek " + list + " and android id " + str);
if (list.contains(str)) {
Toast.makeText(context, "your device is registered", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "your device is not registered " + str, Toast.LENGTH_LONG).show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
System.exit(1);
}
}, 10000);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("myapp", "Something wrong");
}
});
requestQueue.add(jsonObjectRequest);
}
private static void writeToFile(String name, String base64) {
File file = new File(cacheDir + name);
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
byte[] decode = Base64.decode(base64, 0);
fos.write(decode);
fos.close();
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
} | 40.556291 | 177 | 0.541639 |
ea384f157be80621fba8276c2eb57346446640e4 | 3,424 | package com.avairebot.senither.utils;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import net.dv8tion.jda.api.entities.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ChatFilterUtil {
private static final List<String> blockedDomains = Arrays.asList(
"discordapp.com/invite/",
"discord.gg/"
);
private static final List<String> blockedMentionedDomains = Arrays.asList(
// Porn Advertisements
"viewc.site",
"privatepage.vip",
"nakedphotos.club"
);
private static final Logger LOGGER = LoggerFactory.getLogger(ChatFilterUtil.class);
private static final int MAX_REDIRECTS = 10;
private static final LoadingCache<String, String> cache = CacheBuilder.newBuilder()
.expireAfterWrite(2, TimeUnit.HOURS)
.build(new CacheLoader<String, String>() {
@Override
public String load(@Nonnull String key) throws Exception {
try {
return getTrueUrl(key, 0);
} catch (MalformedURLException ignored) {
return key;
} catch (IOException e) {
LOGGER.error("An exception was thrown while trying to resolve the true url for {}", key, e);
return key;
}
}
});
private static final Pattern urlPattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.|)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL
);
public static boolean isAdvertisement(Message jdaMessage) {
String message = jdaMessage.getContentRaw();
for (String domain : blockedMentionedDomains) {
if (message.toLowerCase().contains(domain)) {
return true;
}
}
Matcher matcher = urlPattern.matcher(message);
while (matcher.find()) {
String url = CacheUtil.getUncheckedUnwrapped(cache, message.substring(matcher.start(1), matcher.end()));
for (String domain : blockedDomains) {
if (url.contains(domain)) {
return true;
}
}
}
return false;
}
@Nonnull
private static String getTrueUrl(String url, int redirectsAttempts) throws IOException {
if (redirectsAttempts > MAX_REDIRECTS) {
return url;
}
System.setProperty("http.agent", "Chrome");
HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setInstanceFollowRedirects(false);
con.connect();
if (con.getHeaderField("Location") == null) {
return url;
}
return getTrueUrl(con.getHeaderField("Location"), ++redirectsAttempts);
}
}
| 33.242718 | 116 | 0.605432 |
2f98dbfd5ac94895acd29ba8f0d1c525aa7bfcac | 2,101 | package uk.gov.hmcts.reform.divorce.ccd;
import io.restassured.response.Response;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import uk.gov.hmcts.reform.ccd.client.model.CaseDetails;
import uk.gov.hmcts.reform.divorce.model.UserDetails;
import uk.gov.hmcts.reform.divorce.support.PetitionSupport;
import uk.gov.hmcts.reform.divorce.support.client.CcdClientSupport;
import uk.gov.hmcts.reform.divorce.util.ResourceLoader;
import uk.gov.hmcts.reform.divorce.util.RestUtil;
import java.util.Collections;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
@Ignore
public class CcdCaseRolesTest extends PetitionSupport {
private static final String SOL_PAYLOAD_CONTEXT_PATH = "ccd-solicitor-payload/";
@Value("${case.maintenance.add-petitioner-solicitor-role.context-path}")
private String addPetSolContextPath;
@Autowired
private CcdClientSupport ccdClientSupport;
@SuppressWarnings("unchecked")
@Test
public void givenSolicitorCreatedCase_whenAssignPetitionerSolRole_thenReturnOk() {
Map<String, Object> caseData = ResourceLoader.loadJsonToObject(SOL_PAYLOAD_CONTEXT_PATH + "base-case.json", Map.class);
UserDetails solicitorUser = getSolicitorUser();
CaseDetails caseDetails = ccdClientSupport.submitCaseForSolicitor(caseData, solicitorUser);
Long caseId = caseDetails.getId();
Response cmsResponse = addPetSolicitorRole(solicitorUser.getAuthToken(), caseId.toString());
assertThat(cmsResponse.getStatusCode(), equalTo(HttpStatus.OK.value()));
}
private Response addPetSolicitorRole(String authToken, String caseId) {
return RestUtil.putToRestService(
serverUrl + addPetSolContextPath + "/" + caseId,
Collections.singletonMap(HttpHeaders.AUTHORIZATION, authToken),
null, null);
}
}
| 38.907407 | 127 | 0.774869 |
76a436c1c8d7b9088a0da2eb5e023baac69b2e87 | 362 | package me.konsolas.conditionalcommands.placeholders;
import org.bukkit.entity.Player;
public class PlaceholderPerm extends AbstractParameteredPlaceholder {
public PlaceholderPerm() {
super("perm");
}
@Override
protected String getSub(Player player, String param) {
return player.hasPermission(param) ? "1.0" : "0.0";
}
}
| 22.625 | 69 | 0.701657 |
35ff55b26badbe9010a32d732f87663829b15065 | 155 | package net.zhuoweizhang.bingvenueaccess.model;
public class Geometry {
public boolean closed;
public double[] latitudes;
public double[] longitudes;
} | 22.142857 | 47 | 0.793548 |
7029db45c7ff462f2f0b3d7d09f7a6ae99565511 | 1,316 | package com.jpardogo.android.listbuddies.models;
import android.content.Context;
import com.jpardogo.android.listbuddies.R;
import com.jpardogo.android.listbuddies.adapters.CustomizeSpinnersAdapter;
import com.jpardogo.listbuddies.lib.views.ListBuddiesLayout;
/**
* Created by jpardogo on 22/02/2014.
*/
public class KeyValuePair {
private String key;
private Object value;
public KeyValuePair(String key, Object value) {
this.key = key;
this.value = value;
}
public int getColor(Context context) {
int color = ListBuddiesLayout.ATTR_NOT_SET;
if (value instanceof CustomizeSpinnersAdapter.OptionTypes) {
switch ((CustomizeSpinnersAdapter.OptionTypes) value) {
case BLACK:
color = context.getResources().getColor(R.color.black);
break;
case INSET:
color = context.getResources().getColor(R.color.inset);
break;
}
} else {
throw new ClassCastException("Wrong type of value, the value must be CustomizeSpinnersAdapter.OptionTypes");
}
return color;
}
public String getKey() {
return key;
}
public int getScrollOption() {
return (Integer) value;
}
}
| 28 | 120 | 0.62766 |
b81468223c02730e8d2aa6d3edff7185c46b5c0a | 509 | package com.jilin.mes.basic.model;
/*
* 创建时间 2018/7/3
* 作者: 程杰
* 博客: www.chengjie-jlu.com
*/
import com.jilin.mes.basic.constant.TableName;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* 科室表
*/
@Entity
@Table(name = TableName.DEPARTMENT)
public class Department {
/**
*科室编号
*/
@Id
@Column(length = 25)
private String number;
/**
* 科室名称
*/
private String name;
}
| 12.725 | 46 | 0.638507 |
418992049e0d3eaf2730ee4c3c204ddb0d352a1d | 11,275 | package gov.samhsa.ocp.ocpfis.service;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.gclient.IQuery;
import ca.uhn.fhir.rest.gclient.ReferenceClientParam;
import ca.uhn.fhir.rest.gclient.TokenClientParam;
import ca.uhn.fhir.validation.FhirValidator;
import gov.samhsa.ocp.ocpfis.config.FisProperties;
import gov.samhsa.ocp.ocpfis.domain.ProvenanceActivityEnum;
import gov.samhsa.ocp.ocpfis.domain.SearchKeyEnum;
import gov.samhsa.ocp.ocpfis.service.dto.PageDto;
import gov.samhsa.ocp.ocpfis.service.dto.RelatedPersonDto;
import gov.samhsa.ocp.ocpfis.service.exception.DuplicateResourceFoundException;
import gov.samhsa.ocp.ocpfis.service.exception.FHIRClientException;
import gov.samhsa.ocp.ocpfis.service.exception.ResourceNotFoundException;
import gov.samhsa.ocp.ocpfis.service.mapping.RelatedPersonToRelatedPersonDtoConverter;
import gov.samhsa.ocp.ocpfis.service.mapping.dtotofhirmodel.RelatedPersonDtoToRelatedPersonConverter;
import gov.samhsa.ocp.ocpfis.util.FhirOperationUtil;
import gov.samhsa.ocp.ocpfis.util.FhirProfileUtil;
import gov.samhsa.ocp.ocpfis.util.PaginationUtil;
import gov.samhsa.ocp.ocpfis.util.ProvenanceUtil;
import gov.samhsa.ocp.ocpfis.util.RichStringClientParam;
import lombok.extern.slf4j.Slf4j;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.RelatedPerson;
import org.hl7.fhir.dstu3.model.ResourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static java.util.stream.Collectors.toList;
@Service
@Slf4j
public class RelatedPersonServiceImpl implements RelatedPersonService {
private final IGenericClient fhirClient;
private final FhirValidator fhirValidator;
private final FisProperties fisProperties;
private final ProvenanceUtil provenanceUtil;
@Autowired
public RelatedPersonServiceImpl(IGenericClient fhirClient, FhirValidator fhirValidator, FisProperties fisProperties, ProvenanceUtil provenanceUtil) {
this.fhirClient = fhirClient;
this.fhirValidator = fhirValidator;
this.fisProperties = fisProperties;
this.provenanceUtil = provenanceUtil;
}
@Override
public PageDto<RelatedPersonDto> searchRelatedPersons(String patientId, Optional<String> searchKey, Optional<String> searchValue, Optional<Boolean> showInactive, Optional<Integer> pageNumber, Optional<Integer> pageSize, Optional<Boolean> showAll) {
int numberPerPage = PaginationUtil.getValidPageSize(fisProperties, pageSize, ResourceType.RelatedPerson.name());
IQuery relatedPersonIQuery = fhirClient.search().forResource(RelatedPerson.class).where(new ReferenceClientParam("patient").hasId("Patient/" + patientId));
//Set Sort order
relatedPersonIQuery = FhirOperationUtil.setLastUpdatedTimeSortOrder(relatedPersonIQuery, true);
if (searchKey.isPresent() && searchValue.isPresent()) {
if (searchKey.get().equalsIgnoreCase(SearchKeyEnum.RelatedPersonSearchKey.NAME.name())) {
relatedPersonIQuery.where(new RichStringClientParam("name").contains().value(searchValue.get().trim()));
} else if (searchKey.get().equalsIgnoreCase(SearchKeyEnum.CommonSearchKey.IDENTIFIER.name())) {
relatedPersonIQuery.where((new TokenClientParam(searchKey.get()).exactly().code(searchValue.get().trim())));
}
}
Bundle firstPageBundle;
Bundle otherPageBundle;
boolean firstPage = true;
firstPageBundle = (Bundle) relatedPersonIQuery.count(numberPerPage).returnBundle(Bundle.class).execute();
if (showAll.isPresent() && showAll.get()) {
List<RelatedPersonDto> patientDtos = convertAllBundleToSingleRelatedPersonDtoList(firstPageBundle, numberPerPage);
return (PageDto<RelatedPersonDto>) PaginationUtil.applyPaginationForCustomArrayList(patientDtos, patientDtos.size(), Optional.of(1), false);
}
if (firstPageBundle == null || firstPageBundle.getEntry().isEmpty()) {
log.info("No RelatedPerson was found for the given criteria");
return new PageDto<>(new ArrayList<>(), numberPerPage, 0, 0, 0, 0);
}
otherPageBundle = firstPageBundle;
if (pageNumber.isPresent() && pageNumber.get() > 1) {
firstPage = false;
otherPageBundle = PaginationUtil.getSearchBundleAfterFirstPage(fhirClient, fisProperties, firstPageBundle, pageNumber.get(), numberPerPage);
}
List<Bundle.BundleEntryComponent> relatedPersons = otherPageBundle.getEntry();
List<RelatedPersonDto> relatedPersonList = relatedPersons.stream().map(this::convertToRelatedPerson).collect(toList());
double totalPages = Math.ceil((double) otherPageBundle.getTotal() / numberPerPage);
int currentPage = firstPage ? 1 : pageNumber.get();
return new PageDto<>(relatedPersonList, numberPerPage, totalPages, currentPage, relatedPersonList.size(), otherPageBundle.getTotal());
}
@Override
public RelatedPersonDto getRelatedPersonById(String relatedPersonId) {
Bundle relatedPersonBundle = fhirClient.search().forResource(RelatedPerson.class)
.where(new TokenClientParam("_id").exactly().code(relatedPersonId))
.returnBundle(Bundle.class)
.execute();
if (relatedPersonBundle == null || relatedPersonBundle.getEntry().isEmpty()) {
throw new ResourceNotFoundException("No RelatedPerson was found for the given RelatedPersonID : " + relatedPersonId);
}
Bundle.BundleEntryComponent relatedPersonBundleEntry = relatedPersonBundle.getEntry().get(0);
RelatedPerson relatedPerson = (RelatedPerson) relatedPersonBundleEntry.getResource();
return RelatedPersonToRelatedPersonDtoConverter.map(relatedPerson);
}
@Override
public void createRelatedPerson(RelatedPersonDto relatedPersonDto, Optional<String> loggedInUser) {
List<String> idList = new ArrayList<>();
checkForDuplicates(relatedPersonDto, relatedPersonDto.getPatient());
try {
final RelatedPerson relatedPerson = RelatedPersonDtoToRelatedPersonConverter.map(relatedPersonDto);
//Set Profile Meta Data
FhirProfileUtil.setRelatedPersonProfileMetaData(fhirClient, relatedPerson);
//Validate
FhirOperationUtil.validateFhirResource(fhirValidator, relatedPerson, Optional.empty(), ResourceType.RelatedPerson.name(), "Create RelatedPerson");
//Create
MethodOutcome methodOutcome = FhirOperationUtil.createFhirResource(fhirClient, relatedPerson, ResourceType.RelatedPerson.name());
idList.add(ResourceType.RelatedPerson.name() + "/" + FhirOperationUtil.getFhirId(methodOutcome));
if(fisProperties.isProvenanceEnabled()) {
provenanceUtil.createProvenance(idList, ProvenanceActivityEnum.CREATE, loggedInUser);
}
} catch (ParseException e) {
throw new FHIRClientException("FHIR Client returned with an error while creating a RelatedPerson : " + e.getMessage());
}
}
@Override
public void updateRelatedPerson(String relatedPersonId, RelatedPersonDto relatedPersonDto, Optional<String> loggedInUser) {
List<String> idList = new ArrayList<>();
relatedPersonDto.setRelatedPersonId(relatedPersonId);
try {
final RelatedPerson relatedPerson = RelatedPersonDtoToRelatedPersonConverter.map(relatedPersonDto);
//Set Profile Meta Data
FhirProfileUtil.setRelatedPersonProfileMetaData(fhirClient, relatedPerson);
//Validate
FhirOperationUtil.validateFhirResource(fhirValidator, relatedPerson, Optional.of(relatedPersonId), ResourceType.RelatedPerson.name(), "Update RelatedPerson");
//Update the resource
MethodOutcome methodOutcome = FhirOperationUtil.updateFhirResource(fhirClient, relatedPerson, "Update RelatedPerson");
idList.add(ResourceType.RelatedPerson.name() + "/" + FhirOperationUtil.getFhirId(methodOutcome));
if(fisProperties.isProvenanceEnabled()) {
provenanceUtil.createProvenance(idList, ProvenanceActivityEnum.UPDATE, loggedInUser);
}
} catch (ParseException e) {
throw new FHIRClientException("FHIR Client returned with an error while creating a RelatedPerson : " + e.getMessage());
}
}
private void checkForDuplicates(RelatedPersonDto relatedPersonDto, String patientId) {
Bundle relatedPersonBundle = (Bundle) FhirOperationUtil.setNoCacheControlDirective(fhirClient.search().forResource(RelatedPerson.class)
.where(RelatedPerson.IDENTIFIER.exactly().systemAndIdentifier(relatedPersonDto.getIdentifierType(), relatedPersonDto.getIdentifierValue()))
.where(new TokenClientParam("patient").exactly().code(patientId)))
.returnBundle(Bundle.class)
.execute();
log.info("Existing RelatedPersons size : " + relatedPersonBundle.getEntry().size());
if (!relatedPersonBundle.getEntry().isEmpty()) {
throw new DuplicateResourceFoundException("RelatedPerson already exists with the given Identifier Type and Identifier Value");
} else {
Bundle rPBundle = (Bundle) FhirOperationUtil.setNoCacheControlDirective(fhirClient.search().forResource(RelatedPerson.class)
.where(new TokenClientParam("patient").exactly().code(patientId)))
.returnBundle(Bundle.class)
.execute();
if (!FhirOperationUtil.getAllBundleComponentsAsList(rPBundle, Optional.empty(), fhirClient, fisProperties).stream().filter(relatedP -> {
RelatedPerson rp = (RelatedPerson) relatedP.getResource();
return rp.getIdentifier().stream().anyMatch(identifier -> identifier.getSystem().equalsIgnoreCase(relatedPersonDto.getIdentifierType()) && identifier.getValue().replaceAll(" ", "")
.replaceAll("-", "").trim()
.equalsIgnoreCase(relatedPersonDto.getIdentifierValue().replaceAll(" ", "").replaceAll("-", "").trim()));
}).collect(toList()).isEmpty()) {
throw new DuplicateResourceFoundException("RelatedPerson already exists with the given Identifier Type and Identifier Value");
}
}
}
private RelatedPersonDto convertToRelatedPerson(Bundle.BundleEntryComponent bundleEntryComponent) {
return RelatedPersonToRelatedPersonDtoConverter.map((RelatedPerson) bundleEntryComponent.getResource());
}
private List<RelatedPersonDto> convertAllBundleToSingleRelatedPersonDtoList(Bundle firstPageSearchBundle, int numberOBundlePerPage) {
return FhirOperationUtil.getAllBundleComponentsAsList(firstPageSearchBundle, Optional.of(numberOBundlePerPage), fhirClient, fisProperties)
.stream().map(this::convertToRelatedPerson)
.collect(toList());
}
}
| 51.25 | 252 | 0.727007 |
491cc696e1cdbe719f03d7b4b40f513362bbfbfc | 2,788 | package edu.fiuba.algo3.modelo.preguntas;
import edu.fiuba.algo3.modelo.Jugador;
import edu.fiuba.algo3.modelo.Opcion;
import edu.fiuba.algo3.modelo.Respuesta;
import edu.fiuba.algo3.modelo.preguntas.MultipleChoice;
import edu.fiuba.algo3.modelo.preguntas.TipoParcial;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class PreguntaMultipleChoiceConPuntajeParcialTest {
@Test
public void testUnaPreguntaMultipleChoiceConPuntajeParcialPuedeCrearseIndicandoleCualEsLaRespuestaCorrecta(){
Opcion opcionCorrecta = new Opcion("4",true);
Opcion opcionCorrecta2 = new Opcion("2^2",true);
Opcion opcionIncorrecta = new Opcion("8",false);
Opcion opcionIncorrecta2 = new Opcion("Pez",false);
ArrayList<Opcion> opciones = new ArrayList<Opcion>(Arrays.asList(opcionCorrecta,opcionCorrecta2,opcionIncorrecta,opcionIncorrecta2));
TipoParcial tipoParcial = new TipoParcial();
MultipleChoice multipleChoiceParcial = new MultipleChoice(" 2+2=..? ", opciones, tipoParcial);
ArrayList<Opcion> opcionesCorrectas = new ArrayList<Opcion>(Arrays.asList(opcionCorrecta2,opcionCorrecta));
assertTrue(multipleChoiceParcial.opcionesCorrectas().containsAll(opcionesCorrectas));
}
@Test
public void testUnaPreguntaMultipleChoiceConPuntajeParcialRecibeUnaListaDeRespuestasYAsignaCorrectamentePuntosALosJugadoresQueRespondieronCorrectamente(){
Jugador jugador1 = new Jugador();
Jugador jugador2 = new Jugador();
Opcion opcionCorrecta = new Opcion("4",true);
Opcion opcionCorrecta2 = new Opcion("2^2",true);
Opcion opcionIncorrecta = new Opcion("8",false);
Opcion opcionIncorrecta2 = new Opcion("Pez",false);
ArrayList<Opcion> opciones = new ArrayList<Opcion>(Arrays.asList(opcionCorrecta,opcionCorrecta2,opcionIncorrecta,opcionIncorrecta2));
TipoParcial tipoParcial = new TipoParcial();
MultipleChoice multipleChoiceParcial = new MultipleChoice(" 2+2=..? ", opciones,tipoParcial);
Respuesta respuestaJugador1 = new Respuesta(jugador1);
Respuesta respuestaJugador2 = new Respuesta(jugador2);
respuestaJugador1.agregarOpcion(opcionCorrecta);
respuestaJugador1.agregarOpcion(opcionCorrecta2);
respuestaJugador2.agregarOpcion(opcionIncorrecta);
respuestaJugador2.agregarOpcion(opcionCorrecta2);
multipleChoiceParcial.asignarPuntaje(respuestaJugador1);
multipleChoiceParcial.asignarPuntaje(respuestaJugador2);
assertEquals(2,jugador1.puntaje());
assertEquals(0,jugador2.puntaje());
}
}
| 38.722222 | 158 | 0.754663 |
cfb65649ea8be80113a4f480ff8c70bf3b47f846 | 674 | package com.device.security.activities;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
/* compiled from: lambda */
public final /* synthetic */ class -$$Lambda$BlockedAppActivity$ieiDy6OeJ0a9p4tNBYtAVQhpnZI implements OnKeyListener {
private final /* synthetic */ BlockedAppActivity f$0;
public /* synthetic */ -$$Lambda$BlockedAppActivity$ieiDy6OeJ0a9p4tNBYtAVQhpnZI(BlockedAppActivity blockedAppActivity) {
this.f$0 = blockedAppActivity;
}
public final boolean onKey(View view, int i, KeyEvent keyEvent) {
return this.f$0.lambda$onCreate$1$BlockedAppActivity(view, i, keyEvent);
}
}
| 35.473684 | 124 | 0.752226 |
aa97e8587cf6140e96dee25b64f3819112542b75 | 27,109 | package vproxybase.processor.http1;
import vproxybase.processor.ConnectionDelegate;
import vproxybase.processor.OOSubContext;
import vproxybase.processor.Processor;
import vproxybase.processor.http1.builder.ChunkBuilder;
import vproxybase.processor.http1.builder.HeaderBuilder;
import vproxybase.processor.http1.builder.RequestBuilder;
import vproxybase.processor.http1.builder.ResponseBuilder;
import vproxybase.processor.http1.entity.Request;
import vproxybase.processor.http1.entity.Response;
import vproxybase.util.ByteArray;
import vproxybase.util.Logger;
import vproxybase.util.Utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
@SuppressWarnings("StatementWithEmptyBody")
public class HttpSubContext extends OOSubContext<HttpContext> {
private int state = 0;
/*
* 0 => idle ~> 1 (if request) or -> 22 (if response)
* 1 => method ~> SP -> 2
* 2 => uri ~> SP -> 3 or \r\n -> 4
* 3 => version ~> \r\n -> 4
* 4 => end-first-line ~> -> 5 or \r\n -> 9
* 5 => header-key ~> ":" -> 6
* 6 => header-split ~> -> 7 or \r\n -> 8
* 7 => header-value ~> \r\n -> 8
* 8 => end-one-header ~> -> 5 or \r\n -> 9
* 9 => end-all-headers ~> (if content-length) -> 10 or (if transfer-encoding:chunked) -> 11 or end -> 0
* 10 => body ~> end -> 0
* 11 => chunk ~> ";" -> 12 or \r\n -> 14
* 12 => chunk-extension-split ~> -> 13 or \r\n -> 14
* 13 => chunk-extension ~> \r\n -> 14
* 14 => end-chunk-size ~> (if chunk-size) -> 15 or (if !chunk-size) -> 17 or \r\n -> 21
* 15 => chunk-content ~> \r\n -> 16
* 16 => end-chunk-content ~> chunk -> 11
* 17 => trailer-key ~> ":" -> 18
* 18 => trailer-split ~> -> 19 or \r\n -> 20
* 19 => trailer-value ~> \r\n -> 20
* 20 => end-one-trailer ~> -> 17 or \r\n -> 21
* 21 => end-all ~> 0
*
* 22 => response-version ~> SP -> 23
* 23 => status ~> SP -> 24
* 24 => reason ~> \r\n -> 4
*/
private final Handler[] handlers = new Handler[]{
HttpSubContext.this::state0,
HttpSubContext.this::state1,
HttpSubContext.this::state2,
HttpSubContext.this::state3,
HttpSubContext.this::state4,
HttpSubContext.this::state5,
HttpSubContext.this::state6,
HttpSubContext.this::state7,
HttpSubContext.this::state8,
HttpSubContext.this::state9,
HttpSubContext.this::state10,
HttpSubContext.this::state11,
HttpSubContext.this::state12,
HttpSubContext.this::state13,
HttpSubContext.this::state14,
HttpSubContext.this::state15,
HttpSubContext.this::state16,
HttpSubContext.this::state17,
HttpSubContext.this::state18,
HttpSubContext.this::state19,
HttpSubContext.this::state20,
HttpSubContext.this::state21,
HttpSubContext.this::state22,
HttpSubContext.this::state23,
HttpSubContext.this::state24,
};
interface Handler {
void handle(byte b) throws Exception;
}
private byte[] buf;
private int bufOffset = 0;
private RequestBuilder req;
private ResponseBuilder resp;
private List<HeaderBuilder> headers;
private HeaderBuilder header;
private List<ChunkBuilder> chunks;
private ChunkBuilder chunk;
private List<HeaderBuilder> trailers;
private HeaderBuilder trailer;
private int proxyLen = -1;
// value of the uri
// would be used as the hint
String theUri = null;
// value of the 'Host: xxx' header
// would be used as the hint
// only accessed when it's a frontend sub context
// if it's a backend sub context, the field might be set but never used
String theHostHeader = null;
private StringBuilder theConnectionHeader = null;
// all these endHeaders fields will set to true in state9 (end-all-headers)
// if there's no body and chunk, the [0] will be set to false because statm will call end() to reset states
// otherwise [0] will remain to be true until the body/chunk is properly handled
// however [1] will always be set to false after state9 finishes in the feed(...) loop
// and [2] will remain to be true after [0] is set to false in the feed(...) loop
// to separate these fields is because we need to alert the feed(...) method when the headers end
// and also we need to know whether we can safely return bytes in the feed(...) method
//
// the first line and the headers are deserialized and may be modified before responding
// so the raw bytes for the headers must not be returned from feed(...).
//
// generally:
// endHeaders[0] means the state machine thinks the headers are ended for current parsing process
// endHeaders[1] means the headers bytes is going to be serialized
// endHeaders[2] means the data in method feed(...) can be returned
private final boolean[] endHeaders = new boolean[]{false, false, false};
private boolean parserMode;
// bytes consumed via feed(...) but paused before handling
ByteArray storedBytesForProcessing = null;
public HttpSubContext(HttpContext httpContext, int connId, ConnectionDelegate delegate) {
super(httpContext, connId, delegate);
}
@Override
public Processor.ProcessorTODO process() {
Processor.ProcessorTODO ret;
if (mode() == Processor.Mode.handle) {
ret = Processor.ProcessorTODO.create();
ret.mode = Processor.Mode.handle;
ret.len = len();
ret.feed = this::processorFeed;
} else {
ret = Processor.ProcessorTODO.createProxy();
ret.len = len();
ret.proxyTODO.proxyDone = this::proxyDone;
if (isFrontend()) {
ret.proxyTODO.connTODO = ctx.connection();
}
}
return ret;
}
public int len() {
if (mode() == Processor.Mode.handle) {
// do feed, and -1 means feed any data into the processor
return -1;
}
if (ctx.upgradedConnection) {
return 0x00ffffff; // use max uint24 to prevent some possible overflow
}
return proxyLen;
}
public void setParserMode() {
this.parserMode = true;
}
public RequestBuilder getParsingReq() {
return this.req;
}
public Request getReq() {
return this.req.build();
}
public Response getResp() {
return this.resp.build();
}
public boolean isIdle() {
return state == 0;
}
public boolean isBeforeBody() {
return state == 10 || state == 11;
}
private Processor.Mode mode() {
if (ctx.upgradedConnection) {
return Processor.Mode.proxy;
}
switch (state) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 11:
case 12:
case 13:
case 14:
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
return Processor.Mode.handle;
case 10:
case 15:
return Processor.Mode.proxy;
}
throw new IllegalStateException("BUG: unexpected state " + state);
}
public Processor.HandleTODO processorFeed(ByteArray data) throws Exception {
Processor.HandleTODO handleTODO = Processor.HandleTODO.create();
handleTODO.send = feedWithStored(data);
handleTODO.frameEnds = state == 0;
if (isFrontend()) {
handleTODO.connTODO = ctx.connection();
}
return handleTODO;
}
private ByteArray feedWithStored(ByteArray data) throws Exception {
if (!ctx.frontendExpectingResponse && isFrontend() && data.length() > 0) {
// the frontend is expecting to receiving response when receiving headers,
// regardless of whether the request is completely received
ctx.frontendExpectingResponse = true;
}
boolean isIdleBeforeFeeding = state == 0;
if (storedBytesForProcessing != null) {
data = storedBytesForProcessing.concat(data);
storedBytesForProcessing = null;
}
ByteArray ret = feed(data);
boolean isIdleAfterFeeding = state == 0;
if (isFrontend() && isIdleBeforeFeeding && isIdleAfterFeeding) {
ctx.currentBackend = -1;
}
return ret;
}
public ByteArray feed(ByteArray data) throws Exception {
int consumedBytes = 0;
ByteArray headersBytes = null;
while (consumedBytes < data.length()) {
feed(data.get(consumedBytes++));
if (parserMode) { // headers manipulation is skipped in parser mode
continue;
}
if (endHeaders[1]) {
if (isFrontend()) {
headersBytes = req.build().toByteArray();
} else {
headersBytes = resp.build().toByteArray();
}
// cut the headers part from data
data = data.sub(consumedBytes, data.length() - consumedBytes);
consumedBytes = 0;
// unset the field
endHeaders[1] = false;
}
// handle byte to be proxied but consumed via feed(...)
if (proxyLen > 0) {
// need to do proxy
int originalCursor = consumedBytes;
consumedBytes += proxyLen;
if (consumedBytes > data.length()) {
// input data has fewer bytes than required
// so still need to do proxy later
consumedBytes = data.length();
}
// need to feed to update the state machine
for (int i = originalCursor; i < consumedBytes; ++i) {
feed(data.get(i));
}
}
// check whether request handling is done
if (isFrontend() && state == 0 /*idle*/) {
break;
}
}
if (parserMode) { // ignore pipeline disabling in parser mode
return data;
}
// there might be bytes not processed yet, cut the bytes
if (consumedBytes < data.length()) {
storedBytesForProcessing = data.sub(consumedBytes, data.length() - consumedBytes);
data = data.sub(0, consumedBytes);
}
if (!endHeaders[2]) { // return nothing because the headers are not ended yet
return null;
}
if (!endHeaders[0]) {
endHeaders[2] = false; // processing finished
if (isFrontend()) {
delegate.pause(); // pause the requests, will be resumed when response finishes
}
}
// return
if (headersBytes != null) {
if (data.length() == 0) {
return headersBytes;
} else {
return headersBytes.concat(data);
}
} else {
return data;
}
}
public void feed(byte b) throws Exception {
if (state < 0 || state >= handlers.length) {
throw new IllegalStateException("BUG: unexpected state " + state);
}
handlers[state].handle(b);
}
private void _proxyDone() {
proxyLen = -1;
if (state == 10) {
end(); // done when body ends
if (isFrontend()) {
ctx.currentBackend = -1; // clear backend
}
} else if (state == 15) {
state = 16;
}
}
private Processor.ProxyDoneTODO proxyDone() {
if (ctx.upgradedConnection) {
return null;
}
int stateWas = this.state;
_proxyDone();
if (stateWas == 10) {
endHeaders[2] = false; // it should be set in feed(...) but there's no chance that feed(...) can be called, so set to false here
}
if (state == 0) {
return Processor.ProxyDoneTODO.createFrameEnds();
} else {
return null;
}
}
@Override
public Processor.HandleTODO connected() {
return null; // never respond when connected
}
@Override
public Processor.HandleTODO remoteClosed() {
return null; // TODO handle http/1.0 without content-length and not chunked
}
@Override
public Processor.DisconnectTODO disconnected(boolean exception) {
if (!ctx.frontendExpectingResponse) {
assert Logger.lowLevelDebug("not expecting response, so backend disconnecting is fine");
return Processor.DisconnectTODO.createSilent();
}
if (ctx.frontendExpectingResponseFrom != connId) {
assert Logger.lowLevelDebug("the disconnected connection is not response connection");
return Processor.DisconnectTODO.createSilent();
}
assert Logger.lowLevelDebug("it's expecting response from the disconnected backend, which is invalid");
return null;
}
// start handler methods
private void end() {
state = 0;
headers = null;
theConnectionHeader = null;
endHeaders[0] = false;
if (!isFrontend() && !parserMode) {
ctx.clearFrontendExpectingResponse(this);
}
}
private void state0(byte b) {
if (isFrontend()) {
req = new RequestBuilder();
state = 1;
state1(b);
} else {
resp = new ResponseBuilder();
state = 22;
state22(b);
}
}
private void state1(byte b) {
if (b == ' ') {
state = 2;
} else {
req.method.append((char) b);
}
}
private void state2(byte b) {
if (b == ' ') {
theUri = req.uri.toString();
state = 3;
} else if (b == '\r') {
// do nothing
} else if (b == '\n') {
theUri = req.uri.toString();
state = 4;
} else {
req.uri.append((char) b);
}
}
private void state3(byte b) {
if (b == '\r') {
// do nothing
} else if (b == '\n') {
state = 4;
} else {
if (req.version == null) {
req.version = new StringBuilder();
}
req.version.append((char) b);
}
}
private void state4(byte b) throws Exception {
if (b == '\r') {
// do nothing
} else if (b == '\n') {
state = 9;
state9(null);
} else {
state = 5;
state5(b);
}
}
private void state5(byte b) throws Exception {
if (header == null) {
header = new HeaderBuilder();
}
if (b == ':') {
state = 6;
state6(b);
} else {
header.key.append((char) b);
}
}
private void state6(byte b) throws Exception {
if (b == ':') {
state = 7;
} else {
throw new Exception("invalid header: " + header + ", invalid splitter " + (char) b);
}
}
private void state7(byte b) {
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 8;
} else {
if (b != ' ' || header.value.length() != 0) { // leading spaces of the value are ignored
header.value.append((char) b);
}
}
}
private void state8(byte b) throws Exception {
if (headers == null) {
headers = new LinkedList<>();
if (isFrontend()) {
req.headers = headers;
} else {
resp.headers = headers;
}
}
if (header != null) {
assert Logger.lowLevelDebug("received header " + header);
boolean addHeader = true;
if (isFrontend()) { // only modify headers if it's frontend
String k = header.key.toString().trim().toLowerCase();
switch (k) {
case "host":
theHostHeader = header.value.toString().trim();
break;
case "connection":
if (!header.value.toString().trim().equalsIgnoreCase("close")) {
theConnectionHeader = header.value;
// keep the Connection: xxx header if it's not 'close'
break;
}
// fall through
case "x-forwarded-for":
case "x-client-port":
case "keep-alive":
// we remove these headers from request
addHeader = false;
break;
}
}
if (addHeader) {
headers.add(header);
}
header = null;
}
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 9;
state9(null);
} else {
state = 5;
state5(b);
}
}
private void addAdditionalHeaders() {
if (parserMode) { // headers manipulation is skipped in parser mode
return;
}
if (headers == null) {
headers = new ArrayList<>(2);
req.headers = headers;
}
// x-forwarded-for
{
HeaderBuilder h = new HeaderBuilder();
h.key.append("x-forwarded-for");
h.value.append(ctx.clientAddress);
headers.add(h);
assert Logger.lowLevelDebug("add header " + h);
}
// x-client-port
{
HeaderBuilder h = new HeaderBuilder();
h.key.append("x-client-port");
h.value.append(ctx.clientPort);
headers.add(h);
assert Logger.lowLevelDebug("add header " + h);
}
// connection
if (theConnectionHeader == null) {
HeaderBuilder h = new HeaderBuilder();
h.key.append("Connection");
h.value.append("Keep-Alive");
headers.add(h);
assert Logger.lowLevelDebug("add header " + h);
}
}
// this method should be called before entering state 9
// it's for state transferring
private void state9(@SuppressWarnings("unused") Byte b) {
Arrays.fill(endHeaders, true);
if (isFrontend()) {
addAdditionalHeaders(); // add additional headers
}
if (headers == null) {
end();
return;
}
for (var h : headers) {
String hdr = h.key.toString().trim();
if (hdr.equalsIgnoreCase("content-length")) {
String len = h.value.toString().trim();
assert Logger.lowLevelDebug("found Content-Length: " + len);
int intLen = Integer.parseInt(len);
if (intLen == 0) {
end();
} else {
state = 10;
proxyLen = intLen;
}
return;
} else if (hdr.equalsIgnoreCase("transfer-encoding")) {
String encoding = h.value.toString().trim().toLowerCase();
assert Logger.lowLevelDebug("found Transfer-Encoding: " + encoding);
if (encoding.equals("chunked")) {
state = 11;
}
return;
} else if (hdr.equalsIgnoreCase("upgrade")) {
if (!parserMode && connId != 0) { // will fallback to raw tcp proxying if the connection is upgraded
assert Logger.lowLevelDebug("found upgrade header: " + h.value);
ctx.upgradedConnection = true;
proxyLen = 0x00ffffff; // use max uint24 to prevent some possible overflow
}
}
}
assert Logger.lowLevelDebug("Content-Length and Transfer-Encoding both not found");
end();
}
private void state10(byte b) {
int contentLength = proxyLen;
--proxyLen;
if (isFrontend()) {
if (parserMode) { // use a byte array buffer to hold the data
if (req.body == null) {
buf = Utils.allocateByteArray(contentLength);
bufOffset = 0;
req.body = ByteArray.from(buf);
}
buf[bufOffset++] = b;
} // else do nothing
} else {
if (parserMode) {
if (resp.body == null) {
buf = Utils.allocateByteArray(contentLength);
bufOffset = 0;
resp.body = ByteArray.from(buf);
}
buf[bufOffset++] = b;
} // else do nothing
}
if (proxyLen == 0) {
buf = null;
// call proxyDone to generalize the 'handle' mode and 'proxy' mode for the body
_proxyDone();
}
}
private void state11(byte b) throws Exception {
if (chunk == null) {
chunk = new ChunkBuilder();
}
if (b == ';') {
state = 12;
} else if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 14;
state14(null);
} else {
chunk.size.append((char) b);
}
}
private void state12(byte b) throws Exception {
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 14;
state14(null);
} else {
state = 13;
if (chunk.extension == null) {
chunk.extension = new StringBuilder();
}
chunk.extension.append((char) b);
}
}
private void state13(byte b) throws Exception {
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 14;
state14(null);
} else {
chunk.extension.append((char) b);
}
}
// this method may be called before entering state 9
// it's for state transferring
private void state14(Byte b) throws Exception {
int size = chunk == null ? 0 : Integer.parseInt(chunk.size.toString().trim(), 16);
if (size != 0) {
state = 15;
proxyLen = size;
} else {
if (b == null) { // called from other states
// end chunk
if (chunks == null) {
chunks = new LinkedList<>();
}
chunks.add(chunk);
chunk = null;
if (isFrontend()) {
req.chunks = chunks;
} else {
resp.chunks = chunks;
}
chunks = null;
} else {
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 21;
state21(null);
} else {
state = 17;
state17(b);
}
}
}
}
private void state15(byte b) {
int contentLength = proxyLen;
--proxyLen;
if (parserMode) {
if (chunk.content == null) {
buf = Utils.allocateByteArray(contentLength);
bufOffset = 0;
chunk.content = ByteArray.from(buf);
}
buf[bufOffset++] = b;
} // else do nothing
if (proxyLen == 0) {
buf = null;
// call proxyDone to generalize the 'handle' mode and 'proxy' mode for the chunk
_proxyDone();
}
}
private void state16(byte b) throws Exception {
if (chunks == null) {
chunks = new LinkedList<>();
}
if (chunk != null) {
chunks.add(chunk);
chunk = null;
}
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 11;
} else {
throw new Exception("invalid chunk end");
}
}
private void state17(byte b) throws Exception {
if (trailer == null) {
trailer = new HeaderBuilder();
}
if (b == ':') {
state = 18;
state18(b);
} else {
trailer.key.append((char) b);
}
}
private void state18(byte b) throws Exception {
if (b == ':') {
state = 19;
} else {
throw new Exception("invalid trailer: " + header + ", invalid splitter " + (char) b);
}
}
private void state19(byte b) {
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 20;
} else {
if (b != ' ' || trailer.value.length() > 0) { // leading spaces are ignored
trailer.value.append((char) b);
}
}
}
private void state20(byte b) throws Exception {
if (trailers == null) {
trailers = new LinkedList<>();
}
if (trailer != null) {
assert Logger.lowLevelDebug("received trailer " + trailer);
trailers.add(trailer);
trailer = null;
}
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 21;
if (isFrontend()) {
req.trailers = trailers;
} else {
resp.trailers = trailers;
}
trailers = null;
state21(null);
} else {
state = 17;
state17(b);
}
}
// this method should be called before entering state 9
// it's for state transferring
private void state21(@SuppressWarnings("unused") Byte b) {
end();
}
private void state22(byte b) {
if (b == ' ') {
state = 23;
} else {
resp.version.append((char) b);
}
}
private void state23(byte b) throws Exception {
if (b == ' ') {
state = 24;
} else {
if (b < '0' || b > '9') {
throw new Exception("invalid character in http response status code: " + ((char) b));
}
resp.statusCode.append((char) b);
}
}
private void state24(byte b) {
if (b == '\r') {
// ignore
} else if (b == '\n') {
state = 4;
} else {
resp.reason.append((char) b);
}
}
}
| 31.892941 | 140 | 0.498358 |
8e7881a0f1aac6078fa2d56ac5bdcc03bd6fe8b8 | 3,663 | package util;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class XMLProcessor {
public static Document importXMLDocument(String filepath){
String xmlCode = FileImporter.importFile(filepath);
try {
return parseXML(xmlCode);
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return null;
}
public static Document parseXML(String xmlCode) throws ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = null;
ByteArrayInputStream input = null;
try {
input = new ByteArrayInputStream(
xmlCode.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
doc = builder.parse(input);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
public static String getAttributeValue(String attributeName, Node node){
Node attribute = node.getAttributes().getNamedItem(attributeName);
if(attribute!=null){
return attribute.getNodeValue();
}
return null;
}
public static List<Node> getNodesByTagName(String tagName, Element element){
List<Node> nodes = new ArrayList<>();
NodeList nl = element.getElementsByTagName(tagName);
if(nl!=null) {
for (int i = 0; i < nl.getLength(); i++) {
nodes.add(nl.item(i));
}
}
return nodes;
}
public static List<Node> getNodesByTagName(String tagName, Document document){
List<Node> nodes = new ArrayList<>();
NodeList nl = document.getElementsByTagName(tagName);
for(int i = 0; i<nl.getLength(); i++){
nodes.add(nl.item(i));
}
return nodes;
}
public static Node getNodeById(String id, Document document){
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = null;
try {
String e = "//*[@id=\""+id+"\"]";
expr = xpath.compile(e);
NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
if(nl.getLength()>0){
return nl.item(0);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return null;
}
public static Node getNodeById(String id, Element element){
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = null;
try {
expr = xpath.compile("//*[@id=\'"+id+"\']");
NodeList nl = (NodeList) expr.evaluate(element, XPathConstants.NODESET);
if(nl.getLength()>0){
return nl.item(0);
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
return null;
}
}
| 30.272727 | 89 | 0.60415 |
8388c44b71b8e3bbc85fecb1642583afa520c260 | 1,265 | package fr.snapgames.fromclasstogame.demo.behaviors;
import fr.snapgames.fromclasstogame.core.behaviors.Behavior;
import fr.snapgames.fromclasstogame.core.entity.GameObject;
import fr.snapgames.fromclasstogame.core.gfx.Render;
import fr.snapgames.fromclasstogame.core.io.actions.ActionHandler;
import fr.snapgames.fromclasstogame.demo.entity.InventoryObject;
import java.awt.event.KeyEvent;
public class InventorySelectorBehavior implements Behavior<GameObject> {
@Override
public void onInput(GameObject go, ActionHandler ih) {
InventoryObject io = (InventoryObject) go;
testKey(ih, io, KeyEvent.VK_1, 1);
testKey(ih, io, KeyEvent.VK_2, 2);
testKey(ih, io, KeyEvent.VK_3, 3);
testKey(ih, io, KeyEvent.VK_4, 4);
testKey(ih, io, KeyEvent.VK_5, 5);
testKey(ih, io, KeyEvent.VK_6, 6);
testKey(ih, io, KeyEvent.VK_7, 7);
testKey(ih, io, KeyEvent.VK_8, 8);
testKey(ih, io, KeyEvent.VK_9, 9);
testKey(ih, io, KeyEvent.VK_0, 10);
}
private void testKey(ActionHandler ih, InventoryObject io, int vk1, int placeHolderIndex) {
if (ih.get(vk1) && io.getNbPlaces() > placeHolderIndex - 1) {
io.setSelectedIndex(placeHolderIndex);
}
}
}
| 37.205882 | 95 | 0.693281 |
06c015eeefb361fec893a19dfd0993bb02cfa9b8 | 1,781 | /**************************************************************************
TableViewScrollPosition.java is part of Titanium4j Mobile 3.0. Copyright 2012 Emitrom 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.
**************************************************************************/
package com.emitrom.ti4j.mobile.client.ui.iphone;
/**
* A set of constants for the position value that can be used for the position
* property of {@link com.emitrom.ti4j.mobile.client.ui.TableView} when
* invoking `scrolltoindex`.
*/
public class TableViewScrollPosition {
public static final int BOTTOM = BOTTOM();
public static final int MIDDLE = MIDDLE();
public static final int NONE = NONE();
public static final int TOP = TOP();
private TableViewScrollPosition() {
}
private static native final int BOTTOM() /*-{
return Titanium.UI.iPhone.TableViewScrollPosition.BOTTOM;
}-*/;
private static native final int MIDDLE() /*-{
return Titanium.UI.iPhone.TableViewScrollPosition.MIDDLE;
}-*/;
private static native final int NONE() /*-{
return Titanium.UI.iPhone.TableViewScrollPosition.NONE;
}-*/;
private static native final int TOP() /*-{
return Titanium.UI.iPhone.TableViewScrollPosition.TOP;
}-*/;
}
| 34.921569 | 93 | 0.661426 |
18018b20efae60672b13beb6c9cbd90c71c4d79f | 2,083 | package com.example.android.androidstore;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
/**
*
* Created by omar on 7/3/16.
*/
public class Product {
private String name;
private double price;
private int quantity;
private String supplierName;
private String supplierEmail;
private byte[] image;
/**
* Create a mew product
* @param name product name
* @param price product price
* @param quantity available quantity
* @param supplierName supplier name
* @param supplierEmail supplier email
*/
public Product(String name, double price, int quantity, String supplierName, String supplierEmail, byte[] image) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.supplierName = supplierName;
this.supplierEmail = supplierEmail;
this.image = image;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getQuantity() {
return quantity;
}
public String getSupplierName() {
return supplierName;
}
public String getSupplierEmail() {
return supplierEmail;
}
public byte[] getImage() {
return image;
}
public Bitmap getBitmapImage() {
if (image == null || image.length == 0) {
return null;
}
return BitmapFactory.decodeByteArray(image , 0, image .length);
}
@Override
public String toString() {
return "name: " + name + "\t" + "price: " + "\t" +
"available quantity: " + quantity + "\t" +
"supplier name: " + supplierName + "\t" + "supplier email: " + supplierEmail;
}
public static byte[] encodeBitmap(Bitmap image) {
// Convert Bitmap to byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
}
| 23.942529 | 118 | 0.612578 |
03076948608c6847ef3c3b170654cf1a4f94f346 | 2,166 | package org.example.app.controller;
import java.net.URI;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.example.app.dto.DeviceDTO;
import org.example.app.service.DeviceService;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@RestController
@RequestMapping(value = "/api/devices", produces = MediaType.APPLICATION_JSON_VALUE)
public class DeviceController {
private final DeviceService deviceService;
public DeviceController(final DeviceService deviceService) {
this.deviceService = deviceService;
}
@GetMapping
public ResponseEntity<List<DeviceDTO>> getAllDevices(@RequestParam(name = "gateway_id") Optional<Long> gatewayId) {
return ResponseEntity.ok(deviceService.findAll(gatewayId));
}
@GetMapping("/{id}")
public ResponseEntity<DeviceDTO> getDevice(@PathVariable final Long id) {
return ResponseEntity.ok(deviceService.get(id));
}
@PostMapping
public ResponseEntity<Void> createDevice(@RequestBody @Valid final DeviceDTO deviceDTO) {
MultiValueMap<String, String> headers = new HttpHeaders();
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(deviceService.create(deviceDTO)).toUri();
headers.add(HttpHeaders.LOCATION, location.toString());
return new ResponseEntity<>(headers, HttpStatus.CREATED);
}
@PutMapping("/{id}")
public ResponseEntity<Void> updateDevice(@PathVariable final Long id,
@RequestBody @Valid final DeviceDTO deviceDTO) {
deviceService.update(id, deviceDTO);
return ResponseEntity.ok().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteDevice(@PathVariable final Long id) {
deviceService.delete(id);
return ResponseEntity.noContent().build();
}
}
| 36.1 | 119 | 0.745152 |
5d070fb42dc4515fa74e64fca9dc415c92d08cd9 | 1,509 | /*
* Copyright (C) 2020 The Android 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 com.android.tools.idea.avdmanager;
import com.android.sdklib.internal.avd.AvdInfo;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.project.Project;
import com.intellij.util.messages.Topic;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Listener of AVD launch events.
*/
public interface AvdLaunchListener {
Topic<AvdLaunchListener> TOPIC = new Topic<>("AVD launch events", AvdLaunchListener.class);
/**
* Called when an AVD is launched from Studio.
*
* @param avd the AVD that was launched
* @param commandLine the command line used to start the emulator
* @param project the project on behalf of which the AVD was launched, or null if not applicable
*/
void avdLaunched(@NotNull AvdInfo avd, @NotNull GeneralCommandLine commandLine, @Nullable Project project);
} | 38.692308 | 109 | 0.759443 |
a1ed696c91814b8c5379f416660342f788734c75 | 754 | package org.javaturk.oopj.ch06.assignment;
public class Stack {
// Default maximum stack size
public static final int MAX_STACK_SIZE = 5;
// Put element on the top
public boolean push(String newElement) {
return false;
}
// Pop element from the top
public String pop() {
return null;
}
// Remove all elements from stack
public void clear() {
}
// Stack status operations
// Is stack empty?
public boolean isEmpty() {
return false;
}
// Is stack full?
public boolean isFull() {
return false;
}
// How many elements in stack?
public int size() {
return 0;
}
// Capacity of stack?
public int getCapacity() {
return MAX_STACK_SIZE;
}
// Outputs the elements in the stack
public void showElements() {
}
}
| 14.784314 | 44 | 0.676393 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.