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
|
|---|---|---|---|---|---|
f71619d8d9df902283ba43c26d5ae7bffba1a501
| 1,235
|
package com.st.academy.pomanager.models.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
@Entity
@Getter
@Setter
@Table(name="proveedor")
@SQLDelete(sql = "UPDATE proveedor SET activo = false WHERE id=?")
@Where(clause = "activo=true")
public class Supplier extends BasePersistanceEntity{
@Column(name = "empresa")
private String company;
@Column(name = "contacto")
private String contact;
@Column(name = "direccion")
private String address;
@ManyToMany(mappedBy = "suppliers")
@JsonIgnore
private Set<Category> categories = new HashSet<>();
@OneToMany(mappedBy = "supplier")
@JsonIgnore
private Set<Product> products = new HashSet<>();
}
| 25.204082
| 66
| 0.761943
|
bba114a1ccb8cc2099d9e398ea84ab365462f609
| 8,719
|
/**
* Copyright (c) 2011-2020, JFXtras
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the organization 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 JFXRAS 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 jfxtras.icalendarfx.property.component;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import jfxtras.icalendarfx.components.VEvent;
import jfxtras.icalendarfx.properties.component.recurrence.ExceptionDates;
public class ExceptionDatesTest
{
@Test
public void canParseExceptions1()
{
String content = "EXDATE:20151112T100000,20151115T100000";
ExceptionDates madeProperty = ExceptionDates.parse(LocalDateTime.class, content);
assertEquals(content, madeProperty.toString());
ExceptionDates expectedProperty = new ExceptionDates(LocalDateTime.of(2015, 11, 12, 10, 0), LocalDateTime.of(2015, 11, 15, 10, 0));
assertEquals(expectedProperty, madeProperty);
List<LocalDateTime> expectedValues = new ArrayList<>(Arrays.asList(LocalDateTime.of(2015, 11, 12, 10, 0), LocalDateTime.of(2015, 11, 15, 10, 0)));
List<Temporal> madeValues = madeProperty.getValue().stream().sorted().collect(Collectors.toList());
assertEquals(expectedValues, madeValues);
}
@Test
public void canParseExceptions2()
{
String content = "EXDATE:19960402T010000Z,19960403T010000Z,19960404T010000Z";
ExceptionDates madeProperty = ExceptionDates.parse(content);
assertEquals(content, madeProperty.toString());
Set<Temporal> set = new HashSet<Temporal>( Arrays.asList(
ZonedDateTime.of(LocalDateTime.of(1996, 4, 2, 1, 0), ZoneId.of("Z")),
ZonedDateTime.of(LocalDateTime.of(1996, 4, 3, 1, 0), ZoneId.of("Z")),
ZonedDateTime.of(LocalDateTime.of(1996, 4, 4, 1, 0), ZoneId.of("Z")) ));
ExceptionDates expectedProperty = new ExceptionDates(set);
assertEquals(expectedProperty, madeProperty);
Set<ZonedDateTime> expectedValues = new HashSet<>(Arrays.asList(
ZonedDateTime.of(LocalDateTime.of(1996, 4, 2, 1, 0), ZoneId.of("Z")),
ZonedDateTime.of(LocalDateTime.of(1996, 4, 3, 1, 0), ZoneId.of("Z")),
ZonedDateTime.of(LocalDateTime.of(1996, 4, 4, 1, 0), ZoneId.of("Z")) ));
assertEquals(expectedValues, madeProperty.getValue());
set.add(ZonedDateTime.of(LocalDateTime.of(1996, 4, 5, 1, 0), ZoneId.of("Z")));
assertEquals(4, expectedProperty.getValue().size());
}
@Test
public void canParseExceptions3()
{
String content = "EXDATE;VALUE=DATE:20160402";
ExceptionDates madeProperty = ExceptionDates.parse(LocalDate.class, content);
assertEquals(content, madeProperty.toString());
ExceptionDates expectedProperty = new ExceptionDates(
LocalDate.of(2016, 4, 2) );
assertEquals(expectedProperty, madeProperty);
Set<LocalDate> expectedValues = new HashSet<>(Arrays.asList( LocalDate.of(2016, 4, 2) ));
assertEquals(expectedValues, madeProperty.getValue());
}
@Test
public void canCatchWrongTypeExceptions1()
{
ExceptionDates e = ExceptionDates.parse("20160228T093000");
e.getValue().add(LocalDateTime.of(2016, 4, 25, 1, 0));
e.getValue().add(LocalDate.of(2016, 4, 25));
assertEquals(1, e.errors().size());
String expectedError = "Recurrences DateTimeType \"DATE\" doesn't match previous recurrences DateTimeType \"DATE_WITH_LOCAL_TIME\"";
assertEquals(expectedError, e.errors().get(0));
}
@Test
public void canCatchWrongTypeInTwoProperty()
{
VEvent v = new VEvent().withExceptionDates(LocalDate.of(2016, 4, 27));
v.setSummary("here:");
ExceptionDates e2 = new ExceptionDates(LocalDateTime.of(2016, 4, 27, 12, 0));
v.getExceptionDates().add(e2);
v.orderChild(e2);
}
@Test
public void canCatchWrongTypeInProperty()
{
ExceptionDates e = ExceptionDates.parse("20160228T093000");
e.getValue().add(LocalDateTime.of(2016, 4, 25, 1, 0));
e.getValue().add(LocalDate.of(2016, 4, 25));
assertEquals(1, e.errors().size());
String expectedMessage = "Recurrences DateTimeType \"DATE\" doesn't match previous recurrences DateTimeType \"DATE_WITH_LOCAL_TIME\"";
assertEquals(expectedMessage, e.errors().get(0));
}
@Test
public void canCatchWrongTimeZone()
{
ExceptionDates e = new ExceptionDates();
e.setValue(new LinkedHashSet<>(Arrays.asList(ZonedDateTime.of(LocalDateTime.of(1996, 4, 2, 1, 0), ZoneId.of("America/Los_Angeles")))));
e.getValue().add(ZonedDateTime.of(LocalDateTime.of(1996, 4, 4, 1, 0), ZoneId.of("America/Los_Angeles")));
e.getValue().add(ZonedDateTime.of(LocalDateTime.of(1996, 4, 5, 1, 0), ZoneId.of("America/New_York")));
assertEquals(1, e.errors().size());
String expectedMessage = "ZoneId \"America/New_York\" doesn't match previous ZoneId \"America/Los_Angeles\"";
assertEquals(expectedMessage, e.errors().get(0));
}
@Test (expected = DateTimeException.class)
public void canCatchWrongExceptionTypeInComponent()
{
VEvent e = new VEvent().withExceptionDates(LocalDate.of(2016, 4, 27),
LocalDateTime.of(2016, 4, 27, 12, 0));
}
@Test
public void canCopyExceptions()
{
String content = "EXDATE:19960402T010000Z,19960403T010000Z,19960404T010000Z";
ExceptionDates property1 = ExceptionDates.parse(content);
ExceptionDates property2 = new ExceptionDates(property1);
assertEquals(property1, property2);
assertFalse(property1 == property2);
assertFalse(property1.getValue() == property2.getValue());
}
@Test
public void canCopyExceptions2()
{
String content = "EXDATE:19960402T010000Z,19960403T010000Z,19960404T010000Z";
ExceptionDates property1 = ExceptionDates.parse(content);
ExceptionDates property2 = new ExceptionDates(property1);
assertEquals(property1, property2);
assertFalse(property1 == property2);
assertFalse(property1.getValue() == property2.getValue());
// make sure wrapped collection is different
Temporal first = property1.getValue().iterator().next();
property1.getValue().remove(first);
assertEquals(2, property1.getValue().size());
assertEquals(3, property2.getValue().size());
}
@Test
public void canCopyEmptyExceptions()
{
ExceptionDates property1 = new ExceptionDates();
ExceptionDates property2 = new ExceptionDates(property1);
assertEquals(property1, property2);
assertFalse(property1 == property2);
assertFalse(property1.getValue() == property2.getValue());
}
}
| 45.176166
| 154
| 0.686661
|
8bbe0cb5956261e6613c962e0f9fce64700c7289
| 1,238
|
package com.caleb.algorithm.dynamicprogramming;
/**
* @author:hanzhigang
* @Date : 2021/3/23 11:47 PM
*/
public class UniquePathII63 {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
// 定义状态数组
int[][] dp = new int[obstacleGrid.length][obstacleGrid[0].length];
// 将第一行和第一列置为1,有障碍的话后面的为0
for (int i = 0; i < dp.length; i++) {
if (obstacleGrid[i][0] == 1) {
break;
}else{
dp[i][0] = 1;
}
}
for (int j = 0; j < dp[0].length; j++) {
if (obstacleGrid[0][j] == 1) {
break;
}else{
dp[0][j] = 1;
}
}
// 依次遍历路径,只计算不存在障碍物的地方,存在障碍物的地方为0
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (obstacleGrid[i][j] != 1) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
// 返回结果
return dp[dp.length-1][dp[0].length-1];
}
/**
* 利用滚动数组来做,空间复杂度也降低
* @param obstacleGrid
* @return
*/
public int uniquePathsWithObstacles1(int[][] obstacleGrid) {
return 0;
}
}
| 26.340426
| 74
| 0.439418
|
221799b4fe7d7d61cc1ff7d03cafdd95aafdfcbe
| 8,836
|
package for_camera_opmodes;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import org.firstinspires.ftc.robotcontroller.internal.FtcRobotControllerActivity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* TeleOp Mode
* <p/>
* Enables control of the robot via the gamepad
*/
public class LinearOpModeCamera extends LinearOpMode {
public Camera camera;
public CameraPreview preview;
public int width;
public int height;
public YuvImage yuvImage = null;
volatile private boolean imageReady = false;
private int looped = 0;
private String data;
private int ds = 1; // downsampling parameter
@Override
// should be overwritten by extension class
public void runOpMode() throws InterruptedException {
}
public Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
public void onPreviewFrame(byte[] data, Camera camera) {
try {
Camera.Parameters parameters = camera.getParameters();
width = parameters.getPreviewSize().width;
height = parameters.getPreviewSize().height;
yuvImage = new YuvImage(data, ImageFormat.NV21, width, height, null);
imageReady = true;
looped += 1;
} catch (Exception e) {
}
}
};
public void setCameraDownsampling(int downSampling) {
ds = downSampling;
}
public boolean imageReady() {
return imageReady;
}
public boolean isCameraAvailable() {
int cameraId = -1;
Camera cam = null;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { // Camera.CameraInfo.CAMERA_FACING_FRONT or BACK
cameraId = i;
break;
}
}
try {
cam = Camera.open(cameraId);
} catch (Exception e) {
Log.e("Error", "Camera Not Available!");
return false;
}
cam.release();
cam = null;
return true;
}
public Camera openCamera(int cameraInfoType) {
int cameraId = -1;
Camera cam = null;
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == cameraInfoType) { // Camera.CameraInfo.CAMERA_FACING_FRONT or BACK
cameraId = i;
break;
}
}
try {
cam = Camera.open(cameraId);
} catch (Exception e) {
Log.e("Error", "Can't Open Camera");
}
return cam;
}
public void startCamera() {
camera = openCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);
camera.setPreviewCallback(previewCallback);
Camera.Parameters parameters = camera.getParameters();
width = parameters.getPreviewSize().width / ds;
height = parameters.getPreviewSize().height / ds;
parameters.setPreviewSize(width, height);
camera.setParameters(parameters);
data = parameters.flatten();
if (preview == null) {
((FtcRobotControllerActivity) hardwareMap.appContext).initPreviewLinear(camera, this, previewCallback);
}
}
public void stopCameraInSecs(int duration) {
Thread cameraKillThread = new Thread(new CameraKillThread(duration));
cameraKillThread.start();
}
public class CameraKillThread implements Runnable {
int dur;
public CameraKillThread(int duration) {
dur = duration;
}
public void run() {
try {
Thread.sleep(dur * 1000, 0);
} catch (InterruptedException ex) {
}
stopCamera();
imageReady = false;
}
}
public void stopCamera() {
if (camera != null) {
if (preview != null) {
((FtcRobotControllerActivity) hardwareMap.appContext).removePreviewLinear(this);
preview = null;
}
camera.stopPreview();
camera.setPreviewCallback(null);
if (camera != null) {
camera.release();
}
camera = null;
}
}
static public int red(int pixel) {
return (pixel >> 16) & 0xff;
}
static public int green(int pixel) {
return (pixel >> 8) & 0xff;
}
static public int blue(int pixel) {
return pixel & 0xff;
}
static public int gray(int pixel) {
return (red(pixel) + green(pixel) + blue(pixel));
}
static public int highestColor(int red, int green, int blue) {
int[] color = {red, green, blue};
int value = 0;
for (int i = 1; i < 3; i++) {
if (color[value] < color[i]) {
value = i;
}
}
return value;
}
// returns ROTATED image, to match preview window
static public Bitmap convertYuvImageToRgb(YuvImage yuvImage, int width, int height, int downSample) {
return OpModeCamera.convertYuvImageToRgb(yuvImage, width, height, downSample);
}
public int normalizePixels(int value) {
value /= 100000;
return value;
}
public void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
SimpleDateFormat s = new SimpleDateFormat("dd MM yyyy hhmmss");
String format = s.format(new Date());
String fname = format +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
public void SaveRGB (Bitmap colorBitmap)
{
String pixelColorMap = "";
String rtemp;
String gtemp;
String btemp;
String xv;
String yv;
int pixelPlaceholder;
int Rtemp;
int Gtemp;
int Btemp;
for(int y = 0; y < 640; y++)
{
for(int x = 0; x < 480; x++)
{
pixelPlaceholder = colorBitmap.getPixel(x,y);
xv = Integer.toString(x);
yv = Integer.toString(y);
Rtemp = red(pixelPlaceholder);
rtemp = Integer.toString(Rtemp);
Gtemp = green(pixelPlaceholder);
gtemp = Integer.toString(Gtemp);
Btemp = blue(pixelPlaceholder);
btemp = Integer.toString(Btemp);
pixelColorMap = pixelColorMap + x + "," + y + " - ";
pixelColorMap = pixelColorMap + rtemp + ",";
pixelColorMap = pixelColorMap + gtemp + ",";
pixelColorMap = pixelColorMap + btemp + System.getProperty("line.separator");
}
}
/*String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());
String fname = format +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
PrintStream out = new PrintStream(new FileOutputStream("filename.txt")))
{
out.print(pixelColorMap);}
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
| 29.551839
| 120
| 0.585559
|
ef22e1913adf6fe1a95f1ab273dfe19ca532c909
| 2,807
|
package reseau.ressources;
import interfaces.ContaineurImageOp;
import io.IO;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import ressources.RessourcesLoader;
public class RessourceImage extends RessourceReseau<BufferedImage> implements ContaineurImageOp {
private Map<Integer, BufferedImage> variantes;
private BufferedImage image;
private IO data;
public RessourceImage(int id, BufferedImage image) {
super(id);
this.image = image;
}
public RessourceImage(IO io) {
super(io);
image = getImage(io);
}
public void setImage(BufferedImage image) {
this.image = image;
data = null;
variantes = null;
}
@Override
public BufferedImage getImage(int teinte, int opacite) {
if(variantes == null)
variantes = new HashMap<Integer, BufferedImage>();
int clef = teinte * 101 + opacite;
BufferedImage img = variantes.get(teinte * 100 + opacite);
if(img == null) {
img = getOp(image, teinte, opacite);
variantes.put(clef, img);
}
return img;
}
@Override
public BufferedImage getImage() {
return image;
}
@Override
public TypeRessource getType() {
return TypeRessource.IMAGE;
}
@Override
public void ecrireDonnees(IO io) {
if(data == null)
data = getIO(image);
io.add(data);
}
@Override
public BufferedImage getRessource() {
return getImage();
}
@Override
public void affecteRessource(BufferedImage ressource) {
setImage(ressource);
}
public static IO getIO(BufferedImage img) {
return ecrire(new IO((2 + img.getWidth() * img.getHeight()) * 4), img);
}
public static BufferedImage getOp(BufferedImage image, int teinte, int opacite) {
BufferedImage img = RessourcesLoader.creerImage(image.getWidth(), image.getHeight());
Graphics2D g = img.createGraphics();
g.drawImage(image, 0, 0, null);
g.setColor(new Color(teinte, teinte, teinte, opacite));
g.setComposite(AlphaComposite.SrcAtop);
g.fillRect(0, 0, img.getWidth(), img.getHeight());
g.dispose();
return img;
}
public static IO ecrire(IO io, BufferedImage img) {
io.addShort(img.getWidth()).addShort(img.getHeight());
for(int x=0 ; x<img.getWidth() ; x++)
for(int y=0 ; y<img.getHeight() ; y++)
io.add(img.getRGB(x, y));
return io;
}
public static BufferedImage getImage(IO io) {
BufferedImage img = new BufferedImage(io.nextShortInt(), io.nextShortInt(), BufferedImage.TYPE_INT_ARGB);
for(int x=0 ; x<img.getWidth() ; x++)
for(int y=0 ; y<img.getHeight() ; y++)
img.setRGB(x, y, io.nextInt());
return img;
}
}
| 25.752294
| 107
| 0.659423
|
8808b30d564f746ec9a5df0c2e2ece89362760a9
| 31,945
|
/*
* Copyright 2019 Equipment & Tool Institute
*/
package org.etools.j1939_84.ui;
import static org.etools.j1939_84.J1939_84.isAutoMode;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.util.concurrent.Executor;
import java.util.logging.Level;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.DefaultCaret;
import org.etools.j1939_84.BuildNumber;
import org.etools.j1939_84.J1939_84;
import org.etools.j1939_84.controllers.QuestionListener;
import org.etools.j1939_84.model.VehicleInformationListener;
import org.etools.j1939_84.resources.Resources;
import org.etools.j1939_84.ui.UserInterfaceContract.Presenter;
import org.etools.j1939_84.ui.widgets.SmartScroller;
import net.soliddesign.j1939tools.bus.Adapter;
import net.soliddesign.j1939tools.j1939.J1939;
/**
* The View for the User Interface.
* <p>
* NOTE: Logic is not present in the class as it will be difficult to unit test.
*
* @author Matt Gumbel (matt@soliddesign.net)
*/
public class UserInterfaceView implements UserInterfaceContract.View {
private static final String SELECT_FILE = "Select File...";
private final BuildNumber buildNumber;
/**
* The controller for the behavior of this view
*/
private final Presenter controller;
private final Executor swingExecutor;
private JButton abortButton;
private JComboBox<Adapter> adapterComboBox;
private JComboBox<String> speedComboBox;
private JLabel calsLabel;
private JScrollPane calsScrollPane;
private JTextArea calsTextField;
private JFileChooser fileChooser;
private JLabel fileLabel;
private JFrame frame;
private JButton helpButton;
private JProgressBar progressBar;
private JButton readVehicleInfoButton;
private JPanel reportControlPanel;
private JScrollPane reportScrollPane;
private JPanel reportSetupPanel;
private JTextArea reportTextArea;
private JButton selectFileButton;
private JSplitPane splitPane;
private JButton startButton;
private JPanel topPanel;
private JPanel vehicleInfoPanel;
private JLabel vinLabel;
private JTextField vinTextField;
private File file = null; // For the auto mode
/**
* Default Constructor
*
* @wbp.parser.entryPoint
*/
public UserInterfaceView() {
swingExecutor = SwingUtilities::invokeLater;
controller = new UserInterfacePresenter(this);
buildNumber = new BuildNumber();
initialize();
}
/**
* Constructor exposed for testing
*
* @param controller
* The {@link UserInterfacePresenter} that will control the UI
* @param buildNumber
* The {@link BuildNumber} that will return the build number
* @param swingExecutor
* The {@link Executor} used to make updates to the UI on the
* Swing Thread
*/
UserInterfaceView(Presenter controller, BuildNumber buildNumber, Executor swingExecutor) {
this.controller = controller;
this.buildNumber = buildNumber;
this.swingExecutor = swingExecutor;
initialize();
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#appendResults(java.lang.
* String)
*/
@Override
public void appendResults(String result) {
refreshUI(() -> getReportTextArea().append(result));
}
@Override
public void displayDialog(String message, String title, int type, boolean modal) {
displayDialog(message, title, type, modal, null);
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#displayDialog(java.lang.
* String, java.lang.String, int)
*/
@Override
public void displayDialog(String message,
String title,
int type,
boolean modal,
QuestionListener questionListener) {
if (modal) {
try {
SwingUtilities.invokeAndWait(() -> {
int result = JOptionPane.showOptionDialog(null, message, title, type, type, null, null, null);
if (questionListener != null) {
questionListener.answered(QuestionListener.AnswerType.getType(result));
}
});
} catch (InvocationTargetException | InterruptedException e) {
J1939_84.getLogger().log(Level.SEVERE, "Error displaying dialog", e);
}
} else {
refreshUI(() -> JOptionPane.showMessageDialog(getFrame(), message, title, type));
}
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#displayFileChooser()
*/
@Override
public void displayFileChooser() {
refreshUI(() -> {
int result = getFileChooser().showDialog(getFrame(), "Use File");
if (result == JFileChooser.APPROVE_OPTION) {
getController().onFileChosen(getFileChooser().getSelectedFile());
}
});
}
@Override
public void displayForm(VehicleInformationListener listener, J1939 j1939) {
SwingUtilities.invokeLater(() -> new VehicleInformationDialog(getFrame(), listener, j1939).setVisible(true));
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#setAdapterComboBoxEnabled(
* boolean)
*/
@Override
public void setAdapterComboBoxEnabled(boolean enabled) {
refreshUI(() -> {
getAdapterComboBox().setEnabled(enabled);
getSpeedComboBox().setEnabled(enabled);
});
}
private JComboBox<String> getSpeedComboBox() {
if (speedComboBox == null) {
speedComboBox = new JComboBox<>();
speedComboBox.setEditable(true);
speedComboBox.setToolTipText("RP1210 Communications Speed");
speedComboBox.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
getController().onAdapterComboBoxItemSelected(getAdapterComboBox().getItemAt(getAdapterComboBox().getSelectedIndex()),
speedComboBox.getItemAt(speedComboBox.getSelectedIndex()));
}
});
}
return speedComboBox;
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#setEngines(java.lang.
* String)
*/
@Override
public void setEngineCals(String text) {
refreshUI(() -> {
getCalsTextField().setText(text);
getCalsTextField().setCaretPosition(0);
});
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#
* setProgressBarText(String)
*/
@Override
public void setProgressBarText(String text) {
refreshUI(() -> getProgressBar().setString(text));
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#setProgressBarValue(int,
* int, int)
*/
@Override
public void setProgressBarValue(int min, int max, int value) {
refreshUI(() -> {
getProgressBar().setMinimum(min);
getProgressBar().setMaximum(max);
getProgressBar().setValue(value);
});
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#
* setReadVehicleInfoButtonEnabled(boolean)
*/
@Override
public void setReadVehicleInfoButtonEnabled(boolean enabled) {
refreshUI(() -> {
getReadVehicleInfoButton().setEnabled(enabled);
getReadVehicleInfoButton().requestFocus();
if (isAutoMode() && enabled && getVinTextField().getText().isEmpty()) {
controller.onReadVehicleInfoButtonClicked();
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.etools.j1939_84.ui.IUserInterfaceView#setSelectFileButtonEnabled(
* boolean)
*/
@Override
public void setSelectFileButtonEnabled(boolean enabled) {
refreshUI(() -> {
getSelectFileButton().setEnabled(enabled);
getSelectFileButton().requestFocus();
if (isAutoMode() && enabled && file == null) {
var dir = new File("reports");
if (!dir.exists() && !dir.mkdir()) {
return;
}
file = new File(dir, LocalDateTime.now().toString());
controller.onFileChosen(file);
}
});
}
/*
* (non-Javadoc)
*
* @see
* org.etools.j1939_84.ui.IUserInterfaceView#setSelectFileButtonText(java.
* lang.String)
*/
@Override
public void setSelectFileButtonText(String text) {
refreshUI(() -> getSelectFileButton().setText(text == null ? SELECT_FILE : text));
}
@Override
public void setStartButtonEnabled(boolean enabled) {
getStartButton().setEnabled(enabled);
getStartButton().requestFocus();
if (isAutoMode() && enabled) {
refreshUI(() -> getController().onStartButtonClicked());
}
}
@Override
public void setStopButtonEnabled(boolean enabled) {
refreshUI(() -> getStopButton().setEnabled(enabled));
}
/*
* (non-Javadoc)
*
* @see org.etools.j1939_84.ui.IUserInterfaceView#setVin(java.lang.String)
*/
@Override
public void setVin(String vin) {
refreshUI(() -> getVinTextField().setText(vin));
}
/**
* Creates, caches and returns the Adapter Combo Box Selector
*
* @return JComboBox
*/
JComboBox<Adapter> getAdapterComboBox() {
if (adapterComboBox == null) {
adapterComboBox = new JComboBox<>();
for (Adapter adapter : getController().getAdapters()) {
adapterComboBox.addItem(adapter);
}
adapterComboBox.setToolTipText("RP1210 Communications Adapter");
adapterComboBox.setSelectedIndex(-1);
if (isAutoMode()) {
adapterComboBox.setSelectedIndex(0);
getController().onAdapterComboBoxItemSelected(adapterComboBox.getItemAt(0),
getSpeedComboBox().getItemAt(getSpeedComboBox().getSelectedIndex()));
}
adapterComboBox.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
getSpeedComboBox().removeAllItems();
((Adapter) e.getItem()).getConnectionStrings().forEach(s -> getSpeedComboBox().addItem(s));
getSpeedComboBox().setSelectedItem("J1939:Baud=Auto");
}
});
}
return adapterComboBox;
}
/**
* Returns the {@link BuildNumber} that reads the version number
*
* @return the instance of the {@link BuildNumber}
*/
private BuildNumber getBuildNumber() {
return buildNumber;
}
/**
* Creates, caches and returns the label for the Engine Calibrations Text
* Field
*
* @return JLabel
*/
private JLabel getCalsLabel() {
if (calsLabel == null) {
calsLabel = new JLabel("<html>Cal<br>IDs:</html>", SwingConstants.CENTER);
calsLabel.setHorizontalTextPosition(SwingConstants.CENTER);
calsLabel.setToolTipText("Engine Calibrations");
}
return calsLabel;
}
/**
* Creates, caches and returns the scroll pane that contains the Report Text
* Area
*
* @return JScrollPane
*/
private JScrollPane getCalsScrollPane() {
if (calsScrollPane == null) {
calsScrollPane = new JScrollPane(getCalsTextField());
calsScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
calsScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
Dimension dimension = new Dimension(200, 100);
calsScrollPane.setPreferredSize(dimension);
calsScrollPane.setMinimumSize(dimension);
}
return calsScrollPane;
}
/**
* Creates, caches and returns the Engine Calibrations Text Field
*
* @return JTextArea
*/
JTextArea getCalsTextField() {
if (calsTextField == null) {
calsTextField = new JTextArea();
calsTextField.setEditable(false);
calsTextField.setToolTipText("Engine Calibrations");
}
return calsTextField;
}
/**
* Returns the {@link UserInterfacePresenter} that controls the view
*
* @return the {@link UserInterfacePresenter}
*/
private Presenter getController() {
return controller;
}
/**
* Creates, caches and returns the File Chooser
*
* @return JFileChooser
*/
JFileChooser getFileChooser() {
if (fileChooser == null) {
final String KEY = "directory";
String dir = Preferences.userNodeForPackage(getClass()).get(KEY, "");
fileChooser = new JFileChooser(dir);
FileNameExtensionFilter filter = new FileNameExtensionFilter("J1939-84 Data Files",
UserInterfacePresenter.FILE_SUFFIX);
fileChooser.setFileFilter(filter);
fileChooser.setDialogTitle("Create Report File");
fileChooser.addActionListener(
e -> {
File file = fileChooser.getSelectedFile();
if (file != null) {
Preferences.userNodeForPackage(getClass())
.put(KEY,
file.getParent());
}
});
}
return fileChooser;
}
/**
* Returns the main frame that contains the user interface
*
* @return JFrame
*/
public JFrame getFrame() {
if (frame == null) {
frame = new JFrame();
frame.setTitle("J1939-84 Tool v" + getBuildNumber().getVersionNumber());
int hundred = (int) (100 * Toolkit.getDefaultToolkit().getScreenResolution() / 72.0);
frame.setBounds(hundred, hundred, 5 * hundred, 5 * hundred);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setIconImages(Resources.getLogoImages());
}
return frame;
}
/**
* Creates, caches and returns the Help Button
*
* @return JButton
*/
JButton getHelpButton() {
if (helpButton == null) {
helpButton = new JButton("Help");
helpButton.addActionListener(e -> getController().onHelpButtonClicked());
}
return helpButton;
}
/**
* Creates, caches and returns the Progress Bar
*
* @return JProgressBar
*/
JProgressBar getProgressBar() {
if (progressBar == null) {
progressBar = new JProgressBar();
progressBar.setStringPainted(true);
progressBar.setString("Select Vehicle Adapter");
}
return progressBar;
}
JButton getReadVehicleInfoButton() {
if (readVehicleInfoButton == null) {
readVehicleInfoButton = new JButton(
"<html><center>Read</center><center>Vehicle</center><center>Info</center><html>");
readVehicleInfoButton.setToolTipText("Queries the vehicle for VIN and Calibrations");
readVehicleInfoButton.setEnabled(false);
readVehicleInfoButton.setHorizontalAlignment(SwingConstants.CENTER);
readVehicleInfoButton.setHorizontalTextPosition(SwingConstants.CENTER);
readVehicleInfoButton.addActionListener(e -> getController().onReadVehicleInfoButtonClicked());
}
return readVehicleInfoButton;
}
/**
* Creates, caches and returns the Panel that contains the Report Controls
*
* @return JPanel
*/
private JPanel getReportControlPanel() {
if (reportControlPanel == null) {
reportControlPanel = new JPanel();
reportControlPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] { 0, 0 };
layout.rowHeights = new int[] { 0, 0 };
layout.columnWeights = new double[] { 1.0, 1.0 };
layout.rowWeights = new double[] { 1.0, 1.0 };
reportControlPanel.setLayout(layout);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.insets = new Insets(5, 5, 5, 5);
gbc1.fill = GridBagConstraints.BOTH;
gbc1.gridx = 0;
gbc1.gridy = 0;
reportControlPanel.add(getStartButton(), gbc1);
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.insets = new Insets(5, 0, 5, 5);
gbc2.fill = GridBagConstraints.BOTH;
gbc2.gridx = 1;
gbc2.gridy = 0;
reportControlPanel.add(getStopButton(), gbc2);
}
return reportControlPanel;
}
/**
* Creates, caches and returns the scroll pane that contains the Report Text
* Area
*
* @return JScrollPane
*/
private JScrollPane getReportScrollPane() {
if (reportScrollPane == null) {
reportScrollPane = new JScrollPane(getReportTextArea());
reportScrollPane.setMinimumSize(new Dimension(500, 100));
reportScrollPane.setPreferredSize(new Dimension(500, 100));
new SmartScroller(reportScrollPane, SmartScroller.VERTICAL, SmartScroller.END);
reportScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
reportScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
return reportScrollPane;
}
/**
* Creates, caches and returns the Panel that contains the controls to setup
* the report
*
* @return JPanel
*/
private JPanel getReportSetupPanel() {
if (reportSetupPanel == null) {
reportSetupPanel = new JPanel();
reportSetupPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] { 0, 0, 0 };
layout.rowHeights = new int[] { 0, 0 };
layout.columnWeights = new double[] { 0.0, Double.MIN_VALUE, Double.MIN_VALUE, 0.0 };
layout.rowWeights = new double[] { 0, 0 };
reportSetupPanel.setLayout(layout);
GridBagConstraints adapterLabelGbc = new GridBagConstraints();
adapterLabelGbc.insets = new Insets(5, 5, 5, 5);
adapterLabelGbc.anchor = GridBagConstraints.EAST;
adapterLabelGbc.gridx = 0;
adapterLabelGbc.gridy = 0;
reportSetupPanel.add(new JLabel("Vehicle Adapter:"), adapterLabelGbc);
GridBagConstraints comboBoxGbc = new GridBagConstraints();
comboBoxGbc.insets = new Insets(5, 0, 5, 5);
comboBoxGbc.anchor = GridBagConstraints.WEST;
comboBoxGbc.gridx = 1;
comboBoxGbc.gridy = 0;
reportSetupPanel.add(getAdapterComboBox(), comboBoxGbc);
GridBagConstraints speedBoxGbc = new GridBagConstraints();
speedBoxGbc.insets = new Insets(5, 5, 5, 5);
speedBoxGbc.anchor = GridBagConstraints.WEST;
speedBoxGbc.gridx = 2;
speedBoxGbc.gridy = 0;
reportSetupPanel.add(getSpeedComboBox(), speedBoxGbc);
GridBagConstraints fileLabelGbc = new GridBagConstraints();
fileLabelGbc.insets = new Insets(0, 5, 5, 5);
fileLabelGbc.anchor = GridBagConstraints.EAST;
fileLabelGbc.gridx = 0;
fileLabelGbc.gridy = 1;
reportSetupPanel.add(getSelectFileLabel(), fileLabelGbc);
GridBagConstraints fileButtonGbc = new GridBagConstraints();
fileButtonGbc.insets = new Insets(0, 0, 5, 5);
fileButtonGbc.anchor = GridBagConstraints.WEST;
fileButtonGbc.gridx = 1;
fileButtonGbc.gridy = 1;
fileButtonGbc.gridwidth = 2;
reportSetupPanel.add(getSelectFileButton(), fileButtonGbc);
GridBagConstraints helpButtonGbc = new GridBagConstraints();
helpButtonGbc.insets = new Insets(5, 0, 5, 5);
helpButtonGbc.anchor = GridBagConstraints.WEST;
helpButtonGbc.gridx = 3;
helpButtonGbc.gridy = 0;
helpButtonGbc.gridheight = 2;
helpButtonGbc.fill = GridBagConstraints.BOTH;
reportSetupPanel.add(getHelpButton(), helpButtonGbc);
}
return reportSetupPanel;
}
/**
* Creates, caches and returns the Text Area that displays the report
*
* @return JTextArea
*/
JTextArea getReportTextArea() {
if (reportTextArea == null) {
reportTextArea = new JTextArea(0, 80);
reportTextArea.setFont(new Font("Courier", Font.PLAIN, reportTextArea.getFont().getSize()));
reportTextArea.setEditable(false);
reportTextArea.setLineWrap(false);
DefaultCaret caret = (DefaultCaret) reportTextArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.UPDATE_WHEN_ON_EDT);
}
return reportTextArea;
}
/**
* Creates, caches and returns the Select File Button
*
* @return JButton
*/
JButton getSelectFileButton() {
if (selectFileButton == null) {
selectFileButton = new JButton(SELECT_FILE);
selectFileButton.setToolTipText("Select or create the file for the report");
selectFileButton.addActionListener(event -> getController().onSelectFileButtonClicked());
selectFileButton.setEnabled(false);
}
return selectFileButton;
}
/**
* Creates, caches and returns the label for the Select File Button
*
* @return JLabel
*/
private JLabel getSelectFileLabel() {
if (fileLabel == null) {
fileLabel = new JLabel("Report File:");
}
return fileLabel;
}
private JSplitPane getSplitPane() {
if (splitPane == null) {
splitPane = new JSplitPane();
splitPane.setContinuousLayout(true);
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
splitPane.setTopComponent(getTopPanel());
splitPane.setBottomComponent(getReportScrollPane());
splitPane.setBorder(BorderFactory.createEmptyBorder());
}
return splitPane;
}
/**
* Creates, caches and returns the Start Button
*
* @return JButton
*/
JButton getStartButton() {
if (startButton == null) {
startButton = new JButton("Start");
startButton.setEnabled(false);
startButton.addActionListener(e -> controller.onStartButtonClicked());
}
return startButton;
}
/**
* Creates, caches and returns the Stop Button
*
* @return JButton
*/
JButton getStopButton() {
if (abortButton == null) {
abortButton = new JButton("Cancel");
abortButton.setEnabled(false);
abortButton.addActionListener(e -> getController().onStopButtonClicked());
}
return abortButton;
}
private JPanel getTopPanel() {
if (topPanel == null) {
topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder());
GridBagLayout layout = new GridBagLayout();
layout.columnWidths = new int[] { 0, 0 };
layout.rowHeights = new int[] { 0, 0, 0, 0, };
layout.columnWeights = new double[] { 1.0, 1.0 };
layout.rowWeights = new double[] { 0.0, 0.0, Double.MIN_VALUE, 0.0 };
topPanel.setLayout(layout);
GridBagConstraints reportSetupPanelGbc = new GridBagConstraints();
reportSetupPanelGbc.insets = new Insets(5, 5, 5, 5);
reportSetupPanelGbc.fill = GridBagConstraints.BOTH;
reportSetupPanelGbc.anchor = GridBagConstraints.WEST;
reportSetupPanelGbc.gridheight = 1;
reportSetupPanelGbc.gridwidth = 2;
reportSetupPanelGbc.gridx = 0;
reportSetupPanelGbc.gridy = 0;
topPanel.add(getReportSetupPanel(), reportSetupPanelGbc);
GridBagConstraints vehicleInfoPanelGbc = new GridBagConstraints();
vehicleInfoPanelGbc.insets = new Insets(0, 5, 5, 5);
vehicleInfoPanelGbc.fill = GridBagConstraints.BOTH;
vehicleInfoPanelGbc.anchor = GridBagConstraints.WEST;
vehicleInfoPanelGbc.gridwidth = 2;
vehicleInfoPanelGbc.gridx = 0;
vehicleInfoPanelGbc.gridy = 1;
vehicleInfoPanelGbc.weighty = 1;
topPanel.add(getVehicleInfoPanel(), vehicleInfoPanelGbc);
GridBagConstraints reportControlPanelGbc = new GridBagConstraints();
reportControlPanelGbc.insets = new Insets(0, 5, 5, 5);
reportControlPanelGbc.fill = GridBagConstraints.BOTH;
reportControlPanelGbc.anchor = GridBagConstraints.WEST;
reportControlPanelGbc.gridheight = 1;
reportControlPanelGbc.gridwidth = 2;
reportControlPanelGbc.gridx = 0;
reportControlPanelGbc.gridy = 2;
reportControlPanelGbc.weighty = 1;
topPanel.add(getReportControlPanel(), reportControlPanelGbc);
GridBagConstraints progressBarGbc = new GridBagConstraints();
progressBarGbc.insets = new Insets(0, 5, 5, 5);
progressBarGbc.fill = GridBagConstraints.BOTH;
progressBarGbc.gridx = 0;
progressBarGbc.gridy = 3;
progressBarGbc.gridwidth = 2;
topPanel.add(getProgressBar(), progressBarGbc);
}
return topPanel;
}
/**
* Creates, caches and returns the Panel that contains the information about
* the vehicle
*
* @return JPanel
*/
private JPanel getVehicleInfoPanel() {
if (vehicleInfoPanel == null) {
vehicleInfoPanel = new JPanel();
vehicleInfoPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
GridBagLayout panelLayout = new GridBagLayout();
panelLayout.columnWidths = new int[] { 0, 0, 0 };
panelLayout.rowHeights = new int[] { 0, 30 };
panelLayout.columnWeights = new double[] { 0.0, Double.MIN_VALUE, 0.0 };
panelLayout.rowWeights = new double[] { 0.0, 1.0 };
vehicleInfoPanel.setLayout(panelLayout);
GridBagConstraints vinLabelGbc = new GridBagConstraints();
vinLabelGbc.insets = new Insets(5, 5, 5, 5);
vinLabelGbc.anchor = GridBagConstraints.EAST;
vinLabelGbc.gridx = 0;
vinLabelGbc.gridy = 0;
vehicleInfoPanel.add(getVinLabel(), vinLabelGbc);
GridBagConstraints vinTextFieldGbc = new GridBagConstraints();
vinTextFieldGbc.insets = new Insets(5, 0, 5, 5);
vinTextFieldGbc.anchor = GridBagConstraints.WEST;
vinTextFieldGbc.fill = GridBagConstraints.BOTH;
vinTextFieldGbc.gridx = 1;
vinTextFieldGbc.gridy = 0;
vehicleInfoPanel.add(getVinTextField(), vinTextFieldGbc);
GridBagConstraints calsLabelGbc = new GridBagConstraints();
calsLabelGbc.insets = new Insets(0, 5, 5, 5);
calsLabelGbc.fill = GridBagConstraints.BOTH;
calsLabelGbc.anchor = GridBagConstraints.EAST;
calsLabelGbc.gridx = 0;
calsLabelGbc.gridy = 1;
vehicleInfoPanel.add(getCalsLabel(), calsLabelGbc);
GridBagConstraints calsTextFieldGbc = new GridBagConstraints();
calsTextFieldGbc.insets = new Insets(0, 0, 5, 5);
calsTextFieldGbc.anchor = GridBagConstraints.WEST;
calsTextFieldGbc.fill = GridBagConstraints.BOTH;
calsTextFieldGbc.gridx = 1;
calsTextFieldGbc.gridy = 1;
vehicleInfoPanel.add(getCalsScrollPane(), calsTextFieldGbc);
GridBagConstraints readVehicleInfoButtonGbc = new GridBagConstraints();
readVehicleInfoButtonGbc.insets = new Insets(5, 0, 5, 5);
readVehicleInfoButtonGbc.fill = GridBagConstraints.BOTH;
readVehicleInfoButtonGbc.gridx = 2;
readVehicleInfoButtonGbc.gridy = 0;
readVehicleInfoButtonGbc.gridheight = 2;
vehicleInfoPanel.add(getReadVehicleInfoButton(), readVehicleInfoButtonGbc);
}
return vehicleInfoPanel;
}
/**
* Creates, caches and returns the label for the Vehicle Identification
* Number Text Field
*
* @return JLabel
*/
private JLabel getVinLabel() {
if (vinLabel == null) {
vinLabel = new JLabel("VIN:");
vinLabel.setToolTipText("Vehicle Identification Number");
}
return vinLabel;
}
/**
* Creates, caches and returns the Vehicle Identification Number Text Field
*
* @return JTextFIeld
*/
JTextField getVinTextField() {
if (vinTextField == null) {
vinTextField = new JTextField();
vinTextField.setToolTipText("Vehicle Identification Number");
vinTextField.setEditable(false);
}
return vinTextField;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
getFrame().getContentPane().add(getSplitPane());
getFrame().revalidate();
getFrame().setLocationRelativeTo(null);
getFrame().addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
getController().disconnect();
}
});
}
/**
* Helper method the runs the given {@link Runnable} in the Swing Thread to
* update the UI
*
* @param runnable
* the {@link Runnable} to execute
*/
private void refreshUI(Runnable runnable) {
swingExecutor.execute(runnable);
}
}
| 35.933633
| 138
| 0.60864
|
4a1fa6dc70e87c24d9f71593370f8782dee2cef0
| 1,415
|
package controllers;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.json.simple.JSONArray;
//import com.avaje.ebean.Model;
import models.Employee;
import models.Parttime;
import play.*;
import play.data.Form;
import play.data.FormFactory;
import play.mvc.*;
import services.DataAccess;
import util.TO_JSON;
import views.html.*;
/**
* This controller contains an action to handle HTTP requests
* and get data from request
*/
public class Parttime_IN extends Controller{
private FormFactory formFactory;
/**
* An action that renders an HTML page with a welcome message.
* The configuration in the <code>routes</code> file means that
* this method will be called when the application receives a
* <code>GET</code> request with a path of <code>/</code>.
*/
public Result index(String fname, String lname, long salary, long workhours) {
//return ok(index.render("Your new application is ready."));
Parttime pt = new Parttime(fname,lname,salary, workhours);
DataAccess da = new DataAccess();
int empId = da.addEmployee(pt);
Employee emp = da.getEmployee(empId);
List<Employee> employee = new ArrayList();
employee.add(emp);
TO_JSON js = new TO_JSON();
System.out.println(" Parttime saved "+empId);
return ok(js.toJSON(employee));
}
}
| 26.203704
| 82
| 0.684806
|
a31e138925c9bcf777f72d9c9701ddcaf6699ddf
| 3,617
|
package tk.louisstudio.daily_notes;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.rengwuxian.materialedittext.MaterialEditText;
public class RegeisterActivity extends AppCompatActivity {
private Toast t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DNUtils.transparencyBar(this);
setContentView(R.layout.activity_register);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
final MaterialEditText email = findViewById(R.id.mail);
final MaterialEditText pass = findViewById(R.id.pass);
final MaterialEditText passagain = findViewById(R.id.passagain);
final MaterialEditText usern = findViewById(R.id.usern);
FloatingActionButton register = findViewById(R.id.registbut);
usern.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (usern.getText().toString().equals("")) {
usern.setError(getString(R.string.inputun));
}
}
});
pass.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (pass.getText().toString().equals("")) {
if (usern.getText().toString().equals("")) {
pass.setError(getString(R.string.inputpw));
}
}
}
});
passagain.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (passagain.getText().toString().equals("")) {
passagain.setError(getString(R.string.inputpw));
}
if (!passagain.getText().toString().equals(pass.getText().toString())) {
passagain.setError(getString(R.string.different));
}
}
});
email.setOnFocusChangeListener(
new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (email.getText().toString().equals("")) {
email.setError(getString(R.string.inputmail));
}
}
});
register.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
int code =
User.instance.register(
usern.getText().toString(),
pass.getText().toString(),
passagain.getText().toString(),
email.getText().toString());
int stringId = 0;
switch (code) {
case 0:
stringId = R.string.successregis;
break;
case 1:
stringId = R.string.usernameSame;
break;
case 2:
stringId = R.string.different;
break;
case 3:
stringId = R.string.internet;
break;
}
t = Toast.makeText(getBaseContext(), getString(stringId), Toast.LENGTH_SHORT);
t.show();
finish();
}
});
}
}
| 35.811881
| 97
| 0.582527
|
5e3fe47cc5094ab12fd387bd3a812359ff259db9
| 294
|
package com.baremetalcode.db.domain;
import lombok.Data;
import java.util.UUID;
@Data
public class User {
private String uuid = UUID.randomUUID().toString();
private String firstName;
private String lastName;
private String countryISO;
private UserAddress userAddress;
}
| 19.6
| 55
| 0.741497
|
0503942d9ee2d4a19b870746c88ea72e0b6389f0
| 605
|
package com.example.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* @author tuzhijin
* @version Id: AsyncTask.java, v 0.1 2019/6/12 18:21 tuzhijin Exp $$
*/
@Component
public class AsyncTask {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
@Async("myTaskAsyncPool") //myTaskAsynPool即配置线程池的方法名,此处如果不写自定义线程池的方法名,会使用默认的线程池
public void doTask1(int i) throws InterruptedException {
logger.info("Task" + i + " started.");
}
}
| 27.5
| 84
| 0.740496
|
a877d04b3757dc7491547c495df35ef537b7750a
| 1,085
|
package com.github.dakusui.jcunit.examples.testgen;
import com.github.dakusui.jcunit.runners.standard.annotations.FactorField;
import com.github.dakusui.jcunit.runners.standard.JCUnit;
import com.github.dakusui.jcunit.runners.standard.TestCaseUtils;
import com.github.dakusui.jcunit.core.tuples.TupleUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(JCUnit.class)
public class TestGen {
@FactorField(stringLevels = { "Starter", "Home Basic", "Home Premium", "Professional", "Enterprise", "Ultimate" })
public String edition;
@FactorField(intLevels = { 1, 2, 4, 8 })
public int ramInGB;
@FactorField(intLevels = { 64, 128, 256, 512 })
public int gramInMB;
@FactorField(intLevels = { 20, 30, 50, 100 })
public int hddSizeInGB;
@FactorField(floatLevels = { 1.5f, 2, 2.5f, 3 })
public float cpuClockInGHz;
@FactorField(stringLevels = { "IE", "Firefox", "Opera", "Safari", "Chrome" })
public String browser;
@Test
public void printTestCase() {
System.out.println(TupleUtils.toString(TestCaseUtils.toTestCase(this)));
}
}
| 36.166667
| 116
| 0.727189
|
444a496693a3bc0f161f6f1798cfab9151882956
| 9,981
|
package athena.user.application;
import athena.api.AthenaMLFeatureConfiguration;
import athena.api.Indexing;
import athena.api.Marking;
import athena.api.clustering.kmeans.KMeansDetectionAlgorithm;
import athena.api.clustering.kmeans.KMeansDetectionModel;
import athena.northbound.DataQueryManager;
import athena.northbound.impl.DataQueryManagerImpl;
import athena.northbound.impl.EventDeliveryManagerImpl;
import athena.northbound.impl.MachineLearningManagerImpl;
import athena.util.DatabaseConnector;
import org.onosproject.athena.database.*;
import org.onosproject.athena.database.impl.FeatureDatabaseMgmtManager;
import org.onosproject.core.ApplicationId;
import org.onosproject.core.DefaultApplicationId;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
/**
* Created by jinwookim on 2017. 6. 7..
*/
public class Sample {
public void requestFeatures() {
// connect to DB cluster and initialize data query manager
DatabaseConnector dc = new DatabaseConnector();
dc.setDATABASE_IP(System.getenv("MD1"));
DataQueryManager dqm = new DataQueryManagerImpl(dc);
// make user-defined feature constraints
FeatureConstraint and = new FeatureConstraint(FeatureConstraintOperatorType.LOGICAL,
new FeatureConstraintOperator(FeatureConstraintOperator.LOGICAL_AND));
FeatureConstraint flowStatsPacketCount = new FeatureConstraint(FeatureConstraintType.FEATURE,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_GT),
new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_PACKET_COUNT),
new TargetAthenaValue(AthenaValueGenerator.generateAthenaValue("10")));
FeatureConstraint flowStatsDuration =
new FeatureConstraint(FeatureConstraintType.FEATURE,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_GT),
new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_DURATION_SEC),
new TargetAthenaValue(1));
and.appenValue(new TargetAthenaValue(flowStatsPacketCount));
and.appenValue(new TargetAthenaValue(flowStatsDuration));
AdvancedFeatureConstraint afc = new AdvancedFeatureConstraint();
afc.addAdvancedOptions(AdvancedFeatureConstraintType.SORTING, new AdvancedFeatureConstraintValue(AthenaFeatureField.FLOW_STATS_DURATION_SEC));
AthenaFeatures af = dqm.requestAthenaFeatures(and, afc);
AthenaFeatureRequester afr = new AthenaFeatureRequester(AthenaFeatureRequestrType.REQUEST_FEATURES,
and, afc);
dqm.displayFeatures(afr, af);
}
public void generateModel() {
int k = 5;
int iter = 20;
// Initialize DB and Computing cluster
DatabaseConnector databaseConnector = new DatabaseConnector();
MachineLearningManagerImpl machineLearningManager = new MachineLearningManagerImpl();
machineLearningManager.setMainClass("athena.user.application.Main");
machineLearningManager.setArtifactId("athena-tester-1.6.0");
machineLearningManager.setDatabaseConnector(databaseConnector);
// Set custom feature constraints
FeatureConstraint featureConstraint = new FeatureConstraint(FeatureConstraintOperatorType.LOGICAL,
new FeatureConstraintOperator(FeatureConstraintOperator.LOGICAL_AND));
FeatureConstraint featureConstraint2 = new FeatureConstraint(FeatureConstraintType.INDEX,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_EQ),
new AthenaIndexField(AthenaIndexField.MATCH_IPV4_SRC),
new TargetAthenaValue(AthenaValueGenerator.parseIPv4ToAthenaValue("10.0.0.1")));
FeatureConstraint featureConstraint3 = new FeatureConstraint(FeatureConstraintType.INDEX,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_EQ),
new AthenaIndexField(AthenaIndexField.MATCH_IP_PROTO),
new TargetAthenaValue(AthenaValueGenerator.generateAthenaValue("6")));
featureConstraint.setLocation("model");
featureConstraint.appenValue(new TargetAthenaValue(featureConstraint2));
featureConstraint.appenValue(new TargetAthenaValue(featureConstraint3));
// Set parameters for data pre-processing
AthenaMLFeatureConfiguration athenaMLFeatureConfiguration = new AthenaMLFeatureConfiguration();
athenaMLFeatureConfiguration.setNormalization(true);
athenaMLFeatureConfiguration.addWeight(new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_PAIR_FLOW_RATIO), 1000);
// Specify which fields are used for ML features
athenaMLFeatureConfiguration.addTargetFeatures(new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_BYTE_COUNT));
athenaMLFeatureConfiguration.addTargetFeatures(new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_PACKET_COUNT));
athenaMLFeatureConfiguration.addTargetFeatures(new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_PAIR_FLOW_RATIO));
athenaMLFeatureConfiguration.addTargetFeatures(new AthenaFeatureField(AthenaFeatureField.FLOW_STATS_DURATION_SEC));
// Set parameters for ML algorithms
KMeansDetectionAlgorithm kMeansDetectionAlgorithm = new KMeansDetectionAlgorithm();
kMeansDetectionAlgorithm.setK(8);
kMeansDetectionAlgorithm.setMaxIterations(iter);
kMeansDetectionAlgorithm.setRuns(10);
Marking marking = new Marking();
marking.setSrcMaskMarking(0x000000ff, 0x00000065);
Indexing indexing = new Indexing();
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_IP_PROTO));
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_TCP_SRC));
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_TCP_DST));
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_UDP_SRC));
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_UDP_DST));
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_IPV4_SRC));
indexing.addIndexingElements(new AthenaIndexField(AthenaIndexField.MATCH_IPV4_DST));
KMeansDetectionModel kMeansDetectionModel = (KMeansDetectionModel) machineLearningManager.generateAthenaDetectionModel(featureConstraint, athenaMLFeatureConfiguration, kMeansDetectionAlgorithm, indexing, marking);
machineLearningManager.saveDetectionModel(kMeansDetectionModel, ".");
kMeansDetectionModel.getSummary().printSummary();
}
public void testOnlineDelivery() {
FeatureConstraint dataRequestobject =
new FeatureConstraint(FeatureConstraintOperatorType.LOGICAL,
new FeatureConstraintOperator(FeatureConstraintOperator.LOGICAL_AND));
FeatureConstraint packetIn1 =
new FeatureConstraint(FeatureConstraintType.INDEX,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_EQ),
new AthenaIndexField(AthenaIndexField.MATCH_IN_PORT)
, new TargetAthenaValue(AthenaValueGenerator.generateAthenaValue("1")));
FeatureConstraint packetIn2 =
new FeatureConstraint(FeatureConstraintType.INDEX,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_EQ),
new AthenaIndexField(AthenaIndexField.MATCH_IPV4_SRC)
, new TargetAthenaValue(AthenaValueGenerator.parseIPv4ToAthenaValue("10.0.0.1")));
FeatureConstraint featureConstraint =
new FeatureConstraint(FeatureConstraintType.INDEX,
FeatureConstraintOperatorType.COMPARABLE,
new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_GT),
new AthenaIndexField(AthenaIndexField.MATCH_IPV4_SRC),
new TargetAthenaValue(AthenaValueGenerator.generateAthenaValue("0")));
// FeatureConstraint featureConstraint = new FeatureConstraint(FeatureConstraintType.INDEX,
// FeatureConstraintOperatorType.COMPARABLE,
// new FeatureConstraintOperator(FeatureConstraintOperator.COMPARISON_GT),
// new AthenaIndexField(AthenaIndexField.MATCH_IPV4_SRC),
// new TargetAthenaValue(AthenaValueGenerator.generateAthenaValue("0")));
dataRequestobject.appenValue(new TargetAthenaValue(packetIn1));
dataRequestobject.appenValue(new TargetAthenaValue(packetIn2));
System.out.println("Initialize EventDeliveryManager !!");
EventDeliveryManagerImpl eventDeliveryManager = new EventDeliveryManagerImpl(new InternalAthenaFeatureEventListener());
System.out.println("Register Online Athena Feature");
eventDeliveryManager.registerOnlineAthenaFeature(new DefaultApplicationId(99, "online"), new QueryIdentifier((short) 1), packetIn2);
}
public class InternalAthenaFeatureEventListener implements AthenaFeatureEventListener {
public InternalAthenaFeatureEventListener() {
}
@Override
public void getRequestedFeatures(ApplicationId applicationId, AthenaFeatures athenaFeatures) {
}
@Override
public void getFeatureEvent(ApplicationId applicationId, QueryIdentifier id, HashMap<String, Object> event) {
System.out.println(event.toString());
}
}
}
| 53.951351
| 221
| 0.742811
|
849d6d432b60eee8bb972059b311366ec3e39a95
| 7,016
|
/**********************************************************************
Copyright (c) 2011 Peter Rainer and others. 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.
Contributors :
...
***********************************************************************/
package org.datanucleus.store.hbase.valuegenerator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.compress.Compression.Algorithm;
import org.apache.hadoop.hbase.util.Bytes;
import org.datanucleus.exceptions.NucleusDataStoreException;
import org.datanucleus.exceptions.NucleusUserException;
import org.datanucleus.store.hbase.HBaseStoreManager;
import org.datanucleus.store.valuegenerator.AbstractDatastoreGenerator;
import org.datanucleus.store.valuegenerator.ValueGenerationBlock;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
/**
* Generator that uses a table in HBase to store and allocate identity values.
*/
public class IncrementGenerator extends AbstractDatastoreGenerator<Long>
{
static final String INCREMENT_COL_NAME = "increment";
/** Key used in the Table to access the increment count */
private String key;
private HTableInterface table;
private String tableName = null;
/**
* Constructor. Will receive the following properties (as a minimum) through this constructor.
* <ul>
* <li>class-name : Name of the class whose object is being inserted.</li>
* <li>root-class-name : Name of the root class in this inheritance tree</li>
* <li>field-name : Name of the field with the strategy (unless datastore identity field)</li>
* <li>catalog-name : Catalog of the table (if specified)</li>
* <li>schema-name : Schema of the table (if specified)</li>
* <li>table-name : Name of the root table for this inheritance tree (containing the field).</li>
* <li>column-name : Name of the column in the table (for the field)</li>
* <li>sequence-name : Name of the sequence (if specified in MetaData as "sequence)</li>
* </ul>
* @param name Symbolic name for this generator
* @param props Properties controlling the behaviour of the generator (or null if not required).
*/
public IncrementGenerator(String name, Properties props)
{
super(name, props);
this.key = properties.getProperty("field-name", name);
this.tableName = properties.getProperty("sequence-table-name");
if (this.tableName == null)
{
this.tableName = "IncrementTable";
}
if (properties.containsKey("key-cache-size"))
{
allocationSize = Integer.valueOf(properties.getProperty("key-cache-size"));
}
else
{
allocationSize = 1;
}
}
private synchronized void initialiseTable()
{
if (this.table == null)
{
try
{
HBaseStoreManager hbaseMgr = (HBaseStoreManager) storeMgr;
Configuration config = hbaseMgr.getHbaseConfig();
HBaseAdmin admin = new HBaseAdmin(config);
try
{
if (!admin.tableExists(this.tableName))
{
if (!storeMgr.getSchemaHandler().isAutoCreateTables())
{
throw new NucleusUserException(Localiser.msg("040011", tableName));
}
NucleusLogger.VALUEGENERATION.debug("IncrementGenerator: Creating Table '" + this.tableName + "'");
HTableDescriptor ht = new HTableDescriptor(this.tableName);
HColumnDescriptor hcd = new HColumnDescriptor(INCREMENT_COL_NAME);
hcd.setCompressionType(Algorithm.NONE);
hcd.setMaxVersions(1);
ht.addFamily(hcd);
admin.createTable(ht);
}
}
finally
{
admin.close();
}
this.table = new HTable(config, this.tableName);
if (!this.table.exists(new Get(Bytes.toBytes(key))))
{
long initialValue = 0;
if (properties.containsKey("key-initial-value"))
{
initialValue = Long.valueOf(properties.getProperty("key-initial-value"))-1;
}
this.table.put(new Put(Bytes.toBytes(key)).add(Bytes.toBytes(INCREMENT_COL_NAME),
Bytes.toBytes(INCREMENT_COL_NAME), Bytes.toBytes(initialValue)));
}
}
catch (IOException ex)
{
NucleusLogger.VALUEGENERATION.fatal("Error instantiating IncrementGenerator", ex);
}
}
}
public String getName()
{
return this.name;
}
/* (non-Javadoc)
* @see org.datanucleus.store.valuegenerator.AbstractGenerator#reserveBlock(long)
*/
protected synchronized ValueGenerationBlock<Long> reserveBlock(long size)
{
if (size < 1)
{
return null;
}
if (this.table == null)
{
this.initialiseTable();
}
// Allocate value(s)
long number;
List<Long> oids = new ArrayList<Long>();
try
{
number = table.incrementColumnValue(Bytes.toBytes(key), Bytes.toBytes(INCREMENT_COL_NAME),
Bytes.toBytes(INCREMENT_COL_NAME), size);
long nextNumber = number - size + 1;
for (int i=0;i<size;i++)
{
oids.add(nextNumber++);
}
}
catch (IOException ex)
{
NucleusLogger.VALUEGENERATION.error("IncrementGenerator: Error incrementing generated value", ex);
throw new NucleusDataStoreException("Error incrementing generated value.", ex);
}
return new ValueGenerationBlock<Long>(oids);
}
}
| 38.549451
| 123
| 0.607469
|
9489f3325c0eb99d67c606ca1f92eea6b12ee48f
| 325
|
package example.guice;
import com.sun.jersey.guice.JerseyServletModule;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
public class ExampleServletModule extends JerseyServletModule {
@Override
protected void configureServlets() {
serve("/resource/*").with(GuiceContainer.class);
}
}
| 25
| 65
| 0.763077
|
927abdbdd848f767f5c6976914dcbe86d8e98cc6
| 13,962
|
package com.aspose.cells.model;
import java.util.*;
import com.aspose.cells.model.Color;
import com.aspose.cells.model.LinkElement;
public class Worksheet {
private List<Link> Links = new ArrayList<Link>();
private Boolean DisplayRightToLeft = null;
private Boolean DisplayZeros = null;
private Integer FirstVisibleColumn = null;
private Integer FirstVisibleRow = null;
private String Name = null;
private Integer Index = null;
private Boolean IsGridlinesVisible = null;
private Boolean IsOutlineShown = null;
private Boolean IsPageBreakPreview = null;
private Boolean IsVisible = null;
private Boolean IsProtected = null;
private Boolean IsRowColumnHeadersVisible = null;
private Boolean IsRulerVisible = null;
private Boolean IsSelected = null;
private Color TabColor = null;
private Boolean TransitionEntry = null;
private Boolean TransitionEvaluation = null;
private String Type = null;
private String ViewType = null;
private String VisibilityType = null;
private Integer Zoom = null;
private LinkElement Cells = null;
private LinkElement Charts = null;
private LinkElement AutoShapes = null;
private LinkElement OleObjects = null;
private LinkElement Comments = null;
private LinkElement Pictures = null;
private LinkElement MergedCells = null;
private LinkElement Validations = null;
private LinkElement ConditionalFormattings = null;
private LinkElement Hyperlinks = null;
/**
* getLinks
* Gets List<Link>
* @return Links
*/
public List<Link> getLinks() {
return Links;
}
/**
* setLinks
* Sets List<Link>
* @param Links List<Link>
*/
public void setLinks(List<Link> Links) {
this.Links = Links;
}
/**
* getDisplayRightToLeft
* Gets Boolean
* @return DisplayRightToLeft
*/
public Boolean getDisplayRightToLeft() {
return DisplayRightToLeft;
}
/**
* setDisplayRightToLeft
* Sets Boolean
* @param DisplayRightToLeft Boolean
*/
public void setDisplayRightToLeft(Boolean DisplayRightToLeft) {
this.DisplayRightToLeft = DisplayRightToLeft;
}
/**
* getDisplayZeros
* Gets Boolean
* @return DisplayZeros
*/
public Boolean getDisplayZeros() {
return DisplayZeros;
}
/**
* setDisplayZeros
* Sets Boolean
* @param DisplayZeros Boolean
*/
public void setDisplayZeros(Boolean DisplayZeros) {
this.DisplayZeros = DisplayZeros;
}
/**
* getFirstVisibleColumn
* Gets Integer
* @return FirstVisibleColumn
*/
public Integer getFirstVisibleColumn() {
return FirstVisibleColumn;
}
/**
* setFirstVisibleColumn
* Sets Integer
* @param FirstVisibleColumn Integer
*/
public void setFirstVisibleColumn(Integer FirstVisibleColumn) {
this.FirstVisibleColumn = FirstVisibleColumn;
}
/**
* getFirstVisibleRow
* Gets Integer
* @return FirstVisibleRow
*/
public Integer getFirstVisibleRow() {
return FirstVisibleRow;
}
/**
* setFirstVisibleRow
* Sets Integer
* @param FirstVisibleRow Integer
*/
public void setFirstVisibleRow(Integer FirstVisibleRow) {
this.FirstVisibleRow = FirstVisibleRow;
}
/**
* getName
* Gets String
* @return Name
*/
public String getName() {
return Name;
}
/**
* setName
* Sets String
* @param Name String
*/
public void setName(String Name) {
this.Name = Name;
}
/**
* getIndex
* Gets Integer
* @return Index
*/
public Integer getIndex() {
return Index;
}
/**
* setIndex
* Sets Integer
* @param Index Integer
*/
public void setIndex(Integer Index) {
this.Index = Index;
}
/**
* getIsGridlinesVisible
* Gets Boolean
* @return IsGridlinesVisible
*/
public Boolean getIsGridlinesVisible() {
return IsGridlinesVisible;
}
/**
* setIsGridlinesVisible
* Sets Boolean
* @param IsGridlinesVisible Boolean
*/
public void setIsGridlinesVisible(Boolean IsGridlinesVisible) {
this.IsGridlinesVisible = IsGridlinesVisible;
}
/**
* getIsOutlineShown
* Gets Boolean
* @return IsOutlineShown
*/
public Boolean getIsOutlineShown() {
return IsOutlineShown;
}
/**
* setIsOutlineShown
* Sets Boolean
* @param IsOutlineShown Boolean
*/
public void setIsOutlineShown(Boolean IsOutlineShown) {
this.IsOutlineShown = IsOutlineShown;
}
/**
* getIsPageBreakPreview
* Gets Boolean
* @return IsPageBreakPreview
*/
public Boolean getIsPageBreakPreview() {
return IsPageBreakPreview;
}
/**
* setIsPageBreakPreview
* Sets Boolean
* @param IsPageBreakPreview Boolean
*/
public void setIsPageBreakPreview(Boolean IsPageBreakPreview) {
this.IsPageBreakPreview = IsPageBreakPreview;
}
/**
* getIsVisible
* Gets Boolean
* @return IsVisible
*/
public Boolean getIsVisible() {
return IsVisible;
}
/**
* setIsVisible
* Sets Boolean
* @param IsVisible Boolean
*/
public void setIsVisible(Boolean IsVisible) {
this.IsVisible = IsVisible;
}
/**
* getIsProtected
* Gets Boolean
* @return IsProtected
*/
public Boolean getIsProtected() {
return IsProtected;
}
/**
* setIsProtected
* Sets Boolean
* @param IsProtected Boolean
*/
public void setIsProtected(Boolean IsProtected) {
this.IsProtected = IsProtected;
}
/**
* getIsRowColumnHeadersVisible
* Gets Boolean
* @return IsRowColumnHeadersVisible
*/
public Boolean getIsRowColumnHeadersVisible() {
return IsRowColumnHeadersVisible;
}
/**
* setIsRowColumnHeadersVisible
* Sets Boolean
* @param IsRowColumnHeadersVisible Boolean
*/
public void setIsRowColumnHeadersVisible(Boolean IsRowColumnHeadersVisible) {
this.IsRowColumnHeadersVisible = IsRowColumnHeadersVisible;
}
/**
* getIsRulerVisible
* Gets Boolean
* @return IsRulerVisible
*/
public Boolean getIsRulerVisible() {
return IsRulerVisible;
}
/**
* setIsRulerVisible
* Sets Boolean
* @param IsRulerVisible Boolean
*/
public void setIsRulerVisible(Boolean IsRulerVisible) {
this.IsRulerVisible = IsRulerVisible;
}
/**
* getIsSelected
* Gets Boolean
* @return IsSelected
*/
public Boolean getIsSelected() {
return IsSelected;
}
/**
* setIsSelected
* Sets Boolean
* @param IsSelected Boolean
*/
public void setIsSelected(Boolean IsSelected) {
this.IsSelected = IsSelected;
}
/**
* getTabColor
* Gets Color
* @return TabColor
*/
public Color getTabColor() {
return TabColor;
}
/**
* setTabColor
* Sets Color
* @param TabColor Color
*/
public void setTabColor(Color TabColor) {
this.TabColor = TabColor;
}
/**
* getTransitionEntry
* Gets Boolean
* @return TransitionEntry
*/
public Boolean getTransitionEntry() {
return TransitionEntry;
}
/**
* setTransitionEntry
* Sets Boolean
* @param TransitionEntry Boolean
*/
public void setTransitionEntry(Boolean TransitionEntry) {
this.TransitionEntry = TransitionEntry;
}
/**
* getTransitionEvaluation
* Gets Boolean
* @return TransitionEvaluation
*/
public Boolean getTransitionEvaluation() {
return TransitionEvaluation;
}
/**
* setTransitionEvaluation
* Sets Boolean
* @param TransitionEvaluation Boolean
*/
public void setTransitionEvaluation(Boolean TransitionEvaluation) {
this.TransitionEvaluation = TransitionEvaluation;
}
/**
* getType
* Gets String
* @return Type
*/
public String getType() {
return Type;
}
/**
* setType
* Sets String
* @param Type String
*/
public void setType(String Type) {
this.Type = Type;
}
/**
* getViewType
* Gets String
* @return ViewType
*/
public String getViewType() {
return ViewType;
}
/**
* setViewType
* Sets String
* @param ViewType String
*/
public void setViewType(String ViewType) {
this.ViewType = ViewType;
}
/**
* getVisibilityType
* Gets String
* @return VisibilityType
*/
public String getVisibilityType() {
return VisibilityType;
}
/**
* setVisibilityType
* Sets String
* @param VisibilityType String
*/
public void setVisibilityType(String VisibilityType) {
this.VisibilityType = VisibilityType;
}
/**
* getZoom
* Gets Integer
* @return Zoom
*/
public Integer getZoom() {
return Zoom;
}
/**
* setZoom
* Sets Integer
* @param Zoom Integer
*/
public void setZoom(Integer Zoom) {
this.Zoom = Zoom;
}
/**
* getCells
* Gets LinkElement
* @return Cells
*/
public LinkElement getCells() {
return Cells;
}
/**
* setCells
* Sets LinkElement
* @param Cells LinkElement
*/
public void setCells(LinkElement Cells) {
this.Cells = Cells;
}
/**
* getCharts
* Gets LinkElement
* @return Charts
*/
public LinkElement getCharts() {
return Charts;
}
/**
* setCharts
* Sets LinkElement
* @param Charts LinkElement
*/
public void setCharts(LinkElement Charts) {
this.Charts = Charts;
}
/**
* getAutoShapes
* Gets LinkElement
* @return AutoShapes
*/
public LinkElement getAutoShapes() {
return AutoShapes;
}
/**
* setAutoShapes
* Sets LinkElement
* @param AutoShapes LinkElement
*/
public void setAutoShapes(LinkElement AutoShapes) {
this.AutoShapes = AutoShapes;
}
/**
* getOleObjects
* Gets LinkElement
* @return OleObjects
*/
public LinkElement getOleObjects() {
return OleObjects;
}
/**
* setOleObjects
* Sets LinkElement
* @param OleObjects LinkElement
*/
public void setOleObjects(LinkElement OleObjects) {
this.OleObjects = OleObjects;
}
/**
* getComments
* Gets LinkElement
* @return Comments
*/
public LinkElement getComments() {
return Comments;
}
/**
* setComments
* Sets LinkElement
* @param Comments LinkElement
*/
public void setComments(LinkElement Comments) {
this.Comments = Comments;
}
/**
* getPictures
* Gets LinkElement
* @return Pictures
*/
public LinkElement getPictures() {
return Pictures;
}
/**
* setPictures
* Sets LinkElement
* @param Pictures LinkElement
*/
public void setPictures(LinkElement Pictures) {
this.Pictures = Pictures;
}
/**
* getMergedCells
* Gets LinkElement
* @return MergedCells
*/
public LinkElement getMergedCells() {
return MergedCells;
}
/**
* setMergedCells
* Sets LinkElement
* @param MergedCells LinkElement
*/
public void setMergedCells(LinkElement MergedCells) {
this.MergedCells = MergedCells;
}
/**
* getValidations
* Gets LinkElement
* @return Validations
*/
public LinkElement getValidations() {
return Validations;
}
/**
* setValidations
* Sets LinkElement
* @param Validations LinkElement
*/
public void setValidations(LinkElement Validations) {
this.Validations = Validations;
}
/**
* getConditionalFormattings
* Gets LinkElement
* @return ConditionalFormattings
*/
public LinkElement getConditionalFormattings() {
return ConditionalFormattings;
}
/**
* setConditionalFormattings
* Sets LinkElement
* @param ConditionalFormattings LinkElement
*/
public void setConditionalFormattings(LinkElement ConditionalFormattings) {
this.ConditionalFormattings = ConditionalFormattings;
}
/**
* getHyperlinks
* Gets LinkElement
* @return Hyperlinks
*/
public LinkElement getHyperlinks() {
return Hyperlinks;
}
/**
* setHyperlinks
* Sets LinkElement
* @param Hyperlinks LinkElement
*/
public void setHyperlinks(LinkElement Hyperlinks) {
this.Hyperlinks = Hyperlinks;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Worksheet {\n");
sb.append(" Links: ").append(Links).append("\n");
sb.append(" DisplayRightToLeft: ").append(DisplayRightToLeft).append("\n");
sb.append(" DisplayZeros: ").append(DisplayZeros).append("\n");
sb.append(" FirstVisibleColumn: ").append(FirstVisibleColumn).append("\n");
sb.append(" FirstVisibleRow: ").append(FirstVisibleRow).append("\n");
sb.append(" Name: ").append(Name).append("\n");
sb.append(" Index: ").append(Index).append("\n");
sb.append(" IsGridlinesVisible: ").append(IsGridlinesVisible).append("\n");
sb.append(" IsOutlineShown: ").append(IsOutlineShown).append("\n");
sb.append(" IsPageBreakPreview: ").append(IsPageBreakPreview).append("\n");
sb.append(" IsVisible: ").append(IsVisible).append("\n");
sb.append(" IsProtected: ").append(IsProtected).append("\n");
sb.append(" IsRowColumnHeadersVisible: ").append(IsRowColumnHeadersVisible).append("\n");
sb.append(" IsRulerVisible: ").append(IsRulerVisible).append("\n");
sb.append(" IsSelected: ").append(IsSelected).append("\n");
sb.append(" TabColor: ").append(TabColor).append("\n");
sb.append(" TransitionEntry: ").append(TransitionEntry).append("\n");
sb.append(" TransitionEvaluation: ").append(TransitionEvaluation).append("\n");
sb.append(" Type: ").append(Type).append("\n");
sb.append(" ViewType: ").append(ViewType).append("\n");
sb.append(" VisibilityType: ").append(VisibilityType).append("\n");
sb.append(" Zoom: ").append(Zoom).append("\n");
sb.append(" Cells: ").append(Cells).append("\n");
sb.append(" Charts: ").append(Charts).append("\n");
sb.append(" AutoShapes: ").append(AutoShapes).append("\n");
sb.append(" OleObjects: ").append(OleObjects).append("\n");
sb.append(" Comments: ").append(Comments).append("\n");
sb.append(" Pictures: ").append(Pictures).append("\n");
sb.append(" MergedCells: ").append(MergedCells).append("\n");
sb.append(" Validations: ").append(Validations).append("\n");
sb.append(" ConditionalFormattings: ").append(ConditionalFormattings).append("\n");
sb.append(" Hyperlinks: ").append(Hyperlinks).append("\n");
sb.append("}\n");
return sb.toString();
}
}
| 21.283537
| 94
| 0.677338
|
299b9170ae0b0710c09e8fe161ef2682e72d7277
| 2,658
|
package com.indiraactive.fulfillmentplatform.utility;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.anyString;
import static com.indiraactive.fulfillmentplatform.utility.CommandLineRunner.ScriptCompletionCode;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommandLineRunnerTests {
@Autowired
private CommandLineRunner commandLineRunner;
@MockBean
private RuntimeWrapper runtimeWrapper;
public void configureMockProcess(int errorCodeProcessWillReturn) throws Exception {
Process process = Mockito.mock(Process.class);
given(process.waitFor()).willReturn(errorCodeProcessWillReturn);
given(process.getInputStream()).willReturn(null);
given(this.runtimeWrapper.executeCommand(anyString())).willReturn(process);
}
@Test
public void testRunScriptReturnsSuccess() throws Exception {
CommandLineRunner.ScriptCompletionCode expected = CommandLineRunner.ScriptCompletionCode.SUCCESS;
String pathToScript = new ClassPathResource("test.py").getFile().getAbsolutePath();
String args = "0";
configureMockProcess(0);
CommandLineRunner.ScriptCompletionCode actual = commandLineRunner.executeCommand("python " + " " + pathToScript + " " + args);
assertEquals(expected, actual);
}
@Test
public void testRunScriptReturnsFailure() throws Exception {
CommandLineRunner.ScriptCompletionCode expected = CommandLineRunner.ScriptCompletionCode.FAILURE;
String pathToScript = new ClassPathResource("test.py").getFile().getAbsolutePath();
String args = "1";
configureMockProcess(1);
CommandLineRunner.ScriptCompletionCode actual = commandLineRunner.executeCommand("python " + " " + pathToScript + " " + args);
assertEquals(expected, actual);
}
@Test
public void testCheckCompletionCode() throws Exception{
ScriptCompletionCode expectedCompletionCode = ScriptCompletionCode.SUCCESS;
ScriptCompletionCode actualError = commandLineRunner.checkCompletionCode(0, "anyString");
assertEquals(actualError, expectedCompletionCode);
}
}
| 36.410959
| 134
| 0.76298
|
d459d6fe7e7c6a58e0bdae1e44128c9486db0802
| 253
|
package edu.cmu.hcii.whyline.source;
/**
*
* @author Andrew J. Ko
*
*/
public abstract class ExpressionElement extends JavaElement {
public ExpressionElement(JavaElement parent, Token first, Token last) {
super(parent, first, last);
}
}
| 14.882353
| 72
| 0.703557
|
abf1385f7ec567148232b84af46e906a165bd0a2
| 78
|
package com.stang.tang.zhima.service;
public interface ParameterService {
}
| 13
| 37
| 0.794872
|
a390d97bf4be417ef68473c24595758189dd4abe
| 5,095
|
/*
* 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.aliyuncs.dds.transform.v20151201;
import java.util.ArrayList;
import java.util.List;
import com.aliyuncs.dds.model.v20151201.EvaluateFailOverSwitchResponse;
import com.aliyuncs.dds.model.v20151201.EvaluateFailOverSwitchResponse.ItemsItem;
import com.aliyuncs.dds.model.v20151201.EvaluateFailOverSwitchResponse.ItemsItem.AccountsItem;
import com.aliyuncs.dds.model.v20151201.EvaluateFailOverSwitchResponse.ReportsItem;
import java.util.Map;
import com.aliyuncs.transform.UnmarshallerContext;
public class EvaluateFailOverSwitchResponseUnmarshaller {
public static EvaluateFailOverSwitchResponse unmarshall(EvaluateFailOverSwitchResponse evaluateFailOverSwitchResponse, UnmarshallerContext context) {
evaluateFailOverSwitchResponse.setRequestId(context.stringValue("EvaluateFailOverSwitchResponse.RequestId"));
evaluateFailOverSwitchResponse.setReplicaId(context.stringValue("EvaluateFailOverSwitchResponse.ReplicaId"));
evaluateFailOverSwitchResponse.setEvaluateResult(context.stringValue("EvaluateFailOverSwitchResponse.EvaluateResult"));
List<ItemsItem> items = new ArrayList<ItemsItem>();
for (int i = 0; i < context.lengthValue("EvaluateFailOverSwitchResponse.Items.Length"); i++) {
ItemsItem itemsItem = new ItemsItem();
itemsItem.setDBInstanceId(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].DBInstanceId"));
itemsItem.setRegionId(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].RegionId"));
itemsItem.setReadWriteType(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].ReadWriteType"));
itemsItem.setInstanceNetworkType(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].InstanceNetworkType"));
itemsItem.setSecurityIPList(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].SecurityIPList"));
itemsItem.setHasInternetIP(context.booleanValue("EvaluateFailOverSwitchResponse.Items["+ i +"].HasInternetIP"));
itemsItem.setInternetIP(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].InternetIP"));
List<AccountsItem> accounts = new ArrayList<AccountsItem>();
for (int j = 0; j < context.lengthValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts.Length"); j++) {
AccountsItem accountsItem = new AccountsItem();
accountsItem.setAccountPrivilege(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountPrivilege"));
accountsItem.setAccountStatus(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountStatus"));
accountsItem.setAccountPrivilegeDetail(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountPrivilegeDetail"));
accountsItem.setAccountDescription(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountDescription"));
accountsItem.setAccountID(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountID"));
accountsItem.setAccountName(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountName"));
accountsItem.setPrivExceeded(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].PrivExceeded"));
accountsItem.setEngine(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].Engine"));
accountsItem.setAccountType(context.stringValue("EvaluateFailOverSwitchResponse.Items["+ i +"].Accounts["+ j +"].AccountType"));
accounts.add(accountsItem);
}
itemsItem.setAccounts(accounts);
items.add(itemsItem);
}
evaluateFailOverSwitchResponse.setItems(items);
List<ReportsItem> reports = new ArrayList<ReportsItem>();
for (int i = 0; i < context.lengthValue("EvaluateFailOverSwitchResponse.Reports.Length"); i++) {
ReportsItem reportsItem = new ReportsItem();
reportsItem.setCheckType(context.stringValue("EvaluateFailOverSwitchResponse.Reports["+ i +"].CheckType"));
reportsItem.setSeverity(context.stringValue("EvaluateFailOverSwitchResponse.Reports["+ i +"].Severity"));
reportsItem.setReasonCode(context.stringValue("EvaluateFailOverSwitchResponse.Reports["+ i +"].ReasonCode"));
reportsItem.setReasonMessage(context.stringValue("EvaluateFailOverSwitchResponse.Reports["+ i +"].ReasonMessage"));
reports.add(reportsItem);
}
evaluateFailOverSwitchResponse.setReports(reports);
return evaluateFailOverSwitchResponse;
}
}
| 62.134146
| 155
| 0.777625
|
41f4729d83ac14e174706e369246c15beaad58cb
| 31,990
|
package io.kickflip.sdk.api;
import android.content.Context;
import android.content.SharedPreferences;
import android.location.Location;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import com.amazonaws.auth.BasicAWSCredentials;
import com.google.gson.Gson;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Map;
import hugo.weaving.DebugLog;
import io.kickflip.sdk.api.json.Response;
import io.kickflip.sdk.api.json.Stream;
import io.kickflip.sdk.api.json.StreamList;
import io.kickflip.sdk.api.json.User;
import io.kickflip.sdk.exception.KickflipException;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Kickflip API Client
* <p/>
* After construction, requests can be immediately performed.
* The client will handle acquiring and refreshing OAuth
* Access tokens as needed.
* <p/>
* The client is intended to manage a unique Kickflip user per Android device installation.
*/
// TODO: Standardize Kickflip server error responses to have detail message
public class KickflipApiClient {
private static final String TAG = "KickflipApiClient2";
private Context mContext;
private String mClientId; // Allow checking whether Client Creds have changed
private String mClientSecret;
private KickflipService mService;
private Gson mGson; // To convert extraInfo map to json string
// TODO : Add static creator allowing username, display_name etc.
/**
* Return an Observable for a {@link KickflipApiClient}.
* @param autoCreateUser whether this call should also automatically create
* a new user for this app install if that has not yet been done.
* You'd generally only pass false if you want to specify a specific username,
* as the rest of the user details can be changed at any time via
* {@link KickflipApiClient#setUserInfo(String, String, String, Map, KickflipCallback)}
* If false, you must manually create a user upon receiving the KickflipApiClient:
* {@link KickflipApiClient#createNewUser(String, String, String, String, Map)}
* {@link KickflipApiClient#createNewUser(String, String, String, String, Map, KickflipCallback)}
* {@link KickflipApiClient#createNewUser(KickflipCallback)} <- this would be equivalent to auto-creating
*/
public static Observable<KickflipApiClient> create(@NonNull final Context context,
@NonNull final String clientId,
@NonNull final String clientSecret,
final boolean autoCreateUser) {
checkNotNull(context);
checkNotNull(clientId);
checkNotNull(clientSecret);
final Handler callbackHandler = new Handler();
return KickflipApiClientGenerator.getService(clientId, clientSecret)
.map(new Func1<KickflipService, KickflipApiClient>() {
@Override
public KickflipApiClient call(KickflipService kickflipService) {
return new KickflipApiClient(context, kickflipService, clientId, clientSecret);
}
})
.flatMap(new Func1<KickflipApiClient, Observable<KickflipApiClient>>() {
@Override
public Observable<KickflipApiClient> call(final KickflipApiClient kickflipApiClient) {
if (!autoCreateUser) return Observable.just(kickflipApiClient);
return kickflipApiClient.getOrCreateActiveUser()
.map(new Func1<User, KickflipApiClient>() {
@Override
public KickflipApiClient call(User user) {
return kickflipApiClient;
}
});
}
});
}
private KickflipApiClient(@NonNull Context context,
@NonNull KickflipService service,
@NonNull String clientId,
@NonNull String clientSecret) {
checkNotNull(context);
checkNotNull(service);
mService = service;
mContext = context;
mClientId = clientId;
mClientSecret = clientSecret;
mGson = new Gson();
}
// /**
// * Construct a KickflipApiClient. All callbacks from this client will occur
// * on the current calling thread.
// *
// * @param appContext Your Application Context
// * @param key Your Kickflip Account Key
// * @param secret Your Kickflip Account Secret
// */
// private KickflipApiClient2(Context appContext, String key, String secret) {
// this(appContext, key, secret, null);
// }
//
// /**
// * Construct a KickflipApiClient. All callbacks from this client will occur
// * on the current calling thread.
// *
// * @param appContext Your Application Context
// * @param key Your Kickflip Account Key
// * @param secret Your Kickflip Account Secret
// * @param cb A callback to be notified when the provided Kickflip credentials are verified
// */
// private KickflipApiClient2(Context appContext, String key, String secret, KickflipCallback cb) {
// super(appContext, new OAuthConfig()
// .setCredentialStoreName("KF")
// .setClientId(key)
// .setClientSecret(secret)
// .setAccessTokenRequestUrl(BASE_URL + "/o/token/")
// .setAccessTokenAuthorizeUrl(BASE_URL + "/o/authorize/"));
// mCallbackHandler = new Handler();
// initialize(cb);
// }
/**
* @return the currently active Kickflip User, creating if necessary
*/
@DebugLog
private Observable<User> getOrCreateActiveUser() {
User persistedUser = getActiveUser();
if (persistedUser != null) {
Log.d(TAG, "Using persisted user");
return Observable.just(persistedUser);
}
// Create a new user
Log.d(TAG, "Creating new user");
final String password = generateRandomPassword();
return mService.createNewUser(password)
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "Failed to create new user!", throwable);
}
})
.doOnNext(new Action1<User>() {
@Override
public void call(User user) {
Log.d(TAG, "Persisting user " + user.getDisplayName());
storeUser(user, password);
}
});
}
public String getClientId() {
return mClientId;
}
public String getClientSecret() {
return mClientSecret;
}
/**
* Create a new Kickflip User.
* The User created as a result of this request is cached and managed by this KickflipApiClient
* throughout the life of the host Android application installation.
* <p/>
* The other methods of this client will be performed on behalf of the user created by this request,
* unless noted otherwise.
*
* @param username The desired username for this Kickflip User. Will be altered if not unique for this Kickflip app.
* @param password The password for this Kickflip user.
* @param email The email address for this Kickflip user.
* @param displayName The display name for this Kickflip user.
* @param extraInfo Map data to be associated with this Kickflip User.
* @param cb This callback will receive a User in {@link KickflipCallback#onSuccess(Object)}
* or an Exception {@link KickflipCallback#onError(KickflipException)}.
*/
@DebugLog
public void createNewUser(@Nullable String username,
@Nullable String password,
@Nullable String email,
@Nullable String displayName,
@Nullable Map extraInfo,
@Nullable final KickflipCallback<User> cb) {
mService.createNewUser(username, password, displayName, email, mGson.toJson(extraInfo))
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "Failed to create user ", throwable);
}
})
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
if (cb != null) cb.onSuccess(user);
}
});
}
@DebugLog
public Observable<User> createNewUser(@Nullable String username,
@Nullable String password,
@Nullable String email,
@Nullable String displayName,
@Nullable Map extraInfo) {
return mService.createNewUser(username, password, displayName, email, mGson.toJson(extraInfo));
}
/**
* Create a new Kickflip User.
* The User created as a result of this request is active for this KickflipApiClient instance
* throughout the life of the host Android application installation, until a subsequent call to this method
* or {@link #loginUser(String, String, KickflipCallback)} }
* <p/>
* The other methods of this client will be performed on behalf of the user created by this request,
* unless noted otherwise.
*
* @param cb This callback will receive a User in {@link KickflipCallback#onSuccess(Object)}
* or an Exception {@link KickflipCallback#onError(KickflipException)}.
*/
@DebugLog
public void createNewUser(@Nullable final KickflipCallback cb) {
final String password = generateRandomPassword();
mService.createNewUser(password)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "Failed to create user ", throwable);
}
})
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
if (cb != null) cb.onSuccess(user);
}
});
}
/**
* Login an exiting Kickflip User and make it active.
*
* @param username The Kickflip user's username
* @param password The Kickflip user's password
* @param cb This callback will receive a User in {@link KickflipCallback#onSuccess(Object)}
* or an Exception {@link KickflipCallback#onError(KickflipException)}.
*/
@DebugLog
public void loginUser(@NonNull String username,
@NonNull final String password,
@Nullable final KickflipCallback<User> cb) {
checkNotNull(username);
checkNotNull(password);
mService.loginUser(username, password)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "Failed to login user ", throwable);
}
})
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
if (cb != null) cb.onSuccess(user);
}
});
}
/**
* Login an exiting Kickflip User and make it active.
*
* @param username The Kickflip user's username
* @param password The Kickflip user's password
* @return An observable for a {@link User}
*/
@DebugLog
public Observable<User> loginUser(@NonNull String username,
@NonNull final String password) {
checkNotNull(username);
checkNotNull(password);
return mService.loginUser(username, password);
}
/**
* Set the current active user's meta info. Pass a null argument to leave it as-is.
*
* @param newPassword the user's new password
* @param email the user's new email address
* @param displayName The desired display name
* @param extraInfo Arbitrary String data to associate with this user.
* @param cb This callback will receive a User in {@link KickflipCallback#onSuccess(Object)}
* or an Exception {@link KickflipCallback#onError(KickflipException)}.
*/
@DebugLog
public void setUserInfo(@Nullable final String newPassword,
@Nullable String email,
@Nullable String displayName,
@Nullable Map extraInfo,
@Nullable final KickflipCallback<User> cb) {
mService.setUserInfo(newPassword, email, displayName, mGson.toJson(extraInfo))
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "Failed to update user ", throwable);
}
})
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
if (cb != null) cb.onSuccess(user);
}
});
}
/**
* Get public user info
*
* @param username The Kickflip user's username
* @param cb This callback will receive a User in {@link KickflipCallback#onSuccess(Object)}
* or an Exception {@link KickflipCallback#onError(KickflipException)}.
*/
@DebugLog
public void getUserInfo(@NonNull String username,
@Nullable final KickflipCallback<User> cb) {
checkNotNull(username);
mService.getUserInfo(username)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to get user. Reason " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<User>() {
@Override
public void call(User user) {
if (cb != null) cb.onSuccess(user);
}
});
}
/**
* Get public user info
*
* @param username The Kickflip user's username
* @return An Observable for the requested User
*/
@DebugLog
public Observable<User> getUserInfo(@NonNull String username) {
checkNotNull(username);
return mService.getUserInfo(username);
}
/**
* Start a new Stream. Must be called after
* {@link KickflipApiClient#createNewUser(KickflipCallback)}
* Delivers stream endpoint destination data via a {@link KickflipCallback}.
*
* @param cb This callback will receive a Stream subclass in {@link KickflipCallback#onSuccess(Object)}
* depending on the Kickflip account type. Implementors should
* check if the response is instanceof HlsStream, RtmpStream, etc.
*/
@DebugLog
public void startStream(@NonNull Stream stream,
@Nullable final KickflipCallback<Stream> cb) {
checkNotNull(stream);
startStreamWithUser(getActiveUser(), stream, cb);
}
/**
* Start a new Stream owned by the given User. Must be called after
* {@link KickflipApiClient#createNewUser(KickflipCallback)}
* Delivers stream endpoint destination data via a {@link KickflipCallback}.
*
* @param user The Kickflip User on whose behalf this request is performed.
* @param cb This callback will receive a Stream subclass in {@link KickflipCallback#onSuccess(Object)}
* depending on the Kickflip account type. Implementors should
* check if the response is instanceof HlsStream, StartRtmpStreamResponse, etc.
*/
@DebugLog
private void startStreamWithUser(@NonNull User user,
@NonNull Stream stream,
@Nullable final KickflipCallback<Stream> cb) {
checkNotNull(user);
checkNotNull(stream);
mService.startStream(user.getUUID(),
stream.isPrivate(),
stream.getTitle(),
stream.getDescription(),
stream.getExtraInfoString())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to start stream. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<Stream>() {
@Override
public void call(Stream stream) {
if (cb != null) cb.onSuccess(stream);
}
});
}
/**
* Stop a Stream. Must be called after
* {@link KickflipApiClient#createNewUser(KickflipCallback)} and
* {@link KickflipApiClient#startStream(Stream, KickflipCallback)}
*
* @param cb This callback will receive a Stream subclass in {@link KickflipCallback#onSuccess(Object)}}
* depending on the Kickflip account type. Implementors should
* check if the response is instanceof HlsStream, etc.
*/
@DebugLog
public void stopStream(@NonNull Stream stream,
@Nullable final KickflipCallback<Stream> cb) {
stopStream(getActiveUser(), stream, cb);
}
/**
* Stop a Stream owned by the given Kickflip User.
*
* @param cb This callback will receive a Stream subclass in #onSuccess(response)
* depending on the Kickflip account type. Implementors should
* check if the response is instanceof HlsStream, etc.
*/
@DebugLog
private void stopStream(@NonNull User user,
@NonNull Stream stream,
@Nullable final KickflipCallback<Stream> cb) {
checkNotNull(user);
checkNotNull(stream);
// TODO: Add start / stop lat lon to Stream?
mService.stopStream(stream.getStreamId(),
user.getUUID(),
stream.getLatitude(),
stream.getLongitude())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to get user. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<Stream>() {
@Override
public void call(Stream stream) {
if (cb != null) cb.onSuccess(stream);
}
});
}
/**
* Send Stream Metadata for a {@link Stream}.
* The target Stream must be owned by the User created with {@link KickflipApiClient#createNewUser(KickflipCallback)}
* from this KickflipApiClient.
*
* @param stream the {@link Stream} to get Meta data for
* @param cb A callback to receive the updated Stream upon request completion
*/
@DebugLog
public void setStreamInfo(@NonNull Stream stream,
@Nullable final KickflipCallback<Stream> cb) {
checkNotNull(stream);
mService.setStreamInfo(stream.getStreamId(),
getActiveUser().getUUID(),
stream.getLatitude(), stream.getLongitude(),
stream.getTitle(),
stream.getDescription(),
stream.getExtraInfoString(),
stream.getCity(),
stream.getState(),
stream.getCountry(),
stream.getThumbnailUrl(),
stream.isPrivate(),
stream.isDeleted())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to set stream info. Reason: " + throwable.getMessage();
Log.e(TAG, "Failed to set stream info ", throwable);
}
})
.subscribe(new Action1<Stream>() {
@Override
public void call(Stream stream) {
if (cb != null) cb.onSuccess(stream);
}
});
}
/**
* Get Stream Metadata for a a public {@link Stream}.
* The target Stream must belong a User of your Kickflip app.
*
* @param streamId the stream id to get info for
* @param cb A callback to receive the updated Stream upon request completion
*/
@DebugLog
public void getStreamInfo(@NonNull String streamId, @Nullable final KickflipCallback<Stream> cb) {
checkNotNull(streamId);
mService.getStreamInfo(streamId)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to get stream info. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<Stream>() {
@Override
public void call(Stream stream) {
if (cb != null) cb.onSuccess(stream);
}
});
}
/**
* Get Stream Metadata for a a public {@link Stream}.
* The target Stream must belong a User of your Kickflip app.
*
* @param streamId the stream id to get info for
* @return an Observable for the requested {@link Stream}
*/
@DebugLog
public Observable<Stream> getStreamInfo(@NonNull String streamId) {
checkNotNull(streamId);
return mService.getStreamInfo(streamId);
}
/**
* Flag a {@link Stream}. Used when the active Kickflip User does not own the Stream.
* <p/>
* To delete a recording the active Kickflip User owns, use
* {@link KickflipApiClient#setStreamInfo(Stream, KickflipCallback)}
*
* @param stream The Stream to flag.
* @param cb A callback to receive the result of the flagging operation.
*/
@DebugLog
public void flagStream(@NonNull Stream stream, @Nullable final KickflipCallback cb) {
checkNotNull(stream);
mService.flagStream(stream.getStreamId(), getActiveUser().getUUID())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to flag stream. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<Stream>() {
@Override
public void call(Stream stream) {
if (cb != null) cb.onSuccess(stream);
}
});
}
/**
* Get a List of {@link Stream} objects created by the given Kickflip User.
*
* @param username the target Kickflip username
* @param cb A callback to receive the resulting List of Streams
*/
@DebugLog
public void getStreamsByUsername(@NonNull String username,
int pageNumber,
int itemsPerPage,
@Nullable final KickflipCallback<StreamList> cb) {
checkNotNull(username);
mService.getStreamsByUser(getActiveUser().getUUID(),
username, itemsPerPage, pageNumber)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to get streams by user. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<StreamList>() {
@Override
public void call(StreamList streams) {
if (cb != null) cb.onSuccess(streams);
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
Log.e(TAG, "Error processing callback", throwable);
}
});
}
/**
* Get a List of {@link Stream}s containing a keyword.
* <p/>
* This method searches all public recordings made by Users of your Kickflip app.
*
* @param keyword The String keyword to query
* @param cb A callback to receive the resulting List of Streams
*/
@DebugLog
public void getStreamsByKeyword(@NonNull String keyword, int pageNumber, int itemsPerPage,
@Nullable final KickflipCallback<StreamList> cb) {
checkNotNull(keyword);
mService.getStreamsByKeyword(getActiveUser().getUUID(),
keyword, itemsPerPage, pageNumber)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to get streams by keyword. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<StreamList>() {
@Override
public void call(StreamList streams) {
if (cb != null) cb.onSuccess(streams);
}
});
}
/**
* Get a List of {@link Stream}s near a geographic location.
* <p/>
* This method searches all public recordings made by Users of your Kickflip app.
*
* @param location The target Location
* @param radius The target Radius in meters
* @param cb A callback to receive the resulting List of Streams
*/
@DebugLog
public void getStreamsByLocation(@NonNull Location location, int radius, int pageNumber, int itemsPerPage,
@Nullable final KickflipCallback<StreamList> cb) {
checkNotNull(location);
mService.getStreamsByLocation(getActiveUser().getUUID(),
location.getLatitude(), location.getLongitude(), radius, itemsPerPage, pageNumber)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
String failMsg = "Failed to get streams by geo. Reason: " + throwable.getMessage();
Log.e(TAG, failMsg, throwable);
if (cb != null) cb.onError(new KickflipException(failMsg, 1));
}
})
.subscribe(new Action1<StreamList>() {
@Override
public void call(StreamList streams) {
if (cb != null) cb.onSuccess(streams);
}
});
}
/**
* Get the current active Kickflip User. If no User has been created, returns null.
* <p/>
* This will be the User created on the last call to
* {@link KickflipApiClient#createNewUser(KickflipCallback)}
* <p/>
* The result of this function is guaranteed to be not null after {@link #getOrCreateActiveUser()}
* succeeds
*
*/
@DebugLog
public User getActiveUser() {
SharedPreferences prefs = getStorage();
if (prefs.contains("uuid") && prefs.contains("name")) {
return new User(
prefs.getString("app_name", ""),
prefs.getString("name", ""),
prefs.getString("uuid", ""),
null);
} else {
return null;
}
}
/**
* Check if a Stream is owned by the active Kickflip User.
*
* @param stream the Stream to test.
* @return true if the active Kickflip User owns the Stream. false otherwise.
*/
@DebugLog
public boolean activeUserOwnsStream(Stream stream) {
return getActiveUser().getName().equals(stream.getOwnerName());
}
@DebugLog
private void storeUser(User user, String password) {
getStorage().edit()
.putString("app_name", user.getApp())
.putString("name", user.getName())
.putString("password", password)
.putString("uuid", user.getUUID())
.apply();
}
private SharedPreferences getStorage() {
return mContext.getSharedPreferences("kfsw", Context.MODE_PRIVATE);
}
private String generateRandomPassword() {
return new BigInteger(130, new SecureRandom()).toString(32);
}
}
| 41.437824
| 140
| 0.552923
|
f97730a2a2b964a13b5f898f101b61474ec2fe61
| 924
|
package com.cloud.legacymodel.communication.answer;
import java.util.HashMap;
public class ClusterVMMetaDataSyncAnswer extends Answer {
private final long _clusterId;
private final HashMap<String, String> _vmMetaDatum;
private boolean _isExecuted = false;
public ClusterVMMetaDataSyncAnswer(final long clusterId, final HashMap<String, String> vmMetaDatum) {
_clusterId = clusterId;
_vmMetaDatum = vmMetaDatum;
result = true;
}
// this is here because a cron command answer is being sent twice
// AgentAttache.processAnswers
// AgentManagerImpl.notifyAnswersToMonitors
public boolean isExecuted() {
return _isExecuted;
}
public void setExecuted() {
_isExecuted = true;
}
public long getClusterId() {
return _clusterId;
}
public HashMap<String, String> getVMMetaDatum() {
return _vmMetaDatum;
}
}
| 26.4
| 105
| 0.693723
|
35ba23bae8b9980677a1a7c7645d9a5889be3c1e
| 1,060
|
/**
*/
package de.darwinspl.feature.evolution.evolutionoperation.impl;
import de.darwinspl.feature.evolution.evolutionoperation.DwEvolutionOperationFeatureVersionDelete;
import de.darwinspl.feature.evolution.evolutionoperation.EvolutionoperationPackage;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Dw Evolution Operation Feature Version Delete</b></em>'.
* <!-- end-user-doc -->
*
* @generated
*/
public class DwEvolutionOperationFeatureVersionDeleteImpl extends DwEvolutionOperationFeatureVersionImpl implements DwEvolutionOperationFeatureVersionDelete {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DwEvolutionOperationFeatureVersionDeleteImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return EvolutionoperationPackage.Literals.DW_EVOLUTION_OPERATION_FEATURE_VERSION_DELETE;
}
} //DwEvolutionOperationFeatureVersionDeleteImpl
| 27.894737
| 158
| 0.75
|
46dda97a36d234449a88cf81cc6aaa41b4d4ef6a
| 2,461
|
package com.dtone.dvs.dto;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.dtone.dvs.util.Constants;
public class ProductFilter {
private ProductType type;
private Long serviceId;
private String countryIsoCode;
private Long operatorId;
private String region;
private List<BenefitTypes> benefitTypes;
public ProductType getType() {
return type;
}
public void setType(ProductType type) {
this.type = type;
}
public Long getServiceId() {
return serviceId;
}
public void setServiceId(Long serviceId) {
this.serviceId = serviceId;
}
public String getCountryIsoCode() {
return countryIsoCode;
}
public void setCountryIsoCode(String countryIsoCode) {
this.countryIsoCode = countryIsoCode;
}
public Long getOperatorId() {
return operatorId;
}
public void setOperatorId(Long operatorId) {
this.operatorId = operatorId;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public List<BenefitTypes> getBenefitTypes() {
return benefitTypes;
}
public void setBenefitTypes(List<BenefitTypes> benefitTypes) {
this.benefitTypes = benefitTypes;
}
public Map<String, String> getQueryParameterMap() {
Map<String, String> queryParameterMap = new HashMap<>();
if (null != type) {
queryParameterMap.put(Constants.TYPE, type.toString());
}
if (null != serviceId && serviceId > 0L) {
queryParameterMap.put(Constants.SERVICE_ID, String.valueOf(serviceId));
}
if (null != countryIsoCode) {
queryParameterMap.put(Constants.COUNTRY_ISO_CODE, countryIsoCode);
}
if (null != operatorId && operatorId > 0L) {
queryParameterMap.put(Constants.OPERATOR_ID, String.valueOf(operatorId));
}
if (null != region) {
queryParameterMap.put(Constants.REGION, region);
}
if (null != benefitTypes) {
queryParameterMap.put(Constants.BENEFIT_TYPES_QP,
benefitTypes.toString().replace(Constants.RIGHT_BRACKET, Constants.EMPTY_STRING)
.replace(Constants.LEFT_BRACKET, Constants.EMPTY_STRING).replaceAll(Constants.SINGLE_SPACE, Constants.EMPTY_STRING));
}
if (queryParameterMap.isEmpty()) {
return null;
}
return queryParameterMap;
}
@Override
public String toString() {
return "ProductFilter [serviceId=" + serviceId + ", countryIsoCode=" + countryIsoCode + ", operatorId="
+ operatorId + ", region=" + region + ", benefitTypes=" + benefitTypes + "]";
}
}
| 21.587719
| 124
| 0.72369
|
924bc6d045c6b5b78afaac09d202d4d74f7e332d
| 5,068
|
package com.shc.ld34.game;
import com.shc.silenceengine.audio.Sound;
import com.shc.silenceengine.core.ResourceLoader;
import com.shc.silenceengine.core.SilenceEngine;
import com.shc.silenceengine.graphics.Sprite;
import com.shc.silenceengine.graphics.TrueTypeFont;
import com.shc.silenceengine.graphics.opengl.Texture;
import com.shc.silenceengine.io.FilePath;
/**
* @author Sri Harsha Chilakapati
*/
public final class Resources
{
private static ResourceLoader loader;
private static void resourceLoadCallback(String info, float percentage)
{
loader.defaultRenderProgressCallback(info, percentage);
if (percentage >= 50)
loader.setLogo(Textures.LOGO);
}
public static void init()
{
loader = new ResourceLoader();
Textures.LOGO = Texture.fromFilePath(FilePath.getResourceFile("resources/Logo.png"));
int texKeyAltID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/key_alt.png"));
int texBackgroundID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/Background.png"));
int texBulletID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/bullet.png"));
int texShipBlackID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/space_ship_black.png"));
int texShipGoldID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/space_ship_gold.png"));
int texShipWhiteID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/space_ship_white.png"));
int texShieldID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/shield.png"));
int texMotherShipID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/space_ship_mother.png"));
int texNewWaveID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/new_wave.png"));
int texShield2ID = loader.loadResource(Texture.class, FilePath.getResourceFile("resources/secure_shield.png"));
int sndMusicID = loader.loadResource(Sound.class, FilePath.getResourceFile("resources/music.ogg"));
int sndShootID = loader.loadResource(Sound.class, FilePath.getResourceFile("resources/shoot.wav"));
int sndExplosionID = loader.loadResource(Sound.class, FilePath.getResourceFile("resources/explosion.wav"));
loader.setProgressRenderCallback(Resources::resourceLoadCallback);
loader.startLoading();
Textures.KEY_ALT = loader.getResource(texKeyAltID);
Textures.BACKGROUND = loader.getResource(texBackgroundID);
Textures.BULLET = loader.getResource(texBulletID);
Textures.SHIP_BLACK = loader.getResource(texShipBlackID);
Textures.SHIP_GOLD = loader.getResource(texShipGoldID);
Textures.SHIP_WHITE = loader.getResource(texShipWhiteID);
Textures.SHIELD = loader.getResource(texShieldID);
Textures.MOTHER_SHIP = loader.getResource(texMotherShipID);
Textures.NEW_WAVE = loader.getResource(texNewWaveID);
Textures.SHIELD2 = loader.getResource(texShield2ID);
Sounds.MUSIC = loader.getResource(sndMusicID);
Sounds.SHOOT = loader.getResource(sndShootID);
Sounds.EXPLOSION = loader.getResource(sndExplosionID);
Sounds.MUSIC.setLooping(true);
Sprites.BULLET = new Sprite(Textures.BULLET);
Sprites.SHIELD = new Sprite(Textures.SHIELD);
Sprites.SHIP_BLACK = new Sprite(Textures.SHIP_BLACK);
Sprites.SHIP_GOLD = new Sprite(Textures.SHIP_GOLD);
Sprites.SHIP_WHITE = new Sprite(Textures.SHIP_WHITE);
Sprites.MOTHER_SHIP = new Sprite(Textures.MOTHER_SHIP);
Sprites.NEW_WAVE = new Sprite(Textures.NEW_WAVE);
Sprites.SHIELD2 = new Sprite(Textures.SHIELD2);
((TrueTypeFont) SilenceEngine.graphics.getGraphics2D().getFont()).setStyle(TrueTypeFont.STYLE_BOLD);
}
public static void dispose()
{
Textures.LOGO.dispose();
loader.dispose();
}
public static final class Textures
{
public static Texture BACKGROUND;
public static Texture LOGO;
public static Texture BULLET;
public static Texture SHIP_BLACK;
public static Texture SHIP_GOLD;
public static Texture SHIP_WHITE;
public static Texture SHIELD;
public static Texture KEY_ALT;
public static Texture MOTHER_SHIP;
public static Texture NEW_WAVE;
public static Texture SHIELD2;
}
public static final class Sounds
{
public static Sound MUSIC;
public static Sound SHOOT;
public static Sound EXPLOSION;
}
public static final class Sprites
{
public static Sprite BULLET;
public static Sprite SHIP_BLACK;
public static Sprite SHIP_GOLD;
public static Sprite SHIP_WHITE;
public static Sprite SHIELD;
public static Sprite MOTHER_SHIP;
public static Sprite NEW_WAVE;
public static Sprite SHIELD2;
}
}
| 42.588235
| 126
| 0.718627
|
23c30943e4effd3b776e3b97be47f03a8c197f62
| 9,392
|
/**
Copyright (c) 2011, SOCIETIES Consortium (WATERFORD INSTITUTE OF TECHNOLOGY (TSSG), HERIOT-WATT UNIVERSITY (HWU), SOLUTA.NET
(SN), GERMAN AEROSPACE CENTRE (Deutsches Zentrum fuer Luft- und Raumfahrt e.V.) (DLR), Zavod za varnostne tehnologije
informacijske družbe in elektronsko poslovanje (SETCCE), INSTITUTE OF COMMUNICATION AND COMPUTER SYSTEMS (ICCS), LAKE
COMMUNICATIONS (LAKE), INTEL PERFORMANCE LEARNING SOLUTIONS LTD (INTEL), PORTUGAL TELECOM INOVAÇÃO, SA (PTIN), IBM Corp (IBM),
INSTITUT TELECOM (ITSUD), AMITEC DIACHYTI EFYIA PLIROFORIKI KAI EPIKINONIES ETERIA PERIORISMENIS EFTHINIS (AMITEC), TELECOM
ITALIA S.p.a.(TI), TRIALOG (TRIALOG), Stiftelsen SINTEF (SINTEF), NEC EUROPE LTD (NEC))
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.societies.css.directory;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.societies.api.schema.css.directory.CssAdvertisementRecord;
import org.societies.api.css.directory.ICssDirectory;
import org.societies.css.directory.model.CssAdvertisementRecordEntry;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
public class CssDirectory implements ICssDirectory {
private SessionFactory sessionFactory;
private static Logger log = LoggerFactory.getLogger(CssDirectory.class);
/**
* @return the sessionFactory
*/
public SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* @param sessionFactory the sessionFactory to set
*/
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public CssDirectory() {
log.info("CSS Directory bundle instantiated.");
}
/*
* (non-Javadoc)
*
* @see
* org.societies.api.css.directory.ICssDirectory#addCssAdvertisementRecord
* (org.societies.api.schema.css.directory.CssAdvertisementRecord)
*/
@Override
public void addCssAdvertisementRecord(CssAdvertisementRecord cssAdRec) {
Session session = sessionFactory.openSession();
CssAdvertisementRecordEntry tmpEntry = null;
Transaction t = session.beginTransaction();
try {
tmpEntry = new CssAdvertisementRecordEntry(cssAdRec.getName(),
cssAdRec.getId(), cssAdRec.getUri());
session.save(tmpEntry);
t.commit();
log.debug("Css Advertisement Record Saved.");
} catch (Exception e) {
t.rollback();
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.societies.api.css.directory.ICssDirectory#deleteCssAdvertisementRecord
* (org.societies.api.schema.css.directory.CssAdvertisementRecord)
*/
@Override
public void deleteCssAdvertisementRecord(CssAdvertisementRecord cssAdRec) {
Session session = sessionFactory.openSession();
CssAdvertisementRecordEntry tmpEntry = null;
Transaction t = session.beginTransaction();
try {
tmpEntry = new CssAdvertisementRecordEntry(cssAdRec.getName(),
cssAdRec.getId(), cssAdRec.getUri());
session.delete(tmpEntry);
t.commit();
log.debug("Css Advertisement Record deleted.");
} catch (Exception e) {
t.rollback();
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.societies.api.css.directory.ICssDirectory#findAllCssAdvertisementRecords
* ()
*/
@SuppressWarnings("unchecked")
@Override
@Async
public Future<List<CssAdvertisementRecord>> findAllCssAdvertisementRecords() {
Session session = sessionFactory.openSession();
List<CssAdvertisementRecordEntry> tmpAdvertList = new ArrayList<CssAdvertisementRecordEntry>();
List<CssAdvertisementRecord> returnList = new ArrayList<CssAdvertisementRecord>();
CssAdvertisementRecord record = null;
try {
tmpAdvertList = session.createCriteria(
CssAdvertisementRecordEntry.class).list();
for (CssAdvertisementRecordEntry entry : tmpAdvertList) {
record = new CssAdvertisementRecord();
record.setName(entry.getName());
record.setId(entry.getId());
record.setUri(entry.getUri());
returnList.add(record);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return new AsyncResult<List<CssAdvertisementRecord>>(returnList);
}
/*
* (non-Javadoc)
*
* @see
* org.societies.api.css.directory.ICssDirectory#findForAllCss(org.societies
* .api.schema.css.directory.CssAdvertisementRecord)
*/
@SuppressWarnings("unchecked")
@Override
@Async
public Future<List<CssAdvertisementRecord>> findForAllCss(
CssAdvertisementRecord filterCss) {
Session session = sessionFactory.openSession();
List<CssAdvertisementRecordEntry> tmpAdvertList = new ArrayList<CssAdvertisementRecordEntry>();
List<CssAdvertisementRecord> returnList = new ArrayList<CssAdvertisementRecord>();
CssAdvertisementRecord record = null;
try {
tmpAdvertList = session.createCriteria(
CssAdvertisementRecordEntry.class).list();
for (CssAdvertisementRecordEntry entry : tmpAdvertList) {
if (entry.getName().contains(filterCss.getName())) {
record = new CssAdvertisementRecord();
record.setName(entry.getName());
record.setId(entry.getId());
record.setUri(entry.getUri());
returnList.add(record);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return new AsyncResult<List<CssAdvertisementRecord>>(returnList);
}
/*
* (non-Javadoc)
*
* @see
* org.societies.api.css.directory.ICssDirectory#updateCssAdvertisementRecord(org.societies
* .api.schema.css.directory.CssAdvertisementRecord,
* org.societies.api.schema.css.directory.CssAdvertisementRecord)
*/
@Override
public void updateCssAdvertisementRecord(CssAdvertisementRecord oldCssValues,
CssAdvertisementRecord updatedCssValues) {
Session session = sessionFactory.openSession();
CssAdvertisementRecordEntry tmpEntry = null;
Transaction t = session.beginTransaction();
try {
tmpEntry = new CssAdvertisementRecordEntry(updatedCssValues.getName(),
updatedCssValues.getId(), updatedCssValues.getUri());
session.saveOrUpdate(tmpEntry);
t.commit();
log.debug("Css Advertisement Record updated.");
} catch (Exception e) {
t.rollback();
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.societies.api.css.directory.ICssDirectory#findAllCssAdvertisementRecords
* ()
*/
@SuppressWarnings("unchecked")
@Override
@Async
public Future<List<CssAdvertisementRecord>> searchByID(List<String> cssIds) {
Session session = sessionFactory.openSession();
List<CssAdvertisementRecordEntry> tmpAdvertList = new ArrayList<CssAdvertisementRecordEntry>();
List<CssAdvertisementRecord> returnList = new ArrayList<CssAdvertisementRecord>();
CssAdvertisementRecord record = null;
try {
if (cssIds != null && (cssIds.size() > 0))
{
tmpAdvertList = session.createCriteria(CssAdvertisementRecordEntry.class).
add(Restrictions.in("id",cssIds)).list();
for (CssAdvertisementRecordEntry entry : tmpAdvertList) {
record = new CssAdvertisementRecord();
record.setName(entry.getName());
record.setId(entry.getId());
record.setUri(entry.getUri());
returnList.add(record);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
return new AsyncResult<List<CssAdvertisementRecord>>(returnList);
}
}
| 30.394822
| 128
| 0.7171
|
7819ad4e7c81eaea468ce3445b2f70d86db8f8c7
| 3,208
|
package com.fengwenyi.erwinmessage.controller;
import com.fengwenyi.api.result.ResultTemplate;
import com.fengwenyi.erwinmessage.service.IMailService;
import com.fengwenyi.erwinmessage.service.IRedisService;
import com.fengwenyi.erwinmessage.util.CacheKeyUtils;
import com.fengwenyi.erwinmessage.util.CodeUtils;
import com.google.code.kaptcha.Producer;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* @author <a href="https://www.fengwenyi.com">Erwin Feng</a>
* @since 2021-07-31
*/
@Tag(name = "通用 API")
@RestController
@RequestMapping("/common")
public class CommonController {
private Producer producer;
private IRedisService redisService;
private IMailService mailService;
@Autowired
public void setProducer(Producer producer) {
this.producer = producer;
}
@Autowired
public void setRedisService(IRedisService redisService) {
this.redisService = redisService;
}
@Autowired
public void setMailService(IMailService mailService) {
this.mailService = mailService;
}
// 图形验证码
@Operation(summary = "图形验证码")
@GetMapping("/captcha.jpg")
public void captcha(String account, HttpServletResponse response) throws IOException {
//生成文字验证码
String code = producer.createText();
redisService.set(CacheKeyUtils.genCaptchaKey(account), code);
//redisService.set(uuid, code);
//session.setAttribute("code",code);
response.setHeader("Cache-Control", "no-store,no-cache");
response.setContentType("image/jpeg");
BufferedImage image = producer.createImage(code);
ServletOutputStream outputStream = response.getOutputStream();
ImageIO.write(image, "jpg", outputStream);
IOUtils.closeQuietly(outputStream);
}
@Operation(summary = "发送邮箱验证码")
@GetMapping("/sendMailCode")
public ResultTemplate<Void> sendMailCode(String account, String captcha) {
String cacheCaptcha = redisService.get(CacheKeyUtils.genCaptchaKey(account));
if (!StringUtils.hasText(cacheCaptcha) || !cacheCaptcha.equals(captcha)) {
if (StringUtils.hasText(cacheCaptcha)) {
redisService.delete(CacheKeyUtils.genCaptchaKey(account));
}
return ResultTemplate.fail("图形验证码不正确");
}
String mailCode = CodeUtils.gen(4);
redisService.set(CacheKeyUtils.genMailCodeKey(account), mailCode);
boolean rs = mailService.sendText(account, "验证码", mailCode);
if (rs) {
return ResultTemplate.success();
}
return ResultTemplate.fail("验证码发送失败");
}
}
| 34.494624
| 90
| 0.721322
|
3f36175f4428706d62800498a0b727431749bce5
| 834
|
package br.com.zupacademy.templateproposta.cartoes;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.validation.constraints.NotBlank;
@Entity
public class Bloqueios {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
private String ipCliente;
@NotBlank
private String agenteUser;
private LocalDateTime criadoEm = LocalDateTime.now();
@ManyToOne
private Cartoes cartao;
@Deprecated
public Bloqueios() {
}
public Bloqueios(@NotBlank String ipCliente, @NotBlank String agenteUser, Cartoes cartao) {
super();
this.ipCliente = ipCliente;
this.agenteUser = agenteUser;
this.cartao = cartao;
}
}
| 21.947368
| 92
| 0.782974
|
4cca78bbe1ddb93282fd948a1357657d0afb6350
| 3,121
|
package com.tts;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Math {
public static void doMath(List<Integer> nums) {
System.out.println("The max number of your entered numbers is:"+max(nums));
System.out.println("The min number of your entered numbers is:"+min(nums));
System.out.println("The sum of your entered numbers is:"+sum(nums));
System.out.println("The average of your entered numbers is:"+avrage(nums));
System.out.println("The product of your entered numbers is:"+product(nums));
}
public static int max(List<Integer> nums) {
int max = nums.get(0); //nums[0]
for (int i = 0; i < nums.size(); i++)
if (nums.get(i) > max)
max = nums.get(i);
return max;
}
public static int min(List<Integer> nums) {
int min = nums.get(0);
for (int i = 0; i < nums.size(); i++)
if (nums.get(i) < min)
min = nums.get(i);
return min;
}
public static int sum(List<Integer> nums) {
int sum = 0;
for (int i = 0; i <nums.size(); i++)
sum+=nums.get(i);
return sum;
}
public static int product(List<Integer> nums) {
int mult = 1;
for (int i = 0; i <nums.size(); i++)
mult*=nums.get(i);
return mult;
}
public static double avrage(List<Integer> nums) {
int sum = 0;
for (int i = 0; i <nums.size(); i++)
sum+=nums.get(i);
return sum/nums.size();
}
public static void main(String[] args) {
int number;
List<Integer> numbers=new ArrayList<>();
Scanner scanner=new Scanner(System.in);
System.out.println("Please enter 5 numbers:");
for(int i=0;i<5;i++){
try{
System.out.printf("Number#%d: ", (i+1));
number=scanner.nextInt();
numbers.add(number);
}
catch (Error e){
System.out.println("Error:"+e.getMessage());
}
}
doMath(numbers);
// int sum=0;
// int mult=1;
// int max=0;
// int min=0;
// int[] myarr= new int[5];
// Scanner scanner1=new Scanner(System.in);
// for(int i=0;i<5;i++){
// myarr[i]=scanner1.nextInt();
// }
// max=myarr[0];
// min=myarr[0];
// for(int i=0;i<5;i++){
// if(myarr[i]>max){
// max=myarr[i];
// }
// if(myarr[i]<min){
// min=myarr[i];
// }
// sum=myarr[i]+sum;
// mult=mult*myarr[i];
// System.out.println("The max number of your entered numbers is:"+max);
// System.out.println("The min number of your entered numbers is:"+min);
// System.out.println("The sum of your entered numbers is:"+sum);
// System.out.println("The product of your entered numbers is:"+mult);
// }
}
}
| 32.510417
| 85
| 0.493432
|
8c9764881e306cca6947970ffa657398152fd5ab
| 2,702
|
// This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.baasplus.models;
import com.aliyun.tea.*;
public class QueryInvoicesocrVatinvoiceResponse extends TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
@NameInMap("req_msg_id")
public String reqMsgId;
// 结果码,一般OK表示调用成功
@NameInMap("result_code")
public String resultCode;
// 异常信息的文本描述
@NameInMap("result_msg")
public String resultMsg;
// 算法错误信息
@NameInMap("algo_msg")
public String algoMsg;
// 算法异常错误码
//
@NameInMap("algo_ret")
public String algoRet;
// 框架错误信息
//
@NameInMap("message")
public String message;
// 算法结果,JSON String
@NameInMap("result")
public String result;
// 框架inference服务错误码,0为正常
@NameInMap("ret")
public String ret;
public static QueryInvoicesocrVatinvoiceResponse build(java.util.Map<String, ?> map) throws Exception {
QueryInvoicesocrVatinvoiceResponse self = new QueryInvoicesocrVatinvoiceResponse();
return TeaModel.build(map, self);
}
public QueryInvoicesocrVatinvoiceResponse setReqMsgId(String reqMsgId) {
this.reqMsgId = reqMsgId;
return this;
}
public String getReqMsgId() {
return this.reqMsgId;
}
public QueryInvoicesocrVatinvoiceResponse setResultCode(String resultCode) {
this.resultCode = resultCode;
return this;
}
public String getResultCode() {
return this.resultCode;
}
public QueryInvoicesocrVatinvoiceResponse setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
return this;
}
public String getResultMsg() {
return this.resultMsg;
}
public QueryInvoicesocrVatinvoiceResponse setAlgoMsg(String algoMsg) {
this.algoMsg = algoMsg;
return this;
}
public String getAlgoMsg() {
return this.algoMsg;
}
public QueryInvoicesocrVatinvoiceResponse setAlgoRet(String algoRet) {
this.algoRet = algoRet;
return this;
}
public String getAlgoRet() {
return this.algoRet;
}
public QueryInvoicesocrVatinvoiceResponse setMessage(String message) {
this.message = message;
return this;
}
public String getMessage() {
return this.message;
}
public QueryInvoicesocrVatinvoiceResponse setResult(String result) {
this.result = result;
return this;
}
public String getResult() {
return this.result;
}
public QueryInvoicesocrVatinvoiceResponse setRet(String ret) {
this.ret = ret;
return this;
}
public String getRet() {
return this.ret;
}
}
| 24.342342
| 107
| 0.657661
|
94ee57e76c45b21ff8d29f9c3680806623289bb8
| 2,300
|
package sonar.calculator.mod.client.gui.machines;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import sonar.calculator.mod.common.containers.ContainerPowerCube;
import sonar.calculator.mod.common.tileentity.machines.TileEntityAdvancedPowerCube;
import sonar.calculator.mod.common.tileentity.machines.TileEntityPowerCube;
import sonar.core.client.gui.GuiSonarTile;
import sonar.core.helpers.FontHelper;
import java.text.DecimalFormat;
import java.util.ArrayList;
public class GuiPowerCube extends GuiSonarTile {
public static final ResourceLocation bground = new ResourceLocation("Calculator:textures/gui/guipowercube.png");
public TileEntityPowerCube entity;
public GuiPowerCube(InventoryPlayer inventoryPlayer, TileEntityPowerCube entity) {
super(new ContainerPowerCube(inventoryPlayer, entity), entity);
this.entity = entity;
}
@Override
public void drawGuiContainerForegroundLayer(int x, int y) {
super.drawGuiContainerForegroundLayer(x, y);
FontHelper.textCentre(FontHelper.translate(entity.getName()), xSize, 6, 0);
FontHelper.textCentre(FontHelper.formatStorage(entity.storage.getEnergyLevel()), this.xSize, 64, 2);
if (x > guiLeft + 130 && x < guiLeft + 144 && y > guiTop + 60 && y < guiTop + 74) {
ArrayList<String> list = new ArrayList<>();
DecimalFormat df = new DecimalFormat("#.##");
list.add(TextFormatting.BLUE + "" + TextFormatting.UNDERLINE + "Machine Stats");
list.add("Stored: " + entity.storage.getEnergyLevel() + " RF");
list.add("Max Input: " + df.format(entity.storage.getMaxReceive()) + " rf/t");
list.add("Max Output: " + df.format(entity instanceof TileEntityAdvancedPowerCube ? entity.storage.getMaxExtract() : 0) + " rf/t");
drawSpecialToolTip(list, x, y, fontRenderer);
}
}
@Override
protected void drawGuiContainerBackgroundLayer(float var1, int var2, int var3) {
super.drawGuiContainerBackgroundLayer(var1, var2, var3);
int k = (int)(this.entity.storage.getEnergyLevel() * 78 / this.entity.storage.getFullCapacity());
int j = 78 - k;
drawTexturedModalRect(this.guiLeft + 49, this.guiTop + 63, 176, 0, k, 10);
}
@Override
public ResourceLocation getBackground() {
return bground;
}
}
| 42.592593
| 134
| 0.752609
|
1a6f11d8e2249120614319c7878a1d5887a12c11
| 4,895
|
package pcl.OpenFM.player;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import net.sourceforge.jaad.aac.Decoder;
import net.sourceforge.jaad.aac.SampleBuffer;
import net.sourceforge.jaad.adts.ADTSDemultiplexer;
import pcl.OpenFM.OpenFM;
import pcl.OpenFM.network.PacketHandler;
import pcl.OpenFM.network.message.MessageRadioPlaying;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.sourceforge.jaad.Radio;
import net.sourceforge.jaad.adts.ADTSDemultiplexer;
public class AACPlayer {
private final Deque<SourceDataLine> linesPlaying = new ConcurrentLinkedDeque<>();
private float volume = 0.0F;
private int posX;
private int posY;
private int posZ;
private World world;
private String streamURL;
private SourceDataLine line;
public void setID(World world, int x, int y, int z) {
// TODO Auto-generated method stub
}
public void play(String streamURL) throws IOException, LineUnavailableException, URISyntaxException {
this.streamURL = streamURL;
final SampleBuffer buf = new SampleBuffer();
/* OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(streamURL)
.build();
Response response = client.newCall(request).execute();
InputStream stream = response.body().byteStream();
BufferedInputStream bis = new BufferedInputStream(response.body().byteStream());
try (final AudioInputStream in = getAudioInputStream(bis)) {
} catch (UnsupportedAudioFileException | IOException e) {
PacketHandler.INSTANCE.sendToServer(new MessageRadioPlaying(this.posX, this.posY, this.posZ, false).wrap());
FMLClientHandler.instance().getClient().thePlayer.addChatMessage(new TextComponentString(I18n.translateToLocal("msg.OpenFM.invalid_link")));
OpenFM.logger.error(e);
throw new IllegalStateException(e);
}*/
SourceDataLine line = null;
byte[] b;
try {
final URI uri = new URI(this.streamURL);
final Socket sock = new Socket(uri.getHost(), uri.getPort()>0 ? uri.getPort() : 80);
//send HTTP request
final PrintStream out = new PrintStream(sock.getOutputStream());
String path = uri.getPath();
if(path==null||path.equals("")) path = "/";
if(uri.getQuery()!=null) path += "?"+uri.getQuery();
out.println("GET "+path+" HTTP/1.1");
out.println("Host: "+uri.getHost());
out.println();
//read response (skip header)
final DataInputStream in = new DataInputStream(sock.getInputStream());
String x;
do {
x = in.readLine();
}
while(x!=null&&!x.trim().equals(""));
final ADTSDemultiplexer adts = new ADTSDemultiplexer(in);
AudioFormat aufmt = new AudioFormat(adts.getSampleFrequency(), 16, adts.getChannelCount(), true, true);
final Decoder dec = new Decoder(adts.getDecoderSpecificInfo());
while(true) {
b = adts.readNextFrame();
dec.decodeFrame(b, buf);
if(line!=null&&formatChanged(line.getFormat(), buf)) {
//format has changed (e.g. SBR has started)
line.stop();
line.close();
line = null;
aufmt = new AudioFormat(buf.getSampleRate(), buf.getBitsPerSample(), buf.getChannels(), true, true);
}
if(line==null) {
line = AudioSystem.getSourceDataLine(aufmt);
line.open();
line.start();
}
b = buf.getData();
line.write(b, 0, b.length);
}
}
finally {
if(line!=null) {
line.stop();
line.close();
}
}
}
public boolean isPlaying() {
// TODO Auto-generated method stub
return line.isActive();
}
public void setVolume(float f) {
// TODO Auto-generated method stub
}
public float getVolume() {
// TODO Auto-generated method stub
return 0;
}
public void stop() {
line.drain();
line.stop();
line.close();
}
private static boolean formatChanged(AudioFormat af, SampleBuffer buf) {
return af.getSampleRate()!=buf.getSampleRate()
||af.getChannels()!=buf.getChannels()
||af.getSampleSizeInBits()!=buf.getBitsPerSample()
||af.isBigEndian()!=buf.isBigEndian();
}
}
| 30.030675
| 144
| 0.715424
|
e9a10785a3b208151d5c2920611e6d0b31af4a94
| 538
|
package com.java.concepts.enums;
import java.util.Arrays;
public class MainClass {
public static void main(String[] args) {
//HttpStatus enum
System.out.println(HttpStatus.CREATES.getStatusCode());
System.out.println(HttpStatus.CREATES.getStatusMessage());
System.out.println(HttpStatus.CREATES);
//Direction enum
System.out.println(Directions.EAST);
System.out.println(Directions.valueOf("EAST"));
System.out.println(Arrays.toString(Directions.values()));
}
}
| 26.9
| 66
| 0.678439
|
0902a15ca3386c321cd4e22acb91d3ada92febee
| 1,363
|
/**
* @info: MountainBaseMapper.java
* @copyright: 2019
*/
package com.github.biticcf.mountain.core.common.service;
import java.sql.SQLException;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
/**
* +MybatisPlus自定义基类,主要是禁用默认的带有分页功能的方法
* +主要因为其分页采用的是逻辑分页,效果不如PageHelper的物理分页好
*
* author: Daniel.Cao
* date: 2019年10月31日
* time: 上午09:10:47
*
* @param <T> 实体类泛型
*/
public interface MountainBaseMapper<T> extends BaseMapper<T> {
// 禁用MybatisPlus的分页功能,使用PageHelper的分页功能
@Deprecated
@Override
default <E extends IPage<T>> E selectPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
try {
throw new SQLException("Not Supported Method[selectPage]!");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
// 禁用MybatisPlus的分页功能,使用PageHelper的分页功能
@Deprecated
@Override
default <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
try {
throw new SQLException("Not Supported Method[selectMapsPage]!");
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
| 24.339286
| 125
| 0.735877
|
c15b8b01cf72a5c06ffee7d36ebf58bf9af5b30f
| 781
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cn.hanbell.oa.ejb;
import cn.hanbell.oa.comm.SuperEJBForEFGP;
import cn.hanbell.oa.entity.HKYX013;
import cn.hanbell.oa.entity.HKYX013Detail;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
/**
*
* @author C1749
*/
@Stateless
@LocalBean
public class HKYX013Bean extends SuperEJBForEFGP<HKYX013> {
@EJB
HKYX013DetailBean hKYX013DetailBean;
public HKYX013Bean() {
super(HKYX013.class);
}
public List<HKYX013Detail> getDetailList(String fsn) {
return hKYX013DetailBean.findByFSN(fsn);
}
}
| 21.694444
| 79
| 0.732394
|
ef3f1b4991198b86e5aa466fdeb2f16403dcd9c1
| 21,397
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package institucion.Views.Secretary;
import config.Secretary.HeaderAssignation;
import institucion.Controllers.CtrlSubject;
import institucion.Controllers.CtrlTeacher;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import javax.swing.AbstractAction;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
/**
*
* @author OscarT
*/
public class Assignation extends javax.swing.JFrame {
/**
* Creates new form Assignation
*/
public int teacherID;
private CtrlTeacher ctrlT;
private CtrlSubject ctrlS;
public Assignation() {
this.setUndecorated(true);
initComponents();
this.setLocationRelativeTo(null);
ctrlT = new CtrlTeacher();
ctrlS = new CtrlSubject();
}
/**
* 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() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
lblTitle = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
tabAssigned = new javax.swing.JTable();
jSeparator1 = new javax.swing.JSeparator();
jScrollPane2 = new javax.swing.JScrollPane();
tabSubjects = new javax.swing.JTable();
btnClose = new javax.swing.JButton();
lblSubtitle_one = new javax.swing.JLabel();
lblSubtitle_two = new javax.swing.JLabel();
lblYear = new javax.swing.JLabel();
cmbYear = new javax.swing.JComboBox();
btnAssign = new javax.swing.JButton();
lblGestion = new javax.swing.JLabel();
cmbGestion = new javax.swing.JComboBox();
jLabel1.setText("jLabel1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowOpened(java.awt.event.WindowEvent evt) {
formWindowOpened(evt);
}
});
jPanel1.setBackground(new java.awt.Color(102, 102, 255));
lblTitle.setFont(new java.awt.Font("Lao UI", 1, 24)); // NOI18N
lblTitle.setForeground(new java.awt.Color(255, 255, 255));
lblTitle.setText("Asignacion a Maestro");
tabAssigned.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane1.setViewportView(tabAssigned);
tabSubjects.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
tabSubjects.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
tabSubjectsMouseClicked(evt);
}
});
jScrollPane2.setViewportView(tabSubjects);
btnClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/close.png"))); // NOI18N
btnClose.setBorder(null);
btnClose.setBorderPainted(false);
btnClose.setContentAreaFilled(false);
btnClose.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnClose.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnCloseMouseClicked(evt);
}
});
lblSubtitle_one.setFont(new java.awt.Font("Lao UI", 1, 14)); // NOI18N
lblSubtitle_one.setForeground(new java.awt.Color(255, 255, 255));
lblSubtitle_one.setText("Materias asignadas: ");
lblSubtitle_two.setFont(new java.awt.Font("Lao UI", 1, 14)); // NOI18N
lblSubtitle_two.setForeground(new java.awt.Color(255, 255, 255));
lblSubtitle_two.setText("Materias:");
lblYear.setFont(new java.awt.Font("Lao UI", 1, 14)); // NOI18N
lblYear.setForeground(new java.awt.Color(255, 255, 255));
lblYear.setText("Anio:");
btnAssign.setFont(new java.awt.Font("Lao UI", 1, 18)); // NOI18N
btnAssign.setForeground(new java.awt.Color(255, 255, 255));
btnAssign.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icons/add.png"))); // NOI18N
btnAssign.setText("Asignar");
btnAssign.setBorder(null);
btnAssign.setBorderPainted(false);
btnAssign.setContentAreaFilled(false);
btnAssign.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btnAssign.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
btnAssign.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
btnAssign.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnAssignMouseClicked(evt);
}
});
lblGestion.setFont(new java.awt.Font("Lao UI", 1, 14)); // NOI18N
lblGestion.setForeground(new java.awt.Color(255, 255, 255));
lblGestion.setText("Gestion:");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnClose))
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 388, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(btnAssign)))
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(692, 692, 692))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lblSubtitle_one)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(lblYear)
.addGap(18, 18, 18)
.addComponent(cmbYear, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(lblGestion)
.addGap(18, 18, 18)
.addComponent(cmbGestion, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(lblSubtitle_two))))
.addGap(0, 0, Short.MAX_VALUE))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(87, 87, 87)
.addComponent(lblTitle)
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(lblTitle)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cmbYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblYear)
.addComponent(lblGestion)
.addComponent(cmbGestion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblSubtitle_two)
.addGap(8, 8, 8)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnAssign, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(11, 11, 11)
.addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(lblSubtitle_one)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(51, 51, 51)
.addComponent(btnClose)
.addGap(26, 26, 26))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 417, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
int teacherId = this.teacherID;
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH);
String gestion = (month < 6)?"I":"II";
this.setDataToTables(teacherId, year, gestion, false);
cmbYear.addItem("Seleccionar");
for(int i = year; i < year+2; i++){
cmbYear.addItem(i);
}
cmbGestion.addItem("Seleccionar");
cmbGestion.addItem("I");
cmbGestion.addItem("II");
}//GEN-LAST:event_formWindowOpened
private void btnCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCloseMouseClicked
this.setVisible(false);
}//GEN-LAST:event_btnCloseMouseClicked
private void btnAssignMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAssignMouseClicked
int teacherId = this.teacherID;
int year = 0;
String gestion = cmbGestion.getSelectedItem().toString();
if(gestion.equals("Seleccionar")){
gestion = "";
}
ArrayList<String> subjectsSelected = new ArrayList<String>();
try{
year = Integer.parseInt(cmbYear.getSelectedItem().toString());
}catch(NumberFormatException e){
year = 0;
}
if(tabSubjects.getSelectedRowCount() > 0){
int selectedRow[] = tabSubjects.getSelectedRows();
int i = 0;
for(int row: selectedRow){
subjectsSelected.add(tabSubjects.getValueAt(row, 0).toString());
i++;
}
Object[] info = ctrlT.assignTeacher(teacherId, subjectsSelected, year, gestion);
boolean flag = (Boolean)info[0];
if(!flag){
JOptionPane.showMessageDialog(this,
"Ingrese bien los datos.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}else{
ArrayList<String> assignedB = (ArrayList<String>) info[1];
String message = "Inscripcion exitosa!";
if(assignedB.size() > 0){
String extra = "";
for(int j = 0; j < assignedB.size(); j++){
extra += assignedB.get(j)+"\n";
}
if(assignedB.size() > 0){
message += "\nMaterias ya fueron asignadas anteriormente: \n"+extra;
}
}
JOptionPane.showMessageDialog(this,
message,
"Asignacion",
JOptionPane.INFORMATION_MESSAGE);
}
this.setDataToTables(teacherId, year, gestion, true);
}else{
JOptionPane.showMessageDialog(this,
"Seleccione una materia.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnAssignMouseClicked
private void tabSubjectsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabSubjectsMouseClicked
int row = tabSubjects.getSelectedRow();
if(row > -1){
int subjectId = Integer.parseInt(tabSubjects.getValueAt(tabSubjects.getSelectedRow(), 0).toString());
JPopupMenu menu = new JPopupMenu();
JMenuItem schedule = new JMenuItem(new AbstractAction("Mostrar Horarios") {
@Override
public void actionPerformed(ActionEvent e) {
String schedules = "";
schedules = ctrlT.getSubjectsForTeacher(subjectId);
JOptionPane.showMessageDialog(null,
"Los siguientes Horarios son: "+schedules,
"HORARIOS",
JOptionPane.INFORMATION_MESSAGE);
}
});
menu.add(schedule);
tabSubjects.setComponentPopupMenu(menu);
}
}//GEN-LAST:event_tabSubjectsMouseClicked
private void setDataToTables(int teacherId, int year,
String gestion, boolean assignation){
DefaultTableModel emptyModel = new DefaultTableModel();
if(!assignation){
/* Populating table Subjects (First) */
tabSubjects.setModel(emptyModel);
Object[][] subjects = {};
subjects = ctrlS.getAllSubjects();
String titlesS[] = {"id", "Nombre"};
DefaultTableModel subjectMod = new DefaultTableModel(subjects, titlesS){
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
tabSubjects.setModel(subjectMod);
tabSubjects.getColumnModel().getColumn(0).setMinWidth(0);
tabSubjects.getColumnModel().getColumn(0).setMaxWidth(0);
tabSubjects.getColumnModel().getColumn(0).setWidth(0);
DefaultTableCellRenderer centerSubject = new DefaultTableCellRenderer();
centerSubject.setHorizontalAlignment( jLabel1.CENTER );
tabSubjects.getColumnModel().getColumn(1).setCellRenderer( centerSubject );
tabSubjects.getColumnModel().getColumn(1).setHeaderRenderer(new HeaderAssignation());
tabSubjects.setShowGrid(false);
tabSubjects.setIntercellSpacing(new Dimension(0, 0));
}
/* Populating table Assigned (Second) */
tabAssigned.setModel(emptyModel);
Object[][] subjectsAssigened = ctrlT.getSubjectsAssigned(teacherId, year, gestion);
String[] titlesA = {"id", "Nombre"};
DefaultTableModel modelAssigned = new DefaultTableModel(subjectsAssigened, titlesA){
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
tabAssigned.setModel(modelAssigned);
tabAssigned.getColumnModel().getColumn(0).setMinWidth(0);
tabAssigned.getColumnModel().getColumn(0).setMaxWidth(0);
tabAssigned.getColumnModel().getColumn(0).setWidth(0);
tabAssigned.getColumnModel().getColumn(1).setHeaderRenderer(new HeaderAssignation());
tabAssigned.setShowGrid(false);
tabAssigned.setIntercellSpacing(new Dimension(0, 0));
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Assignation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Assignation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Assignation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Assignation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Assignation().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAssign;
private javax.swing.JButton btnClose;
private javax.swing.JComboBox cmbGestion;
private javax.swing.JComboBox cmbYear;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JLabel lblGestion;
private javax.swing.JLabel lblSubtitle_one;
private javax.swing.JLabel lblSubtitle_two;
private javax.swing.JLabel lblTitle;
private javax.swing.JLabel lblYear;
private javax.swing.JTable tabAssigned;
private javax.swing.JTable tabSubjects;
// End of variables declaration//GEN-END:variables
}
| 47.548889
| 190
| 0.605552
|
c14257c3f1e0fd6e21b30c8ef6cc0b4fb231a7f5
| 3,546
|
/*
* Copyright (c) 2020 Dzikoysk
*
* 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.dzikoysk.funnycommands.commands;
import panda.utilities.StringUtils;
import panda.std.Option;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public final class CommandStructure {
private final CommandMetadata element;
private final Map<String, CommandStructure> children;
public CommandStructure(CommandMetadata element) {
this.element = element;
this.children = new HashMap<>();
}
public void print() {
print(this, 0);
}
private void print(CommandStructure node, int level) {
for (CommandStructure child : node.getSubcommands()) {
System.out.println(StringUtils.buildSpace(level * 2) + (level == 0 ? "/" : "..") + child.getSimpleName() + " -> " + child.element);
child.print(child, level + 1);
}
}
public CommandStructure computeIfAbsent(String name, Function<String, CommandMetadata> function) {
return getSubcommandStructure(name).orElseGet(() -> add(function.apply(name)));
}
public CommandStructure add(CommandMetadata element) {
CommandStructure tree = new CommandStructure(element);
children.put(tree.getSimpleName(), tree);
return tree;
}
public Option<CommandMetadata> get(String name) {
return getSubcommandStructure(name).map(CommandStructure::getMetadata);
}
public List<CommandStructure> collectCommandsStartingWith(String str) {
List<CommandStructure> nodes = new ArrayList<>();
for (CommandStructure tree : children.values()) {
if (tree.getName().startsWith(str)) {
nodes.add(tree);
}
nodes.addAll(tree.collectCommandsStartingWith(str));
}
return nodes;
}
public Option<CommandStructure> getSubcommandStructure(String nodeName) {
for (CommandStructure child : children.values()) {
if (child.getSimpleName().equalsIgnoreCase(nodeName)) {
return Option.of(child);
}
for (String alias : child.element.getCommandInfo().getAliases()) {
if (alias.equalsIgnoreCase(nodeName)) {
return Option.of(child);
}
}
}
return Option.none();
}
public Collection<CommandStructure> getSubcommands() {
return children.values();
}
public List<String> getSubcommandsNames() {
return getSubcommands().stream()
.map(CommandStructure::getSimpleName)
.collect(Collectors.toList());
}
public CommandMetadata getMetadata() {
return element;
}
public String getSimpleName() {
return element.getSimpleName();
}
public String getName() {
return element.getName();
}
}
| 30.568966
| 143
| 0.650592
|
ed960ec995d994873fe0a52c66e3f0608a43859b
| 810
|
package gov.nasa.jpl.aerie.merlin.server.services;
import gov.nasa.jpl.aerie.merlin.server.exceptions.NoSuchPlanException;
import gov.nasa.jpl.aerie.merlin.server.models.Constraint;
import gov.nasa.jpl.aerie.merlin.server.models.Plan;
import gov.nasa.jpl.aerie.merlin.server.models.PlanId;
import gov.nasa.jpl.aerie.merlin.server.models.ProfileSet;
import gov.nasa.jpl.aerie.merlin.server.models.Timestamp;
import java.util.Map;
public interface PlanService {
Plan getPlan(PlanId planId) throws NoSuchPlanException;
RevisionData getPlanRevisionData(PlanId planId) throws NoSuchPlanException;
Map<String, Constraint> getConstraintsForPlan(PlanId planId) throws NoSuchPlanException;
long addExternalDataset(PlanId planId, Timestamp datasetStart, ProfileSet profileSet) throws NoSuchPlanException;
}
| 40.5
| 115
| 0.832099
|
2de90ba23da3f6550f0dcff0592f1661f0fef512
| 3,195
|
package com.der3318.forumsurf;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PTTProcessor implements ForumProcessor {
private String loadMoreDataToken = null;
@Override
public String getUrlForPostList(String boardToken, boolean loadMoreData) {
String url;
if (loadMoreData && this.loadMoreDataToken != null) {
final String urlFormat = "https://www.ptt.cc%s";
url = String.format(urlFormat, this.loadMoreDataToken);
} else {
final String urlFormat = "https://www.ptt.cc/bbs/%s/index.html";
url = String.format(urlFormat, boardToken);
}
return url;
}
@Override
public String getUrlForPost(String postToken) {
final String urlFormat = "https://www.ptt.cc%s";
return String.format(urlFormat, postToken);
}
@Override
public String getUrlForCommentList(String postToken) {
final String urlFormat = "https://www.ptt.cc%s";
return String.format(urlFormat, postToken);
}
@Override
public List<ForumPost> convertResponseToPostList(String response) {
List<ForumPost> postList = new ArrayList<>();
Document document = Jsoup.parse(response);
for (Element element : document.select("div.r-ent")) {
if (element.select("div.title").select("a").isEmpty()) {
continue;
}
String title = element.select("div.title").select("a").text();
String user = element.select("div.meta").select("div.author").text();
String time = element.select("div.meta").select("div.date").text().trim();
String token = element.select("div.title").select("a").attr("href");
postList.add(new ForumPost(title, user, time, "", token));
}
Collections.reverse(postList);
return postList;
}
@Override
public void updateTokenUsedToLoadMoreData(String response) {
Document document = Jsoup.parse(response);
this.loadMoreDataToken = document.select("a:containsOwn(‹ 上頁)").attr("href");
}
@Override
public void updatePostUsingResponse(ForumPost post, String response) {
Document document = Jsoup.parse(response);
Element content = document.select("div.bbs-screen.bbs-content").first();
content.select("div").remove();
post.setContent(content.wholeText());
}
@Override
public List<String> convertResponseToCommentList(String response) {
List<String> commentList = new ArrayList<>();
Document document = Jsoup.parse(response);
Element content = document.select("div.bbs-screen.bbs-content").first();
for (Element element : document.select("div.push")) {
if (element.select("span.f3.push-content").text().length() > 2) {
commentList.add(element.select("span.f3.push-content").text().substring(2));
}
}
return commentList;
}
}
| 37.151163
| 93
| 0.617214
|
5e15fe7bbf907ee38d11c74a87d50d9bfb7aecaa
| 1,966
|
/*
*
* Copyright 2020 IBM 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.ibm.eventstreams.connect.jdbcsink.sink.datasource.database;
import com.ibm.eventstreams.connect.jdbcsink.database.DatabaseType;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class DatabaseTypeTest {
@Nested
class FromJDBCUrl {
@Test
void shouldReturnDatabaseTypeForValidJdbcUrl() {
String databaseType = "postgresql";
String connectionUrl = String.format("jdbc:%s://127.0.0.1:5432/blah", databaseType);
DatabaseType type = DatabaseType.fromJdbcUrl(connectionUrl);
assertEquals(type, DatabaseType.postgresql);
}
@Test
void shouldReturnNullForInValidJdbcUrl() {
String databaseType = "postgresql";
String connectionUrl = String.format("jdbc://", databaseType);
DatabaseType type = DatabaseType.fromJdbcUrl(connectionUrl);
assertEquals(type, null);
}
@Test
void shouldReturnNullForANotSupportedDatabaseType() {
String databaseType = "not supported";
String connectionUrl = String.format("jdbc:%s://127.0.0.1:5432/blah", databaseType);
DatabaseType type = DatabaseType.fromJdbcUrl(connectionUrl);
assertEquals(type, null);
}
}
}
| 31.709677
| 96
| 0.685656
|
d0d1fb3e9174f7e785fd52727d7839e3279fa776
| 118
|
package online.zouxiaolong;
/**
* @author zZZ....
* @description
* @date 2022/1/17
*/
public class test {
}
| 10.727273
| 27
| 0.59322
|
ebd1322ecf407f2a0fc2283e546e04a7a5ff4d7c
| 3,337
|
package io.deephaven.client.impl;
import io.deephaven.proto.backplane.grpc.Ticket;
import io.deephaven.qst.table.TableSpec;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* A session represents a client-side connection to a Deephaven server.
*/
public interface Session extends AutoCloseable, TableHandleManager {
/**
* Creates a new export with a {@link io.deephaven.client.impl.ExportRequest.Listener#logging() logging listener}.
*
* <p>
* Equivalent to {@code export(ExportsRequest.logging(table)).get(0)}.
*
* @param table the table
* @return the export
*/
Export export(TableSpec table);
/**
* Creates new exports according to the {@code request}.
*
* @param request the request
* @return the exports
*/
List<Export> export(ExportsRequest request);
// ----------------------------------------------------------
/**
* Creates a new console session of script type {@code type}.
*
* <p>
* Note: the server does not currently support independent console sessions. See
* <a href="https://github.com/deephaven/deephaven-core/issues/1172">Issue 1172</a>.
*
* @param type the script type
* @return the console session future
*/
CompletableFuture<? extends ConsoleSession> console(String type);
// ----------------------------------------------------------
/**
* Publishes {@code ticket} into the global scope with {@code name}.
*
* @param name the name, must conform to {@link javax.lang.model.SourceVersion#isName(CharSequence)}
* @param ticket the ticket
* @return the publish completable future
*/
CompletableFuture<Void> publish(String name, HasTicket ticket);
default CompletableFuture<Void> publish(String name, Ticket ticket) {
return publish(name, () -> ticket);
}
/**
* Closes the session.
*/
@Override
void close();
/**
* Closes the session.
*
* @return the future
*/
CompletableFuture<Void> closeFuture();
/**
* A batch table handle manager.
*
* @return a batch manager
*/
TableHandleManager batch();
/**
* A batch table handle manager.
*
* @param mixinStacktraces if stacktraces should be mixin
* @return a batch manager
*/
TableHandleManager batch(boolean mixinStacktraces);
/**
* A serial table handle manager.
*
* @return a serial manager
*/
TableHandleManager serial();
// ----------------------------------------------------------
/**
* Advanced usage, creates a new ticket for {@code this} session, but must be managed by the caller. Useful for more
* advanced integrations, particularly around doPut. Callers are responsible for {@link #release(Ticket) releasing}
* the ticket if necessary.
*
* @return the new ticket
* @see #release(Ticket)
*/
Ticket newTicket();
/**
* Releases a ticket.
*
* <p>
* Note: this should <b>only</b> be called in combination with tickets returned from {@link #newTicket()}.
*
* @param ticket the ticket
* @return the future
*/
CompletableFuture<Void> release(Ticket ticket);
}
| 27.578512
| 120
| 0.600539
|
e1d4bfc385410eb4c82c89d545d565307d69e771
| 11,464
|
package com.clfsjkj.govcar;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.clfsjkj.govcar.adapter.MainFragmentAdapter;
import com.clfsjkj.govcar.base.BaseActivity;
import com.clfsjkj.govcar.http.UpdateAppHttpUtil;
import com.clfsjkj.govcar.keepingappalive.receiver.ScreenReceiverUtil;
import com.clfsjkj.govcar.keepingappalive.service.DaemonService;
import com.clfsjkj.govcar.keepingappalive.service.PlayerMusicService;
import com.clfsjkj.govcar.keepingappalive.utils.Contants;
import com.clfsjkj.govcar.keepingappalive.utils.JobSchedulerManager;
import com.clfsjkj.govcar.keepingappalive.utils.ScreenManager;
import com.clfsjkj.govcar.permission.DefaultRationale;
import com.clfsjkj.govcar.permission.PermissionSetting;
import com.clfsjkj.govcar.utils.NotifyUtil;
import com.vector.update_app.UpdateAppManager;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Rationale;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* 主框架
*/
public class MainActivity extends BaseActivity {
// @BindView(R.id.toolbar)
// Toolbar mToolbar;
private String mUpdateUrl1 = "https://raw.githubusercontent.com/WVector/AppUpdateDemo/master/json/json1.txt";
private Context context;
private NotifyUtil notifyUtils;
/**
* 菜单标题
*/
private final int[] TAB_TITLES = new int[]{R.string.menu_msg, R.string.menu_contact, R.string.menu_find, R.string.menu_me};
/**
* 菜单图标
*/
private final int[] TAB_IMGS = new int[]{R.drawable.tab_main_msg_selector, R.drawable.tab_main_contact_selector, R.drawable.tab_main_find_selector
, R.drawable.tab_main_me_selector};
@BindView(R.id.view_pager)
ViewPager viewPager;
@BindView(R.id.tab_layout)
TabLayout tabLayout;
/**
* 页卡适配器
*/
private PagerAdapter adapter;
/**
* 退出时间
*/
private long exitTime;
/**
* 动态权限
*/
private Rationale mRationale;
private PermissionSetting mSetting;
/**
* keepingappalive
*/
// 动态注册锁屏等广播
private ScreenReceiverUtil mScreenListener;
// 1像素Activity管理类
private ScreenManager mScreenManager;
// JobService,执行系统任务
private JobSchedulerManager mJobManager;
// 华为推送管理类
// private HwPushManager mHwPushManager;
private ScreenReceiverUtil.SreenStateListener mScreenListenerer = new ScreenReceiverUtil.SreenStateListener() {
@Override
public void onSreenOn() {
// 亮屏,移除"1像素"
mScreenManager.finishActivity();
}
@Override
public void onSreenOff() {
// 接到锁屏广播,将MainActivity切换到可见模式
// "咕咚"、"乐动力"、"悦动圈"就是这么做滴
// Intent intent = new Intent(MainActivity.this,MainActivity.class);
// startActivity(intent);
// 如果你觉得,直接跳出SportActivity很不爽
// 那么,我们就制造个"1像素"惨案
mScreenManager.startActivity();
}
@Override
public void onUserPresent() {
// 解锁,暂不用,保留
}
};
private String TAG = "GovCar";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
context = this;
initMyToolBar();
setStatusBarFullTransparent();
setFitSystemWindow(true);
// 初始化页卡
initPager();
setTabs(tabLayout, getLayoutInflater(), TAB_TITLES, TAB_IMGS);
//动态权限demo
mRationale = new DefaultRationale();
mSetting = new PermissionSetting(this);
// permission();
//keepaingappaliva
if (Contants.DEBUG)
Log.d(TAG, "--->onCreate");
// 1. 注册锁屏广播监听器
mScreenListener = new ScreenReceiverUtil(this);
mScreenManager = ScreenManager.getScreenManagerInstance(this);
mScreenListener.setScreenReceiverListener(mScreenListenerer);
// 2. 启动系统任务
mJobManager = JobSchedulerManager.getJobSchedulerInstance(this);
mJobManager.startJobScheduler();
// 3. 启动前台Service
startDaemonService();
// 4. 启动播放音乐Service
// startPlayMusicService();
//APP版本更新检查
// checkVersion();
}
private void initMyToolBar() {
// initToolBar(mToolbar, "GovCar");
// Button rightBtnSearch = (Button) mToolbar.findViewById(R.id.right_btn);
// rightBtnSearch.setVisibility(View.VISIBLE);
// rightBtnSearch.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
//// startActivity(new Intent(MainActivity.this, SearchActivity.class));
// }
// });
}
private void checkVersion() {
// 1,有新版本
// {
// "update": "Yes",//有新版本
// "new_version": "0.8.3",//新版本号
// "apk_file_url": "https://raw.githubusercontent.com/WVector/AppUpdateDemo/master/apk/app-debug.apk", //apk下载地址
// "update_log": "1,添加删除信用卡接口\r\n2,添加vip认证\r\n3,区分自定义消费,一个小时不限制。\r\n4,添加放弃任务接口,小时内不生成。\r\n5,消费任务手动生成。",//更新内容
// "target_size": "5M",//apk大小
// "new_md5":"A818AD325EACC199BC62C552A32C35F2",
// "constraint": false//是否强制更新
// }
// 2,没有新版本
// {
// "update": "No",//没有新版本
// }
new UpdateAppManager
.Builder()
//当前Activity
.setActivity(this)
//更新地址
.setUpdateUrl(mUpdateUrl1)
//实现httpManager接口的对象
.setHttpManager(new UpdateAppHttpUtil())
.build()
.update();
}
private void stopPlayMusicService() {
Intent intent = new Intent(MainActivity.this, PlayerMusicService.class);
stopService(intent);
}
private void startPlayMusicService() {
Intent intent = new Intent(MainActivity.this, PlayerMusicService.class);
startService(intent);
}
private void startDaemonService() {
Intent intent = new Intent(MainActivity.this, DaemonService.class);
startService(intent);
}
private void stopDaemonService() {
Intent intent = new Intent(MainActivity.this, DaemonService.class);
stopService(intent);
}
public void permission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermission(Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);
// AndPermission.with(this)
// .permission(Manifest.permission.RECORD_AUDIO)
// .rationale(mRationale)
// .onGranted(new Action() {
// @Override
// public void onAction(List<String> permissions) {
// Toast.makeText(MainActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
// }
// })
// .onDenied(new Action() {
// @Override
// public void onAction(@NonNull List<String> permissions) {
// Toast.makeText(MainActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
// if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions)) {
// mSetting.showSetting(permissions);
// }
// }
// })
// .start();
}
}
private void requestPermission(String... permissions) {
AndPermission.with(this)
.permission(permissions)
.rationale(mRationale)
.onGranted(new Action() {
@Override
public void onAction(List<String> permissions) {
// Toast.makeText(MainActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
}
})
.onDenied(new Action() {
@Override
public void onAction(@NonNull List<String> permissions) {
// Toast.makeText(MainActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, permissions)) {
mSetting.showSetting(permissions);
}
}
})
.start();
}
/**
* 设置页卡显示效果
*
* @param tabLayout
* @param inflater
* @param tabTitlees
* @param tabImgs
*/
private void setTabs(TabLayout tabLayout, LayoutInflater inflater, int[] tabTitlees, int[] tabImgs) {
for (int i = 0; i < tabImgs.length; i++) {
TabLayout.Tab tab = tabLayout.newTab();
View view = inflater.inflate(R.layout.item_main_menu, null);
// 使用自定义视图,目的是为了便于修改,也可使用自带的视图
tab.setCustomView(view);
TextView tvTitle = (TextView) view.findViewById(R.id.txt_tab);
tvTitle.setText(tabTitlees[i]);
ImageView imgTab = (ImageView) view.findViewById(R.id.img_tab);
imgTab.setImageResource(tabImgs[i]);
tabLayout.addTab(tab);
}
}
private void initPager() {
adapter = new MainFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
// 关联切换
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// 取消平滑切换
viewPager.setCurrentItem(tab.getPosition(), false);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
&& event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {
// 重写键盘事件分发,onKeyDown方法某些情况下捕获不到,只能在这里写
if ((System.currentTimeMillis() - exitTime) > 2000) {
Snackbar snackbar = Snackbar.make(viewPager, "再按一次退出程序", Snackbar.LENGTH_SHORT);
snackbar.getView().setBackgroundResource(R.color.colorPrimary);
snackbar.show();
exitTime = System.currentTimeMillis();
} else {
finish();
}
return true;
}
return super.dispatchKeyEvent(event);
}
}
| 34.323353
| 150
| 0.60328
|
53a14ad853aa91df96111ebdffd24f42567dc6d5
| 103
|
package astro.tool.box.enumeration;
public enum Unit {
DEGREE, ARCSEC, MAS, DAY, YEAR;
}
| 12.875
| 36
| 0.640777
|
f36f2117efe28e56d84e7cc8f10ab5ca9f3bd371
| 645
|
package org.dspbench.core.hook;
import org.dspbench.core.Tuple;
import org.dspbench.core.Values;
import org.dspbench.metrics.ThroughputNew;
/**
*
* @author mayconbordin
*/
public class ThroughputHook extends Hook {
private ThroughputNew throughput;
//private Throughput.Context context;
public ThroughputHook(ThroughputNew throughput) {
this.throughput = throughput;
}
public void beforeTuple(Tuple tuple) {
//context = throughput.time();
}
public void afterTuple(Tuple tuple) {
//context.stop();
throughput.count();
}
public void onEmit(Values values) {
}
}
| 20.15625
| 53
| 0.672868
|
899059556738a164f4de133c2a835eb148ceb757
| 1,643
|
package com.hua.security.service;
import com.hua.security.mapper.GithubUserMapper;
import com.hua.security.pojo.githubUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserService implements UserDetailsService {
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
GithubUserMapper githubUserMapper ;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
githubUser user = githubUserMapper.getByUsername(s) ;
List<GrantedAuthority> authorities=new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_vip1"));
authorities.add(new SimpleGrantedAuthority("ROLE_vip2"));
authorities.add(new SimpleGrantedAuthority("ROLE_vip3"));
String uuid = user.getUuid();
String username = user.getUsername();
if(username.equals(s)){
return new User(username,bCryptPasswordEncoder.encode(uuid),authorities);
}else{
return null;
}
}
}
| 39.119048
| 86
| 0.776628
|
240c8dbfd5427e6312fcfee0436c8538390ccea9
| 6,775
|
package de.aljoshavieth.moneycounter;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import static de.aljoshavieth.moneycounter.MainActivity.coinAmount;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link CoinsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link CoinsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class CoinsFragment extends Fragment implements View.OnClickListener{
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private EditText eur2AmountText;
private EditText eur1AmountText;
private EditText ct50AmountText;
private EditText ct20AmountText;
private EditText ct10AmountText;
private EditText ct5AmountText;
private EditText ct2AmountText;
private EditText ct1AmountText;
private Button doneButton;
private MainActivity mainActivity;
private OnFragmentInteractionListener mListener;
public CoinsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment CoinsFragment.
*/
// TODO: Rename and change types and number of parameters
public static CoinsFragment newInstance(String param1, String param2) {
CoinsFragment fragment = new CoinsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_coins, container, false);
eur2AmountText = view.findViewById(R.id.eur2Input);
eur1AmountText = view.findViewById(R.id.eur1Input);
ct50AmountText = view.findViewById(R.id.ct50Input);
ct20AmountText = view.findViewById(R.id.ct20Input);
ct10AmountText = view.findViewById(R.id.ct10Input);
ct5AmountText = view.findViewById(R.id.ct5Input);
ct2AmountText = view.findViewById(R.id.ct2Input);
ct1AmountText = view.findViewById(R.id.ct1Input);
doneButton = view.findViewById(R.id.coinsDoneBtn);
doneButton.setOnClickListener(this);
mainActivity = (MainActivity) getActivity();
return view;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.coinsDoneBtn){
calculateCoins();
mainActivity.switchToMainFragment();
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void calculateCoins(){
double eur2Amount = 0.00;
double eur1Amount = 0.00;
double ct50Amount = 0.00;
double ct20Amount = 0.00;
double ct10Amount = 0.00;
double ct5Amount = 0.00;
double ct2Amount = 0.00;
double ct1Amount = 0.00;
if(!eur2AmountText.getText().toString().isEmpty()){
eur2Amount = 2.00 *Double.valueOf(eur2AmountText.getText().toString());
}
if(!eur1AmountText.getText().toString().isEmpty()){
eur1Amount = 1.00 *Double.valueOf(eur1AmountText.getText().toString());
}
if(!ct50AmountText.getText().toString().isEmpty()){
ct50Amount = 0.50 *Double.valueOf(ct50AmountText.getText().toString());
}
if(!ct20AmountText.getText().toString().isEmpty()){
ct20Amount = 0.20 *Double.valueOf(ct20AmountText.getText().toString());
}
if(!ct10AmountText.getText().toString().isEmpty()){
ct10Amount = 0.10 *Double.valueOf(ct10AmountText.getText().toString());
}
if(!ct5AmountText.getText().toString().isEmpty()){
ct5Amount = 0.05 *Double.valueOf(ct5AmountText.getText().toString());
}
if(!ct2AmountText.getText().toString().isEmpty()){
ct2Amount = 0.02 *Double.valueOf(ct2AmountText.getText().toString());
}
if(!ct1AmountText.getText().toString().isEmpty()){
ct1Amount = 0.01 *Double.valueOf(ct1AmountText.getText().toString());
}
coinAmount = eur2Amount + eur1Amount + ct50Amount + ct20Amount + ct10Amount + ct5Amount + ct2Amount + ct1Amount;
coinAmount = mainActivity.round(coinAmount, 2);
}
}
| 34.92268
| 120
| 0.666273
|
0a75064260f48585dcc4d9adad679651583b7ddf
| 401
|
public static void CopyFile(String in, String out) throws Exception {
FileChannel sourceChannel = new FileInputStream(new File(in)).getChannel();
FileChannel destinationChannel = new FileOutputStream(new File(out)).getChannel();
sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
sourceChannel.close();
destinationChannel.close();
}
| 50.125
| 90
| 0.710723
|
a5deaac47d232e9fe508026d95894f1f3e840bcc
| 2,591
|
package com.alibaba.datax.common.element;
import com.alibaba.datax.common.exception.CommonErrorCode;
import com.alibaba.datax.common.exception.DataXException;
import org.apache.commons.lang3.math.NumberUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
/**
* @author ChengJie
* @desciption
* @date 2019/5/20 15:34
**/
public class DecimalColumn extends Column {
public DecimalColumn(final String data) {
super(new BigDecimal(0), Type.DECIMAL, 0);
if (null == data) {
return;
}
try {
BigDecimal rawData = NumberUtils.createBigDecimal(data);
super.setRawData(rawData);
super.setByteSize(data.length());
} catch (Exception e) {
throw DataXException.asDataXException(
CommonErrorCode.CONVERT_NOT_SUPPORT,
String.format("String[%s]不能转为Decimal .", data));
}
}
@Override
public Long asLong() {
if (null == this.getRawData()) {
return null;
}
BigDecimal decimal=(BigDecimal)this.getRawData();
return decimal.longValue();
}
@Override
public Double asDouble() {
if (null == this.getRawData()) {
return null;
}
BigDecimal decimal=(BigDecimal)this.getRawData();
return decimal.doubleValue();
}
@Override
public String asString() {
if (null == this.getRawData()) {
return null;
}
BigDecimal decimal=(BigDecimal)this.getRawData();
return decimal.toString();
}
@Override
public Date asDate() {
throw DataXException.asDataXException(
CommonErrorCode.CONVERT_NOT_SUPPORT, "Long类型不能转为Bytes .");
}
@Override
public byte[] asBytes() {
throw DataXException.asDataXException(
CommonErrorCode.CONVERT_NOT_SUPPORT, "Long类型不能转为Bytes .");
}
@Override
public Boolean asBoolean() {
throw DataXException.asDataXException(
CommonErrorCode.CONVERT_NOT_SUPPORT, "Long类型不能转为Bytes .");
}
@Override
public BigDecimal asBigDecimal() {
if (null == this.getRawData()) {
return null;
}
BigDecimal decimal=(BigDecimal)this.getRawData();
return decimal;
}
@Override
public BigInteger asBigInteger() {
if (null == this.getRawData()) {
return null;
}
BigDecimal decimal=(BigDecimal)this.getRawData();
return decimal.toBigInteger();
}
}
| 26.438776
| 74
| 0.60247
|
d305b03e65ddaabfcadfc7437616fa5e156fbeee
| 2,641
|
package xyz.germanfica._2018._1st.tp3;
/*
* Actualizaciones:
* - Nombre de la clase "Puntos" a "Cliente", por lo que ahora tiene más sentido
* que el cliente tenga puntos y no al revés.
* - Nombres más descriptivos a los parámetros.
* - Se agregaron comentarios, a excepcion del constructor para reforzar el
* entendimiento de los mismos.
*/
// Nota: los métodos de objetivo mostrar cartel no deben ir en el objecto/clase.
public class Cliente {
private String nombre;
private int puntos;
public static int cantidadMaximaDePuntosLogrables = 5000;
// Constructores
public Cliente(String nombre) {
this.nombre = nombre;
puntos = 0;
}
// Observadores
/**
* Retorna el nombre del cliente
* @return
*/
public String getNombre() {
return nombre;
}
/**
* Retorna la cantidad de puntos acumulados por el cliente
* @return puntos
*/
public int getPuntos() {
return puntos;
}
/**
* Retorna en texto plano todos los atributos del cliente
*/
public String toString() {
return "Cliente: " + nombre + "\nPuntaje: " + puntos;
}
/**
* Verifica si el cliente actual es igual al cliente enviado por parámetro
* @param cliente
* @return
*/
public boolean equals(Cliente cliente) {
return cliente.getNombre()==nombre && cliente.puntos==this.puntos;
}
// Modificadores
/**
* Cambiar nombre del cliente
* @param nombre
*/
/*
* Actualizacion del día 21 de Abril del 2018 a las 12:31:
* - Nombre del parámetro "n" por "nombre"
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* Cambiar el puntaje del cliente
* @param puntos
*/
/*
* Actualizacion del día 21 de Abril del 2018 a las 12:35:
* - Nombre del parámetro "d" por "puntos"
*/
public void setPuntos(int puntos) {
if(puntos<cantidadMaximaDePuntosLogrables) {
this.puntos = puntos;
}else {
this.puntos = cantidadMaximaDePuntosLogrables;
}
}
// Propias del tipo
/**
* Sumar más puntos al cliente pero con una cantidad máxima de puntos logrables
* @param mas
*/
public void sumarPuntos(int mas) {
if(mas<cantidadMaximaDePuntosLogrables) {
puntos = puntos + mas;
}else {
puntos = cantidadMaximaDePuntosLogrables;
}
}
/**
* Canjear los puntos del cliente. Resta el valor del parámetro al atributo puntos,
* devuelve true si se pudo efectuar la operacion.
* @param canje
* @return
*/
public boolean canjearPuntos(int canje) {
int número;
boolean respuesta;
respuesta = false;
número = puntos - canje;
if(número>0){
puntos = puntos - canje;
respuesta = true;
}
return respuesta;
}
}
| 21.298387
| 84
| 0.673987
|
b1f9dad9b9ed0360635f3f8861f4b055364031cc
| 3,598
|
package com.luxoft.fabric.integration;
import com.luxoft.fabric.FabricConnector;
import com.luxoft.fabric.config.ConfigAdapter;
import org.hyperledger.fabric.sdk.BlockEvent;
import org.hyperledger.fabric.sdk.NetworkConfig;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class ServiceDiscoveryIntegrationTest extends BaseIntegrationTest {
private static final Logger logger = LoggerFactory.getLogger(FabricConnectorIntegrationTest.class);
/*Attention! Test will work only in case you have following lines in your /etc/hosts file:
127.0.0.1 orderer.example.com
127.0.0.1 peer0.org1.example.com
This is necessary, because during Service Discovery real names of peers and orderer are returned.
Those name's make sense inside of docker container, but not in local java application.
Alternative solutions would be running our own DNS inside of this Java process or using a lot of reflexion to slip the names after they were discovered.
I believe having customs /etc/hosts is the cleanest solution, though not ideal.
*/
@Test
public void testServiceDiscoveryWithFabricConfig() throws Exception {
logger.info("Starting SanityCheck");
FabricConnector fabricConnector = new FabricConnector(ConfigAdapter.getBuilder(fabricConfigServiceDiscovery).build());
byte[] key = "someKey".getBytes();
byte[] value = UUID.randomUUID().toString().getBytes();
CompletableFuture<BlockEvent.TransactionEvent> putEventFuture = fabricConnector.invoke(
"put", "mychcode", "mychannel", key, value);
Assert.assertNotNull(putEventFuture.get());
CompletableFuture<byte[]> queryFuture = fabricConnector.query(
"get", "mychcode", "mychannel", key);
Assert.assertArrayEquals(value, queryFuture.get());
logger.info("Finished SanityCheck");
}
/*Attention! Test will work only in case you have following lines in your /etc/hosts file:
127.0.0.1 orderer.example.com
127.0.0.1 peer0.org1.example.com
This is necessary, because during Service Discovery real names of peers and orderer are returned.
Those name's make sense inside of docker container, but not in local java application.
Alternative solutions would be running our own DNS inside of this Java process or using a lot of reflexion to slip the names after they were discovered.
I believe having customs /etc/hosts is the cleanest solution, though not ideal.
*/
@Test
public void testServiceDiscoveryWithNetworkConfig() throws Exception {
logger.info("Starting SanityCheck");
NetworkConfig networkConfig = NetworkConfig.fromYamlFile(new File(NETWORK_CONFIG__SERVICE_DISCOVERY_FILE));
FabricConnector fabricConnector = new FabricConnector(ConfigAdapter.getBuilder(networkConfig).build());
byte[] key = "someKey".getBytes();
byte[] value = UUID.randomUUID().toString().getBytes();
CompletableFuture<BlockEvent.TransactionEvent> putEventFuture = fabricConnector.invoke(
"put", "mychcode", "mychannel", key, value);
Assert.assertNotNull(putEventFuture.get());
CompletableFuture<byte[]> queryFuture = fabricConnector.query(
"get", "mychcode", "mychannel", key);
Assert.assertArrayEquals(value, queryFuture.get());
logger.info("Finished SanityCheck");
}
}
| 46.727273
| 157
| 0.72179
|
fcab3e67cb02e79142994e577509d361646d41c9
| 3,593
|
package me.zombie_striker.brsscalar;
import me.zombie_striker.omeggajava.JOmegga;
import me.zombie_striker.omeggajava.events.ChatCommandEvent;
import me.zombie_striker.omeggajava.events.EventHandler;
import me.zombie_striker.omeggajava.events.Listener;
import me.zombie_striker.omeggajava.events.TickEvent;
import javax.swing.*;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
public class ScalarListener implements Listener {
private List<UpscaleRequest> requests = new LinkedList<>();
@EventHandler
public void onChat(ChatCommandEvent event) {
if (event.getCommand().equals("brsscalar:save")) {
if(!JOmegga.getPlayer(event.getPlayername()).isHost()){
JOmegga.whisper(event.getPlayername(),"Only the host can use this command.");
return;
}
if (event.getArgs().length < 1) {
JOmegga.whisper(event.getPlayername(), "You need to provide the name of the save ");
return;
}
JOmegga.save(event.getArgs()[0]);
JOmegga.whisper(event.getPlayername(),"Saving map to \""+event.getArgs()[0]+"\"");
}else if (event.getCommand().equals("brsscalar")) {
if(!JOmegga.getPlayer(event.getPlayername()).isHost()){
JOmegga.whisper(event.getPlayername(),"Only the host can use this command.");
return;
}
if (event.getArgs().length < 1) {
JOmegga.whisper(event.getPlayername(), "You need to provide the name of the save you wish to upscale (Or use ~ to use the current map.)");
return;
}
String upscaleName = event.getArgs()[0];
if (event.getArgs().length < 2) {
JOmegga.whisper(event.getPlayername(), "Please provide the scale you wish to scale the bricks by (use whole numbers).");
return;
}
double scalarx = Double.parseDouble(event.getArgs()[1]);
double scalary = scalarx;
double scalarz = scalarx;
if(event.getArgs().length >= 4){
scalary = Double.parseDouble(event.getArgs()[2]);
scalarz = Double.parseDouble(event.getArgs()[3]);
}
if (scalarx == 0|| scalary == 0 || scalarz==0) {
JOmegga.whisper(event.getPlayername(), "The scalar provided is 0.");
return;
}
if(upscaleName.equals("~")){
upscaleName = "brsscalar_current";
JOmegga.save(upscaleName);
}else if (!new File(JOmegga.getOmeggaDir(), "/data/Saved/Builds/" + upscaleName + ".brs").exists()) {
JOmegga.whisper(event.getPlayername(), upscaleName + ".brs does not exist in the /Builds/ folder.");
return;
}
requests.add(new UpscaleRequest(JOmegga.readSaveData(upscaleName), scalarx,scalary,scalarz, event.getPlayername()));
JOmegga.whisper(event.getPlayername(), "Upscaling \"" + upscaleName + "\" by " + scalarx+(scalarx!=scalary||scalarx!=scalarz?", "+scalary+", "+scalarz:"") + ".");
}
}
@EventHandler
public void onTick(TickEvent event) {
if (requests.size() > 0)
for (UpscaleRequest request : new LinkedList<>(requests)) {
request.tick();
if (request.done()) {
JOmegga.whisper(request.getPlayerName(), "Done upscaling.");
requests.remove(request);
}
}
}
}
| 44.9125
| 174
| 0.582243
|
31ac6c87a26838495466ff1bd4dbbe6bb4ef60f3
| 2,456
|
package com.scififics.writershub.models;
import java.util.ArrayList;
public class SearchData {
/*
Searches all chapters by type and term
@param type - Determines what field is being searched. For example, title or description
@param term - The search term provided.
@param allChapters - A list of all chapters to be searched
@return - A list of all chapters for which the term is included in the type
*/
public static ArrayList<Chapter> findByTypeAndTerm (String type, String term, Iterable<Chapter> allChapters) {
ArrayList<Chapter> results = new ArrayList<>();
if (type.equals("tags")) {
results = findByTag(term, allChapters);
return results;
}
for (Chapter chapter : allChapters) {
String aValue = getFieldValue(chapter, type);
if (aValue != null && aValue.toLowerCase().contains(term.toLowerCase())) {
results.add(chapter);
}
}
return results;
}
/*
Gets the value of the field
@param chapter - the chapter which contains the field needed
@param fieldName - the field which holds the needed data
@return - the toString of the field
*/
public static String getFieldValue(Chapter chapter, String fieldName) {
String theValue;
if (fieldName.equals("title")){
theValue = chapter.getTitle();
} else if (fieldName.equals("description")){
theValue = chapter.getDescription();
} else {
theValue = chapter.getContent();
}
return theValue;
}
/*
Gets a list of chapters associated with the searched tag
@param term - the search term
@allChapters - a list of chapters to be searched
@return - a list of chapters tagged by the search term
*/
public static ArrayList<Chapter> findByTag (String term, Iterable<Chapter> allChapters) {
ArrayList<Chapter> results = new ArrayList<>();
for (Chapter chapter : allChapters) {
if (chapter.getTags() != null) {
for (Tag tag : chapter.getTags()) {
if (tag.toString().toLowerCase().contains(term.toLowerCase()) && !results.contains(chapter)) {
results.add(chapter);
}
}
}
}
return results;
}
}
| 30.7
| 114
| 0.586726
|
06dc12c093252a175ec0b25f740d2943dc1bc900
| 1,250
|
package com.muzi.weshop.view.activity;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.muzi.weshop.R;
import com.muzi.weshop.common.base.BaseActivity;
import com.muzi.weshop.common.contants.Constants;
import com.muzi.weshop.model.LoginModel;
import com.orhanobut.hawk.Hawk;
public class SplashActivity extends BaseActivity {
@Override
protected boolean hideStatusBar() {
return true;
}
@Override
protected int attachedLayout() {
return R.layout.activity_splash;
}
@Override
protected void initViews() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
LoginModel loginModel = Hawk.get(Constants.LOGIN_INFO);
if(loginModel == null){
startActivity(new Intent(SplashActivity.this , LoginActivity.class));
finish();
}else{
startActivity(new Intent(SplashActivity.this , MainActivity.class));
finish();
}
}
} , 3000);
}
@Override
protected void requestData() {
}
}
| 25
| 89
| 0.6176
|
23e936ee30535d2716d4a2101559a4e20d40ec50
| 6,669
|
/*
* Copyright 2016 Johann Reyes
*
* 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.vaporwarecorp.mirror.feature.pocketsphinx;
import com.robopupu.api.dependency.Provides;
import com.robopupu.api.dependency.Scope;
import com.robopupu.api.plugin.Plug;
import com.robopupu.api.plugin.Plugin;
import com.robopupu.api.plugin.PluginBus;
import com.vaporwarecorp.mirror.app.MirrorAppScope;
import com.vaporwarecorp.mirror.component.AppManager;
import com.vaporwarecorp.mirror.component.EventManager;
import com.vaporwarecorp.mirror.component.SoundManager;
import com.vaporwarecorp.mirror.event.CommandEvent;
import com.vaporwarecorp.mirror.feature.alexa.AlexaCommandManager;
import com.vaporwarecorp.mirror.feature.common.AbstractMirrorManager;
import com.vaporwarecorp.mirror.feature.houndify.HoundifyCommandManager;
import com.vaporwarecorp.mirror.feature.speechtotext.SpeechToTextManager;
import edu.cmu.pocketsphinx.Assets;
import edu.cmu.pocketsphinx.Hypothesis;
import edu.cmu.pocketsphinx.RecognitionListener;
import edu.cmu.pocketsphinx.SpeechRecognizer;
import timber.log.Timber;
import java.io.File;
import java.io.IOException;
import static com.vaporwarecorp.mirror.component.CommandManager.*;
import static edu.cmu.pocketsphinx.SpeechRecognizerSetup.defaultSetup;
@Plugin
@Scope(MirrorAppScope.class)
@Provides(PocketSphinxManager.class)
public class PocketSphinxManagerImpl extends AbstractMirrorManager implements PocketSphinxManager, RecognitionListener {
// ------------------------------ FIELDS ------------------------------
private static final String MENU_SEARCH = "MENU";
@Plug
AlexaCommandManager mAlexaCommandManager;
@Plug
AppManager mAppManager;
@Plug
EventManager mEventManager;
@Plug
HoundifyCommandManager mHoundifyCommandManager;
@Plug
SoundManager mSoundManager;
@Plug
SpeechToTextManager mSpeechToTextManager;
private SpeechRecognizer mRecognizer;
// ------------------------ INTERFACE METHODS ------------------------
// --------------------- Interface MirrorManager ---------------------
@Override
public void onFeaturePause() {
if (mRecognizer == null) {
return;
}
mRecognizer.stop();
}
@Override
public void onFeatureResume() {
if (mRecognizer == null) {
return;
}
mRecognizer.stop();
mRecognizer.startListening(MENU_SEARCH);
}
@Override
public void onFeatureStart() {
try {
final File assetsDir = new Assets(mAppManager.getAppContext()).syncAssets();
mRecognizer = defaultSetup()
.setAcousticModel(new File(assetsDir, "en-us-ptm"))
.setDictionary(new File(assetsDir, "6117.dic"))
.setKeywordThreshold(1e-40f)
.setBoolean("-allphone_ci", true)
.setFloat("-lw", 6.5)
.getRecognizer();
mRecognizer.addListener(this);
final File menuKeywords = new File(assetsDir, "menu.gram");
mRecognizer.addKeywordSearch(MENU_SEARCH, menuKeywords);
if (!PluginBus.isPlugged(AlexaCommandManager.class)) {
PluginBus.plug(AlexaCommandManager.class);
}
if (!PluginBus.isPlugged(HoundifyCommandManager.class)) {
PluginBus.plug(HoundifyCommandManager.class);
}
if (!PluginBus.isPlugged(SpeechToTextManager.class)) {
PluginBus.plug(SpeechToTextManager.class);
}
mAlexaCommandManager.start();
mHoundifyCommandManager.start();
mSpeechToTextManager.start();
} catch (IOException e) {
Timber.e(e, e.getMessage());
throw new RuntimeException(e);
} catch (RuntimeException e) {
Timber.e(e, e.getMessage());
throw e;
}
}
@Override
public void onFeatureStop() {
mAlexaCommandManager.stop();
mHoundifyCommandManager.stop();
mSpeechToTextManager.stop();
if (mRecognizer == null) {
return;
}
mRecognizer.cancel();
mRecognizer.shutdown();
mRecognizer = null;
}
// --------------------- Interface RecognitionListener ---------------------
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onEndOfSpeech() {
if (!mRecognizer.getSearchName().equals(MENU_SEARCH)) {
mRecognizer.stop();
mRecognizer.startListening(MENU_SEARCH);
}
}
@Override
public void onPartialResult(Hypothesis hypothesis) {
if (hypothesis == null) return;
final String text = hypothesis.getHypstr().trim().toLowerCase();
if (KEYWORD_ALEXA.equals(text) || KEYWORD_HOUNDIFY.equals(text) || KEYWORD_GOOGLE.equals(text)) {
mRecognizer.stop();
}
}
@Override
public void onResult(Hypothesis hypothesis) {
if (hypothesis == null) return;
final String text = hypothesis.getHypstr().trim().toLowerCase();
if (KEYWORD_ALEXA.equals(text) && mAlexaCommandManager.isEnabled()) {
mEventManager.post(new CommandEvent(CommandEvent.TYPE_COMMAND_START, KEYWORD_ALEXA));
mAlexaCommandManager.voiceSearch();
} else if (KEYWORD_HOUNDIFY.equals(text) && mHoundifyCommandManager.isEnabled()) {
mEventManager.post(new CommandEvent(CommandEvent.TYPE_COMMAND_START, KEYWORD_HOUNDIFY));
mHoundifyCommandManager.voiceSearch();
} else if (KEYWORD_GOOGLE.equals(text)) {
mEventManager.post(new CommandEvent(CommandEvent.TYPE_COMMAND_START, KEYWORD_GOOGLE));
mSpeechToTextManager.voiceSearch();
} else {
mRecognizer.startListening(MENU_SEARCH);
}
}
@Override
public void onError(Exception e) {
Timber.e(e, "onError");
mRecognizer.startListening(MENU_SEARCH);
}
@Override
public void onTimeout() {
Timber.e("onTimeout");
mRecognizer.startListening(MENU_SEARCH);
}
}
| 33.852792
| 120
| 0.653621
|
1a76df839a95c81484bf9d9a4e9c37b884e8f0b2
| 2,801
|
package com.refinedmods.refinedstorage2.api.network.node.controller;
import com.refinedmods.refinedstorage2.api.core.Action;
import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorage;
import com.refinedmods.refinedstorage2.api.network.energy.EnergyStorageImpl;
import com.refinedmods.refinedstorage2.api.network.energy.InfiniteEnergyStorage;
import com.refinedmods.refinedstorage2.api.network.node.NetworkNodeImpl;
public class ControllerNetworkNode extends NetworkNodeImpl implements EnergyStorage {
private final EnergyStorage energyStorage;
private final ControllerListener listener;
public ControllerNetworkNode(long stored, long capacity, ControllerType type, ControllerListener listener) {
this.energyStorage = buildEnergyStorage(capacity, type);
this.energyStorage.receive(stored, Action.EXECUTE);
this.listener = listener;
}
private static EnergyStorage buildEnergyStorage(long capacity, ControllerType type) {
return type == ControllerType.CREATIVE ? new InfiniteEnergyStorage() : new EnergyStorageImpl(capacity);
}
public ControllerEnergyState getState() {
if (!isActive()) {
return ControllerEnergyState.OFF;
}
double pct = (double) energyStorage.getStored() / (double) energyStorage.getCapacity();
if (pct >= 0.4) {
return ControllerEnergyState.ON;
}
if (pct >= 0.3) {
return ControllerEnergyState.NEARLY_ON;
}
if (pct >= 0.01) {
return ControllerEnergyState.NEARLY_OFF;
}
return ControllerEnergyState.OFF;
}
public long getActualStored() {
return energyStorage.getStored();
}
public long getActualCapacity() {
return energyStorage.getCapacity();
}
@Override
public long getStored() {
if (!isActive()) {
return 0;
}
return energyStorage.getStored();
}
@Override
public long getCapacity() {
if (!isActive()) {
return 0;
}
return energyStorage.getCapacity();
}
@Override
public long receive(long amount, Action action) {
long remainder = energyStorage.receive(amount, action);
if (remainder != amount && action == Action.EXECUTE) {
listener.onEnergyChanged();
}
return remainder;
}
@Override
public long extract(long amount, Action action) {
if (!isActive()) {
return 0;
}
long extracted = energyStorage.extract(amount, action);
if (extracted > 0L && action == Action.EXECUTE) {
listener.onEnergyChanged();
}
return extracted;
}
@Override
public long getEnergyUsage() {
return 0L;
}
}
| 31.122222
| 112
| 0.652981
|
9dbbca10ca5d7e5fc3b7a69873e31883e79b8e0a
| 5,317
|
package vn.edu.tlu.hatrang.autoRWRMTN.internal.task;
import java.awt.Color;
import java.awt.Paint;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkFactory;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyNode;
import org.cytoscape.model.CyRow;
import org.cytoscape.model.CyTable;
import org.cytoscape.model.CyTableUtil;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;
import org.cytoscape.view.presentation.property.NodeShapeVisualProperty;
import org.cytoscape.view.vizmap.VisualPropertyDependency;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.view.vizmap.mappings.BoundaryRangeValues;
import org.cytoscape.view.vizmap.mappings.ContinuousMapping;
import org.cytoscape.view.vizmap.mappings.DiscreteMapping;
import org.cytoscape.view.vizmap.mappings.PassthroughMapping;
import org.cytoscape.work.ObservableTask;
import org.cytoscape.work.SynchronousTaskManager;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskManager;
import org.cytoscape.work.TaskMonitor;
import org.cytoscape.work.json.JSONResult;
import com.google.gson.Gson;
import vn.edu.tlu.hatrang.autoRWRMTN.internal.RESTmodel.EvidenceResult;
import vn.edu.tlu.hatrang.autoRWRMTN.internal.RESTmodel.RankedResult;
import vn.edu.tlu.hatrang.autoRWRMTN.internal.model.Common;
public class ExamineRankedGenesandDiseasesTask implements ObservableTask {
CyNetworkFactory networkFactory;
CyNetworkManager networkManager;
CyNetwork network;
TaskManager cyTaskManager;
SynchronousTaskManager cySynchronousTaskManager;
public static ArrayList<EvidenceResult> result;
private volatile boolean interrupted = false;
public ExamineRankedGenesandDiseasesTask(CyNetworkFactory networkFactory, CyNetworkManager networkManager,
CyNetwork network, TaskManager cyTaskManager, SynchronousTaskManager cySynchronousTaskManager) {
super();
this.networkFactory = networkFactory;
this.networkManager = networkManager;
this.network = network;
this.cyTaskManager = cyTaskManager;
this.cySynchronousTaskManager = cySynchronousTaskManager;
}
@Override
public void cancel() {
// TODO Auto-generated method stub
interrupted = true;
}
@Override
public void run(TaskMonitor taskMonitor) throws Exception {
// TODO Auto-generated method stu
// network_gene and network_disease
CyNetwork network_rna = Common.getNetworkByName(networkManager, Common.DiseaseTerm);
if (interrupted){
return;
}
List<CyNode> selected_rnas = CyTableUtil.getNodesInState(network_rna, "selected", true);
System.out.println(selected_rnas.size());
if (selected_rnas.size()==0){
taskMonitor.setStatusMessage("You should select at least one row in node table");
//JOptionPane.showMessageDialog(null, "You should select at least one row to find evidence");
return;
}
CyTable nodeTable = network_rna.getDefaultNodeTable();
if (nodeTable.getColumn("PubMed (PudMedIDs)") == null) {
nodeTable.createColumn("PubMed (PudMedIDs)", String.class, false);
}
result=new ArrayList<>();
for (CyNode node : selected_rnas) {
if (interrupted){
return;
}
String RID = network_rna.getRow(node).get("shared name", String.class);
taskMonitor.setStatusMessage("Finding evidences of association of Keyword \"" + Common.DiseaseTerm
+ "\" and miRNA " + RID);
System.out.println("Finding evidences of association of Keyword \"" + Common.DiseaseTerm + "\" and miRNA "
+ RID);
String searchterm = "(" + Common.DiseaseTerm + "[Title/Abstract] AND " + RID + "[Title/Abstract]) OR ("
+ Common.DiseaseTerm + "[MeSH%20Terms] AND " + RID + ")";
Set<String> IDs = new TreeSet<String>();
System.out.println("PubMed query: " + searchterm);
taskMonitor.setStatusMessage("Finding evidences of association of Keyword \"" + Common.DiseaseTerm
+ "\" and miRNA " + RID + ". Currently found " + Common.numOfEvidence);
EvidenceResult er=new EvidenceResult();
er.setRnaName(RID);
IDs = Common.getPubMedIDFromPubMedSearch(searchterm,er.getInfo());
er.setPubMedIds(IDs);
result.add(er);
if (IDs.size() > 0) {
if (interrupted){
return;
}
String IDsStr = IDs.toString().substring(1, IDs.toString().length() - 1);
nodeTable.getRow(node.getSUID()).set("PubMed (PudMedIDs)", IDsStr);
}
}
}
public static String getJson(ArrayList<EvidenceResult> listresult) {
return new Gson().toJson(listresult);
}
@SuppressWarnings("unchecked")
@Override
public <R> R getResults(Class<? extends R> type) {
// TODO Auto-generated method stub
if (type.equals(String.class)) {
return (R) getJson(result);
} else if (type.equals(JSONResult.class)) {
JSONResult res = () -> {
return getJson(result);
};
return (R) (res);
} else {
return null;
}
}
@Override
public List<Class<?>> getResultClasses() {
// TODO Auto-generated method stub
return Arrays.asList(String.class, JSONResult.class);
}
}
| 33.23125
| 109
| 0.753056
|
e672ee65431052d020a16136d850a08167698f21
| 639
|
/*
*
* * All Application code is Copyright 2016, The Department of Homeland Security (DHS), U.S. Customs and Border Protection (CBP).
* *
* * Please see LICENSE.txt for details.
*
*/
package gov.gtas.services.matcher;
class ProcessedMatcherResults {
private boolean caseCreated = false;
private int hitCounter;
void setCaseCreated(boolean caseCreated) {
this.caseCreated = caseCreated;
}
boolean getCaseCreated() {
return caseCreated;
}
void setHitCounter(int hitCounter) {
this.hitCounter = hitCounter;
}
int getHitCounter() {
return hitCounter;
}
}
| 19.96875
| 130
| 0.657277
|
fadcea497105c3756e4b14c36e3ce07e7b5dd99c
| 3,473
|
package test;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import utils.ScreenShot;
import pages.ListPage;
public class CreateListTest {
private static Logger LOGGER = Logger.getGlobal();
private static RemoteWebDriver driver;
private static ExtentReports extent;
private static ExtentTest test;
@BeforeAll
public static void init() {
extent = new ExtentReports("src/test/resources/reports/report1.html", true);
test = extent.startTest("ExtentDemo");
System.setProperty("webdriver.chrome.driver",
"src/test/resources/chromedriver.exe");
ChromeOptions cOptions = new ChromeOptions();
cOptions.setHeadless(false);
driver = new ChromeDriver(cOptions);
cOptions.setCapability("profile.default_content_setting_values.cookies", 2);
cOptions.setCapability("network.cookie.cookieBehavior", 2);
cOptions.setCapability("profile.block_third_party_cookies", true);
driver.manage().window().setSize(new Dimension(1366, 768));
}
@BeforeEach
public void setup() {
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try {
driver.get(ListPage.URL);
} catch (TimeoutException e) {
System.out.println("Page: " + ListPage.URL + " did not load within 30 seconds!");
}
}
@AfterAll
public static void finalTearDown() {
LOGGER.warning("Closing webdriver instance!");
driver.quit();
LOGGER.info("Webdriver closed successfully!");
extent.endTest(test);
extent.flush();
extent.close();
}
@Test
public void createList() throws InterruptedException {
LOGGER.warning("Connecting to To Do List....");
new WebDriverWait(driver, 5);
String tNum = "1";
String tText = "test";
ListPage Page = PageFactory.initElements(driver, ListPage.class);
Page.NumInfo(tNum);
Page.TextInfo(tText);
Page.clickCreate();
driver.getPageSource().contains("QUERY SUCCESS");
}
@Test
public void ReadOneList() throws InterruptedException {
LOGGER.warning("Connecting to To Do List....");
new WebDriverWait(driver, 5);
ListPage Page = PageFactory.initElements(driver, ListPage.class);
Page.clickReadAll();
driver.getPageSource().contains("QUERY SUCCESS");
}
@Test
public void DeleteOneList() throws InterruptedException {
LOGGER.warning("Connecting to To Do List....");
new WebDriverWait(driver, 5);
String tNum = "1";
String tText = "test";
String tId = "1";
ListPage Page = PageFactory.initElements(driver, ListPage.class);
Page.NumInfo(tNum);
Page.TextInfo(tText);
Page.IdInfo(tId);
Page.clickDelete();
driver.getPageSource().contains("QUERY SUCCESS");
}
}
| 27.132813
| 84
| 0.731068
|
176e183bb7ddd7295fdaec40f83d8c589d1a4099
| 3,653
|
/*
* Copyright 2014 peter.
*
* 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 uk.trainwatch.apps.signalanalyser.monitor;
import java.io.IOException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.logging.Level;
import uk.trainwatch.apps.signalanalyser.AbstractApp;
import uk.trainwatch.nrod.td.berth.BerthAreaMap;
import uk.trainwatch.nrod.td.model.BerthCancel;
import uk.trainwatch.nrod.td.model.BerthInterpose;
import uk.trainwatch.nrod.td.model.BerthStep;
import uk.trainwatch.nrod.td.model.Heartbeat;
import uk.trainwatch.nrod.td.model.TDMessage;
import uk.trainwatch.nrod.td.model.TDMessageFactory;
import uk.trainwatch.nrod.td.model.TDVisitor;
import uk.trainwatch.rabbitmq.RabbitMQ;
import uk.trainwatch.util.counter.RateMonitor;
/**
*
* @author peter
*/
public class Monitor
extends AbstractApp
{
private final String signalArea;
private final String queueName;
private final String routingKey;
public Monitor( String signalArea )
{
this.signalArea = signalArea;
routingKey = "nr.td.area." + signalArea;
queueName = "signal.map." + signalArea;
}
@Override
protected void setupApplication()
throws IOException
{
Consumer<TDMessage> rawMonitor = RateMonitor.log( LOG, "Receive " + routingKey );
Consumer<TDMessage> tdViewer = new TDVisitor()
{
@Override
public void visit( BerthCancel s )
{
LOG.log( Level.INFO, () -> "Canc " + s.getDescr() + " " + s.getFrom() );
}
@Override
public void visit( BerthInterpose s )
{
LOG.log( Level.INFO, () -> "Put " + s.getDescr() + " " + s.getTo() );
}
@Override
public void visit( BerthStep s )
{
LOG.log( Level.INFO, () -> "Move " + s.getDescr() + " " + s.getFrom() + " -> " + s.getTo() );
}
@Override
public void visit( Heartbeat s )
{
LOG.log( Level.INFO, () -> "Heart " + s.getReport_time() );
}
};
RabbitMQ.queueStream( getRabbitmq(),
queueName,
routingKey,
s -> s.map( RabbitMQ.toJsonObject.andThen( TDMessageFactory.INSTANCE ) ).
filter( Objects::nonNull ).
forEach( rawMonitor.andThen( tdViewer ) )
);
}
public static void main( String... args )
throws Exception
{
if( args.length != 1 ) {
LOG.log( Level.SEVERE, "A signalling area is required" );
System.exit( 1 );
}
String area = args[0].toUpperCase();
if( area.isEmpty() || area.length() != 2 ) {
LOG.log( Level.SEVERE, "Signalling area code is 2 characters only." );
System.exit( 1 );
}
LOG.log( Level.INFO, () -> "Initialising Network Rail Signal Analyser for area " + area );
new Monitor( area ).run();
}
}
| 31.222222
| 109
| 0.590474
|
33f7ef763ec8de8a1a9df2bed81b3e4f4fe743bb
| 493
|
package wang.icopy.security.domain;
import lombok.*;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class City implements Serializable {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String state;
}
| 17
| 43
| 0.756592
|
8ff7e326d0ed7929e61f1fe632e0819a5f8a27e0
| 1,957
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.axiom.ts.dom.document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.axiom.ts.dom.DOMTestCase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
/**
* Tests the behavior of {@link Document#adoptNode(Node)} if the node is
* already owned by the document. In this case, the method is still expected
* to detach the node from its parent.
*/
public class TestAdoptNodeToSameDocument extends DOMTestCase {
public TestAdoptNodeToSameDocument(DocumentBuilderFactory dbf) {
super(dbf);
}
protected void runTest() throws Throwable {
DocumentBuilder builder = dbf.newDocumentBuilder();
Document document = builder.newDocument();
Element parent = document.createElementNS(null, "test");
Text node = document.createTextNode("test");
parent.appendChild(node);
assertSame(node, document.adoptNode(node));
assertSame(document, node.getOwnerDocument());
assertNull(node.getParentNode());
assertNull(parent.getFirstChild());
}
}
| 37.634615
| 76
| 0.736842
|
a42cc7696e7ea6e177aebc48eb73e51b03e8a05b
| 6,797
|
/*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.social.vkontakte.api;
import java.util.List;
/**
* Defines operations for interacting with a user's friends.
* @author vkolodrevskiy
*/
public interface IFriendsOperations {
public final static String DEFAULT_FIELDS = "first_name,last_name,photo_50,photo_100,photo_200,contacts,bdate,sex,screen_name";
/**
* Retrieves a list of user friends for the current authorized user.
* @return a list of user friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<VKontakteProfile> get();
/**
* Retrieves a list of user friends for the current authorized user.
* @param fields VKontakte fields to retrieve, comma-delimited.
* @return a list of user friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<VKontakteProfile> get(String fields);
/**
* Retrieves a list of user friends for specified user unique identifier.
* @param userId user unique identifier for which to get friends.
* @return a list of user friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<VKontakteProfile> get(Long userId);
/**
* Retrieves a list of user friends for specified user unique identifier.
* @param userId user unique identifier for which to get friends.
* @param fields VKontakte fields to retrieve, comma-delimited.
* @return a list of user friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<VKontakteProfile> get(Long userId, String fields);
/**
* Retrieves a list of user friends for specified user unique identifier.
* @param userId user unique identifier for which to get friends.
* @param fields VKontakte fields to retrieve, comma-delimited.
* @param count Number(positive number) of friends to return. If you want to return all friends pass negative number.
* @param offset Offset(positive number) needed to return a specific subset of friends.
* @return a list of user friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<VKontakteProfile> get(Long userId, String fields, int count, int offset);
/**
* Retrieves a list of user friends id's that are online for the current authorized user.
* Result <code>List</code> will contain 2 lists if you set <code>onlineMobile</code> parameter to <code>true</code>.
* First list will contain id's of online friends that use website, second list will contain id's of friends using mobile.
* @param onlineMobile <code>true</code> to return an additional online_mobile field, <code>false</code> otherwise.
* @param count Number(positive number) of friends to return. If you want to return all friends pass negative number.
* @param offset Offset(positive number) needed to return a specific subset of friends.
* @return a list of user online friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<List<String>> getOnline(boolean onlineMobile, int count, int offset);
/**
* Retrieves a list of user friends that are online for specified user unique identifier.
* Result <code>List</code> will contain 2 lists if you set <code>onlineMobile</code> parameter to <code>true</code>.
* First list will contain id's of online friends that use website, second list will contain id's of friends using mobile.
* @param userId user unique identifier for which to get friends.
* @param onlineMobile <code>true</code> to return an additional online_mobile field, <code>false</code> otherwise.
* @param count Number(positive number) of friends to return. If you want to return all friends pass negative number.
* @param offset Offset(positive number) needed to return a specific subset of friends.
* @return a list of user online friends profiles.
* @throws org.springframework.social.ApiException if there is an error while communicating with VKontakte.
* @throws org.springframework.social.MissingAuthorizationException if VKontakteTemplate was not created with an access token.
* @throws org.springframework.social.vkontakte.api.VKontakteErrorException if VKontakte returned error.
*/
public List<List<String>> getOnline(Long userId, boolean onlineMobile, int count, int offset);
}
| 63.523364
| 131
| 0.755775
|
4cc27d941899f36747ea404b513e469540dc95c8
| 13,581
|
/*
* Copyright (C) 2022 Steve Jrong
*
* GitHub Homepage: https://www.github.com/SteveJrong
* Gitee Homepage: https://gitee.com/stevejrong1024
*
* 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 com.stevejrong.music.factory.provider.service.music.metadata.resolver.persist.impl;
import com.google.common.collect.Lists;
import com.stevejrong.music.factory.common.enums.ID3v2FramesForMP3Enum;
import com.stevejrong.music.factory.common.util.*;
import com.stevejrong.music.factory.spi.service.music.metadata.resolver.persist.AbstractAudioFileMetadataPersistResolver;
import com.stevejrong.music.factory.spi.service.music.metadata.resolver.persist.IAudioFileMetadataPersistResolver;
import com.stevejrong.music.factory.spi.service.music.metadata.resolver.query.IAudioFileMetadataQueryResolver;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.TagField;
import org.jaudiotagger.tag.id3.*;
import org.jaudiotagger.tag.id3.framebody.FrameBodyTDAT;
import org.jaudiotagger.tag.id3.framebody.FrameBodyTYER;
import org.jaudiotagger.tag.images.Artwork;
import org.jaudiotagger.tag.images.ArtworkFactory;
import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
/**
* MP3音频文件的元数据存储器
*
* @author Steve Jrong
* @since 1.0
*/
public class Mp3MetadataPersistResolver extends AbstractAudioFileMetadataPersistResolver implements IAudioFileMetadataPersistResolver {
@Override
public void setAudioFile(AudioFile audioFile) {
super.audioFile = audioFile;
}
@Override
public void setIAudioFileMetadataQueryResolver(IAudioFileMetadataQueryResolver metadataQueryResolver) {
super.metadataQueryResolver = metadataQueryResolver;
}
@Override
public void setSongTitle(String songTitle) {
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
ID3v1Tag id3v1Tag = Mp3Util.checkID3v1Tag((MP3File) getAudioFile());
// 先处理ID3v2标签
String songTitleForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.TIT2.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(songTitle) && StringUtils.isBlank(songTitleForID3v2Tag)) {
// 当ID3v2标签中没有歌曲名称时,需设置ID3v2标签中的歌曲名称信息
setFieldAndCommit(id3v2Tag, FieldKey.TITLE, songTitle, getAudioFile());
}
// 再处理ID3v1标签
List<TagField> tagField = Optional.ofNullable(id3v1Tag.getFields(FieldKey.TITLE)).orElse(Lists.newArrayList());
if (StringUtils.isNotBlank(songTitle) && (CollectionUtils.isEmpty(tagField) || StringUtils.isBlank(((ID3v1TagField) tagField.get(0)).getContent()))) {
// 当ID3v1标签中没有歌曲名称时,需设置ID3v1标签中的歌曲名称信息
setFieldAndCommit(id3v1Tag, FieldKey.TITLE, new String(songTitle.getBytes(), StandardCharsets.ISO_8859_1), getAudioFile());
}
}
@Override
public void setSongArtist(String songArtist) {
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
ID3v1Tag id3v1Tag = Mp3Util.checkID3v1Tag((MP3File) getAudioFile());
// 先处理ID3v2标签
String songArtistForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.TPE1.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(songArtist) && StringUtils.isBlank(songArtistForID3v2Tag)) {
// 当ID3v2标签中没有歌曲艺术家时,需设置ID3v2标签中的歌曲艺术家信息
setFieldAndCommit(id3v2Tag, FieldKey.ARTIST, songArtist, getAudioFile());
}
// 再处理ID3v1标签
List<TagField> tagField = Optional.ofNullable(id3v1Tag.getFields(FieldKey.ARTIST)).orElse(Lists.newArrayList());
if (StringUtils.isNotBlank(songArtist) && (CollectionUtils.isEmpty(tagField) || StringUtils.isBlank(((ID3v1TagField) tagField.get(0)).getContent()))) {
// 当ID3v1标签中没有歌曲艺术家时,需设置ID3v1标签中的歌曲艺术家信息
setFieldAndCommit(id3v1Tag, FieldKey.ARTIST, new String(songArtist.getBytes(), StandardCharsets.ISO_8859_1), getAudioFile());
}
}
@Override
public void setAlbumName(String albumName) {
MP3File mp3File = (MP3File) getAudioFile();
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
ID3v1Tag id3v1Tag = Mp3Util.checkID3v1Tag((MP3File) getAudioFile());
// 先处理ID3v2标签
String albumNameForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.TALB.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(albumName) && StringUtils.isBlank(albumNameForID3v2Tag)) {
// 当ID3v2标签中没有歌曲所属的专辑名称时,需设置ID3v2标签中的歌曲所属的专辑名称信息
setFieldAndCommit(id3v2Tag, FieldKey.ALBUM, albumName, getAudioFile());
}
// 再处理ID3v1标签
List<TagField> tagField = Optional.ofNullable(id3v1Tag.getFields(FieldKey.ALBUM)).orElse(Lists.newArrayList());
if (StringUtils.isNotBlank(albumName) && (CollectionUtils.isEmpty(tagField) || StringUtils.isBlank(((ID3v1TagField) tagField.get(0)).getContent()))) {
// 当ID3v1标签中没有歌曲所属的专辑名称时,需设置ID3v1标签中的歌曲所属的专辑名称信息
setFieldAndCommit(id3v1Tag, FieldKey.ALBUM, new String(albumName.getBytes(), StandardCharsets.ISO_8859_1), getAudioFile());
}
}
@Override
public void setAlbumPicture(byte[] albumPictureByteArray) {
// 专辑封面不支持ID3v1标签
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
if (ArrayUtils.isEmpty(albumPictureByteArray)) {
// 若第三方在线音乐服务平台中都没有查询到专辑图片,则使用默认专辑图片
albumPictureByteArray = FileUtil.getDefaultAlbumPictureByteArray();
}
// 读取音频文件内的专辑封面图片
byte[] originalAlbumPictureByteArray = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.APIC.getValue(), "PictureData", id3v2Tag);
BufferedImage originalAlbumPicture = null;
if (ArrayUtils.isNotEmpty(originalAlbumPictureByteArray)) {
originalAlbumPicture = ArrayUtil.getBufferedImageByPictureByteArray(originalAlbumPictureByteArray);
}
if (ArrayUtils.isEmpty(originalAlbumPictureByteArray)
|| (null != originalAlbumPicture && originalAlbumPicture.getWidth() * originalAlbumPicture.getHeight() < 500 * 500)) {
// 先删除专辑封面属性
id3v2Tag.deleteField(FieldKey.COVER_ART);
// 再设置新的专辑封面图片
Artwork artwork = ArtworkFactory.createArtworkFromMetadataBlockDataPicture(AlbumPictureUtil.buildMetadataBlockDataPicture(albumPictureByteArray));
setFieldAndCommit(id3v2Tag, artwork, getAudioFile());
}
}
@Override
public void setSongLyrics(String songLyrics) {
// 歌曲内嵌歌词不支持ID3v1标签
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
String songLyricsForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.USLT.getValue(), "Lyrics", id3v2Tag);
if (StringUtils.isNotBlank(songLyrics) && StringUtils.isBlank(songLyricsForID3v2Tag)) {
// 当ID3v2标签中没有歌曲内嵌歌词时,需设置ID3v2标签中的歌曲内嵌歌词信息
setFieldAndCommit(id3v2Tag, FieldKey.LYRICS, songLyrics, getAudioFile());
}
}
@Override
public void setAlbumArtist(String albumArtist) {
// 歌曲所属专辑的艺术家不支持ID3v1标签
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
String albumArtistForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.TPE2.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(albumArtist) && StringUtils.isBlank(albumArtistForID3v2Tag)) {
// 当ID3v2标签中没有歌曲所属专辑的艺术家时,需设置ID3v2标签中的歌曲所属专辑的艺术家信息
setFieldAndCommit(id3v2Tag, FieldKey.ALBUM_ARTIST, albumArtist, getAudioFile());
}
}
@Override
public void setAlbumPublishDate(LocalDate albumPublishDate) {
MP3File mp3File = (MP3File) getAudioFile();
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
ID3v1Tag id3v1Tag = Mp3Util.checkID3v1Tag((MP3File) getAudioFile());
// 先处理ID3v2标签
// ID3v2标签中的发布时间,支持年月日
List<TagField> tagFieldList = Optional.ofNullable(id3v2Tag.getFields(ID3v2FramesForMP3Enum.TYERTDAT.getValue())).orElse(Lists.newArrayList());
Optional<AbstractTagFrameBody> publishYearBody, publishMonthAndDayBody;
String publishYear = null, publishMonthAndDay = null;
if (CollectionUtils.isNotEmpty(tagFieldList)) {
publishYearBody = ((TyerTdatAggregatedFrame) tagFieldList.get(0)).getFrames().stream().map(AbstractTagFrame::getBody)
.filter(item -> item instanceof FrameBodyTYER)
.findFirst();
publishMonthAndDayBody = ((TyerTdatAggregatedFrame) tagFieldList.get(0)).getFrames().stream().map(AbstractTagFrame::getBody)
.filter(item -> item instanceof FrameBodyTDAT)
.findFirst();
publishYear = publishYearBody.get().getObjectValue("Text").toString();
publishMonthAndDay = publishMonthAndDayBody.get().getObjectValue("Text").toString();
}
if (null != albumPublishDate && (StringUtils.isBlank(publishYear) || StringUtils.isBlank(publishMonthAndDay))) {
// 当ID3v2标签中的歌曲所属专辑的发布年份和月日有任意一项缺失时,需设置ID3v2标签中的歌曲所属专辑的发布时间信息
setFieldAndCommit(id3v2Tag, FieldKey.YEAR,
DateTimeUtil.localDateToString(DateTimeUtil.DatePattern.YYYYMMDD_FORMAT.getValue(), albumPublishDate), getAudioFile());
}
// 再处理ID3v1标签
// // ID3v1标签中的发布时间,仅支持年份
List<TagField> tagField = Optional.ofNullable(id3v1Tag.getFields(FieldKey.YEAR)).orElse(Lists.newArrayList());
if (null != albumPublishDate && (CollectionUtils.isEmpty(tagField) || StringUtils.isBlank(((ID3v1TagField) tagField.get(0)).getContent()))) {
// 当ID3v1标签中的歌曲所属专辑的发布年份缺失时,需设置ID3v1标签中的歌曲所属专辑的发布时间信息
setFieldAndCommit(id3v1Tag, FieldKey.YEAR,
new String(DateTimeUtil.localDateToString(DateTimeUtil.DatePattern.YYYYMMDD_FORMAT.getValue(), albumPublishDate).getBytes(), StandardCharsets.ISO_8859_1),
getAudioFile());
}
}
@Override
public void setAlbumDescription(String albumDescription) {
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
// 先处理ID3v2标签
String albumDescriptionForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.COMM.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(albumDescription) && StringUtils.isBlank(albumDescriptionForID3v2Tag)) {
// 当ID3v2标签中没有歌曲所属专辑的描述时,需设置ID3v2标签中的歌曲所属专辑的描述信息
setFieldAndCommit(id3v2Tag, FieldKey.COMMENT, albumDescription, getAudioFile());
}
// 再处理ID3v1标签
// ID3v1标签仅支持ISO-8859-1编码,不支持中文存储,默认不设置
/*List<TagField> tagField = Optional.ofNullable(id3v1Tag.getFields(FieldKey.COMMENT)).orElse(Lists.newArrayList());
if (StringUtils.isNotBlank(albumDescription) && (CollectionUtils.isEmpty(tagField) || StringUtils.isBlank(((ID3v1TagField) tagField.get(0)).getContent()))) {
// 当ID3v1标签中没有歌曲所属专辑的描述时,需设置ID3v1标签中的歌曲所属专辑的描述信息
setFieldAndCommit(id3v1Tag, FieldKey.COMMENT, new String(albumDescription.getBytes(), StandardCharsets.ISO_8859_1), getAudioFile());
}*/
}
@Override
public void setAlbumLanguage(String albumLanguage) {
// 歌曲所属专辑的语言类型不支持ID3v1标签
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
String albumLanguageForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.TLAN.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(albumLanguage) && StringUtils.isBlank(albumLanguageForID3v2Tag)) {
// 当ID3v2标签中没有歌曲所属专辑的语言类型时,需设置ID3v2标签中的歌曲所属专辑的语言类型信息
setFieldAndCommit(id3v2Tag, FieldKey.LANGUAGE, albumLanguage, getAudioFile());
}
}
@Override
public void setAlbumCopyright(String albumCopyright) {
MP3File mp3File = (MP3File) getAudioFile();
// 歌曲所属专辑的版权信息不支持ID3v1标签
AbstractID3v2Tag id3v2Tag = Mp3Util.checkID3v2Tag((MP3File) getAudioFile());
String albumCopyrightForID3v2Tag = Mp3Util.getContentByContentKeyAndMp3FrameNameInID3v2Tag(ID3v2FramesForMP3Enum.TCOP.getValue(), "Text", id3v2Tag);
if (StringUtils.isNotBlank(albumCopyright) && StringUtils.isBlank(albumCopyrightForID3v2Tag)) {
// 当ID3v2标签中没有歌曲所属专辑的版权信息时,需设置ID3v2标签中的歌曲所属专辑的版权信息信息
setFieldAndCommit(id3v2Tag, FieldKey.COPYRIGHT, albumCopyright, getAudioFile());
}
}
}
| 50.865169
| 174
| 0.726309
|
00f1e1ac178c816efcbb6c2f4c8393ef05684b7d
| 812
|
package Thirteenth;
import java.util.ArrayList;
import java.util.Iterator;
public class InteratorTest {
// ArrayList<>:
// 이 녀석은 다양한 데이터 타입을 수용할 수 있게 해준다.
// <String> 문자열, <Integer> 정수, <Float> float 타입 등등
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
//
list.add("one");
list.add("tow");
list.add("three");
list.add("four");
list.add("five");
String s;
// ArrayList 를 순회할 수 있는 정보를 획득함
Iterator e = list.iterator();
// e 를 통해 순회할 수 있는 정보가 있다면
while(e.hasNext()) {
// 해당 위치의 정보를 에 저장하세요.
s = (String) e.next();
System.out.println(s);
}
}
}
| 23.2
| 60
| 0.53202
|
9672b1bf8001a6baf86dae0a89bf9da33954d462
| 132
|
package com.hamzajg.quicktest.sharedkernel.dtos;
public class ProductCategoryDto {
public String id;
public String name;
}
| 18.857143
| 48
| 0.765152
|
4f5316fd95ff0d3f1e41c6948ed52ed6d45e02aa
| 4,113
|
package io.quarkus.benchmark.resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.hibernate.FlushMode;
import org.hibernate.reactive.mutiny.Mutiny;
import io.quarkus.benchmark.model.World;
import io.quarkus.benchmark.repository.WorldRepository;
import io.smallrye.mutiny.Uni;
@Produces(MediaType.APPLICATION_JSON)
@Path("/")
public class DbResource {
@Inject
WorldRepository worldRepository;
@GET
@Path("db")
public Uni<World> db() {
return randomWorld();
}
@GET
@Path("queries")
public Uni<Collection<World>> queries(@QueryParam("queries") String queries) {
return worldRepository.inSession(session -> randomWorldForRead(session, parseQueryCount(queries)));
}
private Uni<Collection<World>> randomWorldForRead(Mutiny.Session session, int count) {
Set<Integer> ids = new HashSet<>(count);
int counter = 0;
while (counter < count) {
counter += ids.add(Integer.valueOf(randomWorldNumber())) ? 1 : 0;
}
return worldRepository.find(session, ids);
}
@GET
@Path("updates")
public Uni<Collection<World>> updates(@QueryParam("queries") String queries) {
return worldRepository.inSession(session -> {
// FIXME: not supported
// session.setJdbcBatchSize(worlds.size());
session.setFlushMode(FlushMode.MANUAL);
var worlds = randomWorldForRead(session, parseQueryCount(queries));
return worlds.flatMap(worldsCollection -> {
worldsCollection.forEach( w -> {
//Read the one field, as required by the following rule:
// # vi. At least the randomNumber field must be read from the database result set.
final int previousRead = w.getRandomNumber();
//Update it, but make sure to exclude the current number as Hibernate optimisations would have us "fail"
//the verification:
w.setRandomNumber(randomWorldNumber(previousRead));
} );
return worldRepository.update(session, worldsCollection);
});
});
}
private Uni<World> randomWorld() {
return worldRepository.find(randomWorldNumber());
}
private int randomWorldNumber() {
return 1 + ThreadLocalRandom.current().nextInt(10000);
}
/**
* Also according to benchmark requirements, except that in this special case
* of the update test we need to ensure we'll actually generate an update operation:
* for this we need to generate a random number between 1 to 10000, but different
* from the current field value.
* @param previousRead
* @return
*/
private int randomWorldNumber(final int previousRead) {
//conceptually split the random space in those before previousRead,
//and those after: this approach makes sure to not affect the random characteristics.
final int trueRandom = ThreadLocalRandom.current().nextInt(9999) + 2;
if (trueRandom<=previousRead) {
//all figures equal or before the current field read need to be shifted back by one
//so to avoid hitting the same number while not affecting the distribution.
return trueRandom - 1;
}
else {
//Those after are generated by taking the generated value 2...10000 as is.
return trueRandom;
}
}
private int parseQueryCount(String textValue) {
if (textValue == null) {
return 1;
}
int parsedValue;
try {
parsedValue = Integer.parseInt(textValue);
} catch (NumberFormatException e) {
return 1;
}
return Math.min(500, Math.max(1, parsedValue));
}
}
| 35.153846
| 124
| 0.63822
|
2a273288b854ded6a50a6564f8e14f5c404eecde
| 7,802
|
package com.example.android.bluetoothlegatt;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by quangta93 on 3/26/15.
*/
public class BleDeviceListFragment extends ListFragment {
private static final String TAG = BleDeviceListFragment.class.getSimpleName();
private static final long SCAN_PERIOD = 5000;
private DeviceScanActivity mActivity;
private BleDeviceListAdapter mListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private Handler mHandler = new Handler();
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
/**
* @scanRecord the content of advertisement record offered by the remote device
*/
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "LeScanCallback: new device = " + device.getName());
if (device == null) return;
mListAdapter.addDevice(device);
}
});
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "on create");
mActivity = (DeviceScanActivity) getActivity();
mBluetoothAdapter = mActivity.getBluetoothAdapter();
mListAdapter = new BleDeviceListAdapter();
setListAdapter(mListAdapter);
setHasOptionsMenu(true);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, " on resume");
if (mActivity.getCurrentTab() == DeviceScanPagerAdapter.BLUETOOTH_TAB) {
bleScan();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(TAG, "Button pressed for " + TAG);
switch (item.getItemId()) {
case R.id.menu_scan: {
bleScan();
return true;
}
case R.id.menu_stop: {
stopScan();
return true;
}
}
return super.onOptionsItemSelected(item);
}
/**
* Scan for Ble devices.
*/
public void bleScan() {
Log.d(TAG, "Start LE Scan");
if (mBluetoothAdapter == null) {
mBluetoothAdapter = mActivity.getBluetoothAdapter();
}
if (mBluetoothAdapter == null) {
Log.w(TAG, "Cannot get bluetooth adapter.");
return;
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, DeviceScanActivity.REQUEST_ENABLE_BT);
}
mActivity.updateOptionsMenu(true);
if (mListAdapter == null) {
mListAdapter = new BleDeviceListAdapter();
}
mListAdapter.clear();
setListAdapter(mListAdapter);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
// Stops scanning after a pre-defined scan period.
mActivity.updateOptionsMenu(false);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
public void stopScan() {
Log.d(TAG, "Stop LE Scan");
mActivity.updateOptionsMenu(false);
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chooses not to enable Bluetooth.
if (requestCode == DeviceScanActivity.REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
mListAdapter.clear();
setListAdapter(mListAdapter);
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
BluetoothDevice device = mListAdapter.getDevice(position);
if (device == null) return;
final Intent intent = new Intent(mActivity, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
intent.putExtra(DeviceControlActivity.EXTRAS_CONNECTION_METHOD, DeviceControlActivity.BLUETOOTH_METHOD);
stopScan();
startActivity(intent);
}
/**
* Simple {@link android.widget.BaseAdapter} to support displaying names and addresses of scanned
* BLE devices.
*/
private class BleDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflater;
public BleDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
if (getActivity() != null) {
mInflater = getActivity().getLayoutInflater();
}
}
public void addDevice(BluetoothDevice device) {
if (!mLeDevices.contains(device)) {
mLeDevices.add(device);
notifyDataSetChanged();
Log.d(TAG, "new item added. notify data set.");
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
@Override
public int getCount() {
return mLeDevices.size();
}
@Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflater.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
| 33.2
| 112
| 0.602666
|
4ca0a4649f7d11df1297e4cd1586adffa49fccfe
| 1,778
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Stastics_1_1 {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long n=sc.nextInt();
long a[]=new long[(int) n];
long i;
long m=0;
for(i=0;i<n;i++){
a[(int) i]=sc.nextInt();
m=m+a[(int) i];
}
float mean=(float)m/n;
System.out.println(mean);
float median=0;
Arrays.sort(a);
if(n%2==0){
median =(float)(a[(int) ((n/2)-1)]+a[(int) (n/2)])/2;
System.out.println(median);
}
else{
median=a[(int) ((n/2)+1)];
System.out.println(median);
}
int count2 = 0;
int count1 = 1;
int pupular1 =0;
int popular2 =0;
for ( i = 0; i < a.length; i++)
{
pupular1 = (int) a[(int) i];
count1 = 0; //see edit
for (int j = (int) (i + 1); j < a.length; j++)
{
if (pupular1 == a[j]) count1++;
}
if (count1 > count2)
{
popular2 = pupular1;
count2 = count1;
}
else if(count1 == count2)
{
popular2 = Math.min(popular2, pupular1);
}
}
System.out.println(popular2);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
}
| 25.4
| 122
| 0.393138
|
99c61ab8eebc74237674708d99cfcb35798ce39b
| 455
|
import java.util.*;
import java.lang.Math.*;
import java.math.*;
class LASTDIG2{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
BigInteger a;
BigInteger b;
BigInteger lastDigit;
for(int i = 0; i < testCases; i++){
a = scan.nextBigInteger();
b = scan.nextBigInteger();
lastDigit = a.modPow(b, BigInteger.valueOf(10));
System.out.println(lastDigit);
}
}
}
| 18.2
| 51
| 0.659341
|
4147dffbff856c2796b3e947a8ee87e03fc10632
| 512
|
package com.android.binding;
import android.app.Application;
import androidx.fragment.app.FragmentManager;
/**
* a class that integrates the Binding process to your android application
* <p>
* Created by Ahmed Adel Ismail on 1/31/2018.
*/
public class Binding extends FragmentManager.FragmentLifecycleCallbacks {
private Binding() {
}
public static void integrate(Application application) {
application.registerActivityLifecycleCallbacks(new ActivitiesLifeCycleCallback());
}
}
| 23.272727
| 90
| 0.757813
|
f03d464b1fe37724769fb50e58d2eed094ec3ded
| 1,234
|
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package jettyissue;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
import java.util.Set;
@HandlesTypes({MyAnnotation.class})
public class MyServletContainerInitializer implements ServletContainerInitializer {
public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException {
System.out.println("STARTED"+c);
}
}
| 37.393939
| 88
| 0.675041
|
931366e1fd32a0e6d340ef4255c79c9f9330664d
| 13,752
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.nodemanager.containermanager.deletion.task
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|containermanager
operator|.
name|deletion
operator|.
name|task
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|FileContext
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|Path
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|fs
operator|.
name|UnsupportedFileSystemException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnServerNodemanagerRecoveryProtos
operator|.
name|DeletionServiceDeleteTaskProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|DeletionService
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|nodemanager
operator|.
name|executor
operator|.
name|DeletionAsUserContext
import|;
end_import
begin_import
import|import
name|java
operator|.
name|io
operator|.
name|IOException
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|List
import|;
end_import
begin_comment
comment|/** * {@link DeletionTask} handling the removal of files (and directories). */
end_comment
begin_class
DECL|class|FileDeletionTask
specifier|public
class|class
name|FileDeletionTask
extends|extends
name|DeletionTask
implements|implements
name|Runnable
block|{
DECL|field|subDir
specifier|private
specifier|final
name|Path
name|subDir
decl_stmt|;
DECL|field|baseDirs
specifier|private
specifier|final
name|List
argument_list|<
name|Path
argument_list|>
name|baseDirs
decl_stmt|;
DECL|field|lfs
specifier|private
specifier|static
specifier|final
name|FileContext
name|lfs
init|=
name|getLfs
argument_list|()
decl_stmt|;
DECL|method|getLfs ()
specifier|private
specifier|static
name|FileContext
name|getLfs
parameter_list|()
block|{
try|try
block|{
return|return
name|FileContext
operator|.
name|getLocalFSFileContext
argument_list|()
return|;
block|}
catch|catch
parameter_list|(
name|UnsupportedFileSystemException
name|e
parameter_list|)
block|{
throw|throw
operator|new
name|RuntimeException
argument_list|(
name|e
argument_list|)
throw|;
block|}
block|}
comment|/** * Construct a FileDeletionTask with the default INVALID_TASK_ID. * * @param deletionService the {@link DeletionService}. * @param user the user deleting the file. * @param subDir the subdirectory to delete. * @param baseDirs the base directories containing the subdir. */
DECL|method|FileDeletionTask (DeletionService deletionService, String user, Path subDir, List<Path> baseDirs)
specifier|public
name|FileDeletionTask
parameter_list|(
name|DeletionService
name|deletionService
parameter_list|,
name|String
name|user
parameter_list|,
name|Path
name|subDir
parameter_list|,
name|List
argument_list|<
name|Path
argument_list|>
name|baseDirs
parameter_list|)
block|{
name|this
argument_list|(
name|INVALID_TASK_ID
argument_list|,
name|deletionService
argument_list|,
name|user
argument_list|,
name|subDir
argument_list|,
name|baseDirs
argument_list|)
expr_stmt|;
block|}
comment|/** * Construct a FileDeletionTask with the default INVALID_TASK_ID. * * @param taskId the ID of the task, if previously set. * @param deletionService the {@link DeletionService}. * @param user the user deleting the file. * @param subDir the subdirectory to delete. * @param baseDirs the base directories containing the subdir. */
DECL|method|FileDeletionTask (int taskId, DeletionService deletionService, String user, Path subDir, List<Path> baseDirs)
specifier|public
name|FileDeletionTask
parameter_list|(
name|int
name|taskId
parameter_list|,
name|DeletionService
name|deletionService
parameter_list|,
name|String
name|user
parameter_list|,
name|Path
name|subDir
parameter_list|,
name|List
argument_list|<
name|Path
argument_list|>
name|baseDirs
parameter_list|)
block|{
name|super
argument_list|(
name|taskId
argument_list|,
name|deletionService
argument_list|,
name|user
argument_list|,
name|DeletionTaskType
operator|.
name|FILE
argument_list|)
expr_stmt|;
name|this
operator|.
name|subDir
operator|=
name|subDir
expr_stmt|;
name|this
operator|.
name|baseDirs
operator|=
name|baseDirs
expr_stmt|;
block|}
comment|/** * Get the subdirectory to delete. * * @return the subDir for the FileDeletionTask. */
DECL|method|getSubDir ()
specifier|public
name|Path
name|getSubDir
parameter_list|()
block|{
return|return
name|this
operator|.
name|subDir
return|;
block|}
comment|/** * Get the base directories containing the subdirectory. * * @return the base directories for the FileDeletionTask. */
DECL|method|getBaseDirs ()
specifier|public
name|List
argument_list|<
name|Path
argument_list|>
name|getBaseDirs
parameter_list|()
block|{
return|return
name|this
operator|.
name|baseDirs
return|;
block|}
comment|/** * Delete the specified file/directory as the specified user. */
annotation|@
name|Override
DECL|method|run ()
specifier|public
name|void
name|run
parameter_list|()
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Running DeletionTask : {}"
argument_list|,
name|this
argument_list|)
expr_stmt|;
name|boolean
name|error
init|=
literal|false
decl_stmt|;
if|if
condition|(
literal|null
operator|==
name|getUser
argument_list|()
condition|)
block|{
if|if
condition|(
name|baseDirs
operator|==
literal|null
operator|||
name|baseDirs
operator|.
name|size
argument_list|()
operator|==
literal|0
condition|)
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"NM deleting absolute path : {}"
argument_list|,
name|subDir
argument_list|)
expr_stmt|;
try|try
block|{
name|lfs
operator|.
name|delete
argument_list|(
name|subDir
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|error
operator|=
literal|true
expr_stmt|;
name|LOG
operator|.
name|warn
argument_list|(
literal|"Failed to delete "
operator|+
name|subDir
argument_list|)
expr_stmt|;
block|}
block|}
else|else
block|{
for|for
control|(
name|Path
name|baseDir
range|:
name|baseDirs
control|)
block|{
name|Path
name|del
init|=
name|subDir
operator|==
literal|null
condition|?
name|baseDir
else|:
operator|new
name|Path
argument_list|(
name|baseDir
argument_list|,
name|subDir
argument_list|)
decl_stmt|;
name|LOG
operator|.
name|debug
argument_list|(
literal|"NM deleting path : {}"
argument_list|,
name|del
argument_list|)
expr_stmt|;
try|try
block|{
name|lfs
operator|.
name|delete
argument_list|(
name|del
argument_list|,
literal|true
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|IOException
name|e
parameter_list|)
block|{
name|error
operator|=
literal|true
expr_stmt|;
name|LOG
operator|.
name|warn
argument_list|(
literal|"Failed to delete "
operator|+
name|subDir
argument_list|)
expr_stmt|;
block|}
block|}
block|}
block|}
else|else
block|{
try|try
block|{
name|LOG
operator|.
name|debug
argument_list|(
literal|"Deleting path: [{}] as user [{}]"
argument_list|,
name|subDir
argument_list|,
name|getUser
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|baseDirs
operator|==
literal|null
operator|||
name|baseDirs
operator|.
name|size
argument_list|()
operator|==
literal|0
condition|)
block|{
name|getDeletionService
argument_list|()
operator|.
name|getContainerExecutor
argument_list|()
operator|.
name|deleteAsUser
argument_list|(
operator|new
name|DeletionAsUserContext
operator|.
name|Builder
argument_list|()
operator|.
name|setUser
argument_list|(
name|getUser
argument_list|()
argument_list|)
operator|.
name|setSubDir
argument_list|(
name|subDir
argument_list|)
operator|.
name|build
argument_list|()
argument_list|)
expr_stmt|;
block|}
else|else
block|{
name|getDeletionService
argument_list|()
operator|.
name|getContainerExecutor
argument_list|()
operator|.
name|deleteAsUser
argument_list|(
operator|new
name|DeletionAsUserContext
operator|.
name|Builder
argument_list|()
operator|.
name|setUser
argument_list|(
name|getUser
argument_list|()
argument_list|)
operator|.
name|setSubDir
argument_list|(
name|subDir
argument_list|)
operator|.
name|setBasedirs
argument_list|(
name|baseDirs
operator|.
name|toArray
argument_list|(
operator|new
name|Path
index|[
literal|0
index|]
argument_list|)
argument_list|)
operator|.
name|build
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
catch|catch
parameter_list|(
name|IOException
decl||
name|InterruptedException
name|e
parameter_list|)
block|{
name|error
operator|=
literal|true
expr_stmt|;
name|LOG
operator|.
name|warn
argument_list|(
literal|"Failed to delete as user "
operator|+
name|getUser
argument_list|()
argument_list|,
name|e
argument_list|)
expr_stmt|;
block|}
block|}
if|if
condition|(
name|error
condition|)
block|{
name|setSuccess
argument_list|(
operator|!
name|error
argument_list|)
expr_stmt|;
block|}
name|deletionTaskFinished
argument_list|()
expr_stmt|;
block|}
comment|/** * Convert the FileDeletionTask to a String representation. * * @return String representation of the FileDeletionTask. */
annotation|@
name|Override
DECL|method|toString ()
specifier|public
name|String
name|toString
parameter_list|()
block|{
name|StringBuilder
name|sb
init|=
operator|new
name|StringBuilder
argument_list|(
literal|"FileDeletionTask :"
argument_list|)
decl_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|" id : "
argument_list|)
operator|.
name|append
argument_list|(
name|getTaskId
argument_list|()
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|" user : "
argument_list|)
operator|.
name|append
argument_list|(
name|getUser
argument_list|()
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|" subDir : "
argument_list|)
operator|.
name|append
argument_list|(
name|subDir
operator|==
literal|null
condition|?
literal|"null"
else|:
name|subDir
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
name|sb
operator|.
name|append
argument_list|(
literal|" baseDir : "
argument_list|)
expr_stmt|;
if|if
condition|(
name|baseDirs
operator|==
literal|null
operator|||
name|baseDirs
operator|.
name|size
argument_list|()
operator|==
literal|0
condition|)
block|{
name|sb
operator|.
name|append
argument_list|(
literal|"null"
argument_list|)
expr_stmt|;
block|}
else|else
block|{
for|for
control|(
name|Path
name|baseDir
range|:
name|baseDirs
control|)
block|{
name|sb
operator|.
name|append
argument_list|(
name|baseDir
operator|.
name|toString
argument_list|()
argument_list|)
operator|.
name|append
argument_list|(
literal|','
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|sb
operator|.
name|toString
argument_list|()
operator|.
name|trim
argument_list|()
return|;
block|}
comment|/** * Convert the FileDeletionTask to the Protobuf representation for storing * in the state store and recovery. * * @return the protobuf representation of the FileDeletionTask. */
DECL|method|convertDeletionTaskToProto ()
specifier|public
name|DeletionServiceDeleteTaskProto
name|convertDeletionTaskToProto
parameter_list|()
block|{
name|DeletionServiceDeleteTaskProto
operator|.
name|Builder
name|builder
init|=
name|getBaseDeletionTaskProtoBuilder
argument_list|()
decl_stmt|;
name|builder
operator|.
name|setTaskType
argument_list|(
name|DeletionTaskType
operator|.
name|FILE
operator|.
name|name
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|getSubDir
argument_list|()
operator|!=
literal|null
condition|)
block|{
name|builder
operator|.
name|setSubdir
argument_list|(
name|getSubDir
argument_list|()
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|getBaseDirs
argument_list|()
operator|!=
literal|null
condition|)
block|{
for|for
control|(
name|Path
name|dir
range|:
name|getBaseDirs
argument_list|()
control|)
block|{
name|builder
operator|.
name|addBasedirs
argument_list|(
name|dir
operator|.
name|toString
argument_list|()
argument_list|)
expr_stmt|;
block|}
block|}
return|return
name|builder
operator|.
name|build
argument_list|()
return|;
block|}
block|}
end_class
end_unit
| 16.046674
| 809
| 0.779232
|
d893a6473bbed906461aa1fc5704dc97c0ca17c2
| 8,729
|
package com.logicmaster63.tdgalaxy;
import com.badlogic.gdx.*;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.controllers.Controllers;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.net.HttpRequestBuilder;
import com.badlogic.gdx.physics.bullet.Bullet;
import com.esotericsoftware.minlog.Log;
import com.logicmaster63.tdgalaxy.constants.Dialogs;
import com.logicmaster63.tdgalaxy.constants.GameMode;
import com.logicmaster63.tdgalaxy.entity.EntityProperties;
import com.logicmaster63.tdgalaxy.interfaces.Debug;
import com.logicmaster63.tdgalaxy.interfaces.FileStuff;
import com.logicmaster63.tdgalaxy.interfaces.OnlineServices;
import com.logicmaster63.tdgalaxy.interfaces.VR;
import com.logicmaster63.tdgalaxy.networking.TDClient;
import com.logicmaster63.tdgalaxy.screens.MainScreen;
import com.logicmaster63.tdgalaxy.controls.ControlHandler;
import com.logicmaster63.tdgalaxy.tools.FileHandler;
import com.logicmaster63.tdgalaxy.tools.PreferenceHandler;
import com.logicmaster63.tdgalaxy.tools.SoundHandler_SecurityExample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.List;
public class TDGalaxy extends Game {
public static void main(String[] args) {
SoundHandler_SecurityExample.get().loadAudios(new HashMap<String, Sound>());
}
//Interfaces
public static FileStuff fileStuff;
public static OnlineServices onlineServices;
private static Debug debugger;
public static VR vr;
public static Dialogs dialogs;
public static PreferenceHandler preferences;
private static List<String> themes = new ArrayList<String>();
private static String ip = "";
private static boolean isDebug, isOnline = false;
private static MainScreen mainScreen;
private static String startingMode;
private Map<String, BitmapFont> fonts;
private AssetManager uiAssets, gameAssets;
private ControlHandler controlHandler;
private TDClient client;
public TDGalaxy(String mode, FileStuff fileStuff, Debug debugger, OnlineServices onlineServices, VR vr, boolean isDebug) {
TDGalaxy.fileStuff = fileStuff;
TDGalaxy.debugger = debugger;
TDGalaxy.onlineServices = onlineServices;
TDGalaxy.startingMode = mode;
TDGalaxy.vr = vr;
}
@Override
public void setScreen(Screen screen) {
super.setScreen(screen);
onlineServices.showBanner(screen instanceof MainScreen);
updateNetwork();
}
@Override
public void create() {
Bullet.init();
themes.add("basic");
//clearPrefs();
//changePref("debug", true);
preferences = new PreferenceHandler();
dialogs = new Dialogs();
fonts = new HashMap<String, BitmapFont>();
FileHandler.loadFonts(fonts);
FileHandler.writeJSON(Gdx.files.external("Map.json"));
if(preferences.isDebug())
Gdx.app.setLogLevel(Application.LOG_DEBUG);
loadExternalAssets();
loadTheme("basic");
GameMode mode;
if(startingMode != null) {
try {
mode = GameMode.valueOf(startingMode);
Gdx.app.log("StartingMode", mode.name());
} catch (Exception e) {
Gdx.app.error("TDGalaxy", "Invalid starting mode", e);
}
}
if(preferences.isVr())
Gdx.graphics.setVSync(false);
mainScreen = new MainScreen(this);
setScreen(mainScreen);
//setScreen(new GameScreen(this, 0, themes.get(0)));
controlHandler = new ControlHandler();
controlHandler.setNeededControllers(2);
client = new TDClient();
//client.connect(5000, "99.36.127.68", Networking.PORT); //99.36.127.68
Log.set(Log.LEVEL_DEBUG);
if(TDGalaxy.preferences.isDebugWindow() && debugger != null) {
debugger.createWindow("Controllers");
debugger.addButton("Controllers", "Requure 1", new Runnable() {
@Override
public void run() {
controlHandler.setNeededControllers(1);
}
});
debugger.addButton("Controllers", "Requure 4", new Runnable() {
@Override
public void run() {
controlHandler.setNeededControllers(4);
}
});
}
if(vr != null && preferences.isVr()) {
vr.initialize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight(),2560, 1440);
new Thread() {
@Override
public void run() {
}
}.start();
}
new EntityProperties("properties/basic/Basic.json");
}
@Override
public void render() {
super.render();
if(TDGalaxy.preferences.isDebugWindow() && debugger != null) {
debugger.updateValue("Controllers", "Players", controlHandler.getPlayers());
debugger.updateValue("Controllers", "TDControllers", controlHandler.getControllers());
debugger.updateValue("Controllers", "Controllers", Controllers.getControllers());
debugger.updateValue("Controllers", "Paused", controlHandler.isPaused());
debugger.updateValue("Controllers", "Needed Controllers", controlHandler.getNeededControllers());
}
}
public AssetManager getUIAssets() {
return uiAssets;
}
public AssetManager getGameAssets() {
return gameAssets;
}
public void loadExternalAssets() {
gameAssets = fileStuff.getExternalAssets();
}
public void loadTheme(String theme) {
if(uiAssets == null)
uiAssets = new AssetManager();
uiAssets.clear();
}
public void updateNetwork() {
isOnline = false;
Gdx.net.sendHttpRequest(new HttpRequestBuilder().newRequest().method(Net.HttpMethods.GET).url("http://checkip.amazonaws.com").build(), new Net.HttpResponseListener() {
@Override
public void handleHttpResponse(Net.HttpResponse httpResponse) {
try {
ip = new BufferedReader(new InputStreamReader(httpResponse.getResultAsStream())).readLine();
isOnline = true;
//client.connect(5000, "99.36.127.68", Networking.PORT);
//client.reconnect();
} catch (IOException e) {
Gdx.app.error("HTTP", e.toString());
}
}
@Override
public void failed(Throwable t) {
Gdx.app.log("Update Network", t.toString());
}
@Override
public void cancelled() {
}
});
}
@Override
public void dispose() {
if(debugger != null)
debugger.disposeWindow("Controllers");
if(vr != null && preferences.isVr())
vr.close();
List<BitmapFont> fontArray = new ArrayList<BitmapFont>(fonts.values());
for(BitmapFont font: fontArray)
font.dispose();
}
public TDClient getClient() {
return client;
}
public static boolean isOnline() {
return isOnline;
}
public void addTheme() {
}
public void removeDebugWindow(String id) {
if(debugger != null)
debugger.createWindow(id);
}
public void createDebugWindow(String id) {
if(debugger != null)
debugger.createWindow(id);
}
public void addDebugTextButton(String name, com.logicmaster63.tdgalaxy.interfaces.ValueReturner valueReturner) {
if(debugger != null)
debugger.addTextButton(name, valueReturner);
}
public void addDebugButton(String id, String name, Runnable runnable) {
if(debugger != null)
debugger.addButton(id, name, runnable);
}
public void removeDebugTextButton(String name) {
if(debugger != null)
debugger.removeTextButton(name);
}
public void removeDebugButton(String name) {
if(debugger != null)
debugger.removeButton(name);
}
public void updateDebug(String id, Map<String, Object> values) {
if(debugger != null)
debugger.updateValues(id, values);
}
public boolean isDebug() {
return isDebug;
}
public static String getIp() {
return ip;
}
public List<String> getThemes() {
return themes;
}
public Map<String, BitmapFont> getFonts() {
return fonts;
}
public VR getVr() {
return vr;
}
}
| 31.512635
| 179
| 0.625501
|
25be19c52b0b4544e20a765331d676258ee64004
| 3,565
|
package cn.org.autumn.modules.lan.interceptor;
import cn.org.autumn.config.Config;
import cn.org.autumn.config.InterceptorHandler;
import cn.org.autumn.modules.lan.service.Language;
import cn.org.autumn.modules.lan.service.LanguageService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;
import java.util.Map;
@Component
public class LanguageInterceptor extends HandlerInterceptorAdapter implements InterceptorHandler {
private static Logger logger = LoggerFactory.getLogger(LanguageInterceptor.class);
@Autowired
LanguageService languageService;
public static LanguageService lang;
public static String LANGUAGE_SESSION = "LANGUAGE_SESSION";
public static Locale getLocale(HttpServletRequest request) {
String language = request.getParameter("lang");
Locale locale = Locale.getDefault();
if (StringUtils.isNotEmpty(language)) {
Locale l = Language.toLocale(language);
if (null != l)
locale = l;
//将国际化语言保存到session
HttpSession session = request.getSession();
session.setAttribute(LANGUAGE_SESSION, locale);
} else {
//如果没有带国际化参数,则判断session有没有保存,有保存,则使用保存的,也就是之前设置的,避免之后的请求不带国际化参数造成语言显示不对
try {
HttpSession session = request.getSession();
Locale localeInSession = (Locale) session.getAttribute(LANGUAGE_SESSION);
if (localeInSession != null) {
locale = localeInSession;
} else {
if (StringUtils.isEmpty(language)) {
if (null == lang)
lang = (LanguageService) Config.getBean("languageService");
if (null != lang)
language = lang.getUserDefaultLanguage();
Locale l = Language.toLocale(language);
if (null != l)
locale = l;
}
}
} catch (Exception e) {
logger.error("LanguageInterceptor.getLocale error: " + e.getMessage());
}
}
return locale;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
String uri = request.getRequestURI();
if (null != modelAndView) {
ModelMap modelMap = modelAndView.getModelMap();
Locale locale = getLocale(request);
if (null == locale) {
logger.error("locale can not be null");
}
Map<String, String> lang = languageService.getLanguage(locale);
if (null == lang || lang.isEmpty())
logger.error("language cannot be empty");
modelMap.put("lang", lang);
}
}
@Override
public HandlerInterceptor getHandlerInterceptor() {
return this;
}
}
| 39.175824
| 156
| 0.640954
|
268208cb27d8e77febb2ecb600604d966f294e33
| 96
|
package ibxm;
public class Note {
public int key, instrument, volume, effect, param;
}
| 13.714286
| 52
| 0.677083
|
d441f6d5d3dcb802534bf10c6244114513d74c90
| 721
|
package com.arematics.minecraft.core.messaging.advanced;
import com.google.gson.JsonParseException;
import java.util.Arrays;
public enum HoverAction{
SHOW_TEXT("show_text"),
SHOW_ACHIEVEMENT("show_achievement"),
SHOW_ITEM("show_item");
public static HoverAction findByAction(String name, HoverAction orElse) throws RuntimeException{
HoverAction action = Arrays.stream(values()).filter(hoverAction -> hoverAction.ACTION.equals(name))
.findFirst().orElse(orElse);
if(action == null) throw new JsonParseException("No HoverAction found");
return action;
}
public final String ACTION;
HoverAction(String action){
this.ACTION = action;
}
}
| 27.730769
| 107
| 0.705964
|
1a75461b2696b9d5e442798f4157eb9c7a1b6486
| 3,566
|
package org.aion.avm.core.shadowing;
import avm.Address;
import org.aion.avm.core.AvmConfiguration;
import org.aion.avm.core.AvmImpl;
import org.aion.avm.core.CommonAvmFactory;
import org.aion.avm.core.blockchainruntime.EmptyCapabilities;
import org.aion.avm.core.dappreading.JarBuilder;
import org.aion.avm.core.util.CodeAndArguments;
import org.aion.avm.core.util.Helpers;
import org.aion.avm.userlib.AionMap;
import org.aion.kernel.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.math.BigInteger;
/**
* Tests that we fail in a meaningful way when a DApp throws an exception due to a missing method.
*/
public class DefaultMethodIntegrationTest {
private org.aion.types.Address deployer = TestingKernel.PREMINED_ADDRESS;
private TestingKernel kernel;
private AvmImpl avm;
@Before
public void setup() {
Block block = new Block(new byte[32], 1, Helpers.randomAddress(), System.currentTimeMillis(), new byte[0]);
this.kernel = new TestingKernel(block);
this.avm = CommonAvmFactory.buildAvmInstanceForConfiguration(new EmptyCapabilities(), new AvmConfiguration());
}
@After
public void tearDown() {
this.avm.shutdown();
}
@Test
public void testMissingDefaultInClinit() throws Exception {
byte[] jar = JarBuilder.buildJarForMainAndClasses(TestDefaultMethodInClinitResource.class, AionMap.class);
byte[] txData = new CodeAndArguments(jar, new byte[0]).encodeToBytes();
// Deploy.
long energyLimit = 2_000_000l;
long energyPrice = 1l;
Transaction create = Transaction.create(deployer, kernel.getNonce(deployer), BigInteger.ZERO, txData, energyLimit, energyPrice);
// The NoSuchMethodError triggers a "FAILED_EXCEPTION" state.
AvmTransactionResult result = (AvmTransactionResult) avm.run(this.kernel, new Transaction[] {create})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.FAILED_EXCEPTION, result.getResultCode());
}
@Test
public void testMissingDefaultInMain() throws Exception {
Block block = new Block(new byte[32], 1, Helpers.randomAddress(), System.currentTimeMillis(), new byte[0]);
byte[] jar = JarBuilder.buildJarForMainAndClasses(TestDefaultMethodInMainResource.class, AionMap.class);
byte[] txData = new CodeAndArguments(jar, new byte[0]).encodeToBytes();
// Deploy.
long energyLimit = 2_000_000l;
long energyPrice = 1l;
Transaction create = Transaction.create(deployer, kernel.getNonce(deployer), BigInteger.ZERO, txData, energyLimit, energyPrice);
AvmTransactionResult createResult = (AvmTransactionResult) avm.run(this.kernel, new Transaction[] {create})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.SUCCESS, createResult.getResultCode());
Address contractAddr = new Address(createResult.getReturnData());
// Setup the call (parameters are currently ignored).
byte[] argData = new byte[0];
Transaction call = Transaction.call(deployer, org.aion.types.Address.wrap(contractAddr.unwrap()), kernel.getNonce(deployer), BigInteger.ZERO, argData, energyLimit, 1l);
// The NoSuchMethodError triggers a "FAILED_EXCEPTION" state.
AvmTransactionResult result = (AvmTransactionResult) avm.run(this.kernel, new Transaction[] {call})[0].get();
Assert.assertEquals(AvmTransactionResult.Code.FAILED_EXCEPTION, result.getResultCode());
}
}
| 45.139241
| 176
| 0.719854
|
9c1f24952a384b93da9d4245065c665bc1d5379c
| 8,802
|
package cl.bebt.staffcore.menu.menu.Reports;
import cl.bebt.staffcore.main;
import cl.bebt.staffcore.menu.PaginatedMenu;
import cl.bebt.staffcore.menu.PlayerMenuUtility;
import cl.bebt.staffcore.sql.Queries.ReportsQuery;
import cl.bebt.staffcore.utils.TpPlayers;
import cl.bebt.staffcore.utils.utils;
import org.bukkit.NamespacedKey;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataType;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class closedReportsMenu extends PaginatedMenu {
private final main plugin;
public closedReportsMenu( PlayerMenuUtility playerMenuUtility , main plugin ){
super( playerMenuUtility );
this.plugin = plugin;
}
@Override
public String getMenuName( ){
return utils.chat( utils.getString( "reports.closed.name" , "menu" , null ) );
}
@Override
public int getSlots( ){
return 54;
}
@Override
public void handleMenu( InventoryClickEvent e ){
Player p = ( Player ) e.getWhoClicked( );
HashMap < Integer, Integer > reports = new HashMap <>( );
int num = 0;
if ( utils.mysqlEnabled( ) ) {
ArrayList < Integer > openReports = ReportsQuery.getClosedReports( );
for ( Integer openReport : openReports ) {
num++;
reports.put( num , openReport );
}
} else {
for ( int id = 0; id <= utils.count( "reports" ); ) {
id++;
try {
if ( plugin.reports.getConfig( ).getString( "reports." + id + ".status" ).equals( "close" ) ) {
num++;
reports.put( num , id );
}
} catch ( NullPointerException ignored ) {
}
}
}
if ( e.getCurrentItem( ).getItemMeta( ).getPersistentDataContainer( ).has( new NamespacedKey( plugin , "close" ) , PersistentDataType.STRING ) ) {
p.closeInventory( );
String jugador = e.getCurrentItem( ).getItemMeta( ).getDisplayName( );
if ( e.getClick( ).isLeftClick( ) ) {
int id = e.getCurrentItem( ).getItemMeta( ).getPersistentDataContainer( ).get( new NamespacedKey( plugin , "close-id" ) , PersistentDataType.INTEGER );
new EditReport( main.getPlayerMenuUtility( p ) , main.plugin , jugador , id ).open( );
} else if ( e.getClick( ).isRightClick( ) ) {
TpPlayers.tpToPlayer( p , jugador );
}
} else if ( e.getCurrentItem( ).equals( close( ) ) ) {
p.closeInventory( );
if ( e.getClick( ).isLeftClick( ) ) {
new ReportManager( main.getPlayerMenuUtility( p ) , main.plugin ).open( );
}
} else if ( e.getCurrentItem( ).equals( back( ) ) ) {
if ( page == 0 ) {
utils.tell( p , utils.getString( "menu.already_in_first_page" , "lg" , "sv" ) );
} else {
page--;
p.closeInventory( );
open( );
}
} else if ( e.getCurrentItem( ).equals( next( ) ) ) {
if ( index + 1 <= reports.size( ) ) {
page++;
p.closeInventory( );
open( );
} else {
utils.tell( p , utils.getString( "menu.already_in_last_page" , "lg" , "sv" ) );
}
}
}
@Override
public void setMenuItems( ){
addMenuBorder( );
HashMap < Integer, Integer > reports = new HashMap <>( );
int num = 0;
JSONObject json = new JSONObject( );
if ( utils.mysqlEnabled( ) ) {
ArrayList < Integer > openReports = ReportsQuery.getClosedReports( );
for ( Integer openReport : openReports ) {
num++;
reports.put( num , openReport );
}
json = ReportsQuery.getClosedReportInfo( );
} else {
for ( int id = 0; id <= utils.count( "reports" ); ) {
id++;
try {
if ( plugin.reports.getConfig( ).getString( "reports." + id + ".status" ).equals( "close" ) ) {
num++;
reports.put( num , id );
}
} catch ( NullPointerException ignored ) {
}
}
}
if ( reports != null && !reports.isEmpty( ) ) {
for ( int i = 1; i <= getMaxItemsPerPage( ); i++ ) {
index = getMaxItemsPerPage( ) * page + i;
if ( index > reports.size( ) ) break;
if ( reports.get( index ) != null ) {
//////////////////////////////
plugin.reports.reloadConfig( );
if ( utils.mysqlEnabled( ) ) {
String rawReportInfo = json.get( String.valueOf( reports.get( index ) ) ).toString( )
.replace( "[" , "" )
.replace( "]" , "" );
JSONObject reportInfo = new JSONObject( rawReportInfo );
ItemStack p_head = utils.getPlayerHead( reportInfo.getString( "Name" ) );
ItemMeta meta = p_head.getItemMeta( );
ArrayList < String > lore = new ArrayList <>( );
meta.setDisplayName( reportInfo.getString( "Name" ) );
lore.add( utils.chat( "&7Reported by: " + reportInfo.getString( "Reporter" ) ) );
lore.add( utils.chat( "&7Reason: &b" + reportInfo.getString( "Reason" ) ) );
lore.add( utils.chat( "&7Date: &c" + reportInfo.getString( "Date" ) ) );
lore.add( utils.chat( "&7Status: &c" + reportInfo.getString( "Status" ) ) );
lore.add( utils.chat( "&7Report ID:&a " + reports.get( index ) ) );
lore.add( utils.chat( "&aLeft click delete or open" ) );
lore.add( utils.chat( "&aRight click to tp" ) );
meta.setLore( lore );
meta.getPersistentDataContainer( ).set( new NamespacedKey( main.plugin , "close-id" ) , PersistentDataType.INTEGER , reports.get( index ) );
meta.getPersistentDataContainer( ).set( new NamespacedKey( main.plugin , "close" ) , PersistentDataType.STRING , "close" );
p_head.setItemMeta( meta );
inventory.addItem( p_head );
} else {
plugin.reports.reloadConfig( );
ItemStack p_head = utils.getPlayerHead( plugin.reports.getConfig( ).get( "reports." + reports.get( index ) + ".name" ).toString( ) );
ItemMeta meta = p_head.getItemMeta( );
ArrayList < String > lore = new ArrayList <>( );
meta.setDisplayName( plugin.reports.getConfig( ).get( "reports." + reports.get( index ) + ".name" ).toString( ) );
lore.add( utils.chat( "&7Reported by: " + plugin.reports.getConfig( ).get( "reports." + reports.get( index ) + ".reported_by" ) ) );
lore.add( utils.chat( "&7Reason: &b" + plugin.reports.getConfig( ).get( "reports." + reports.get( index ) + ".reason" ) ) );
lore.add( utils.chat( "&7Date: &c" + plugin.reports.getConfig( ).get( "reports." + reports.get( index ) + ".time" ) ) );
lore.add( utils.chat( "&7Status: &a" + plugin.reports.getConfig( ).get( "reports." + reports.get( index ) + ".status" ) ) );
lore.add( utils.chat( "&7Report ID:&a " + reports.get( index ) ) );
lore.add( utils.chat( "&aLeft click delete or open" ) );
lore.add( utils.chat( "&aRight click to tp" ) );
meta.setLore( lore );
meta.getPersistentDataContainer( ).set( new NamespacedKey( main.plugin , "close-id" ) , PersistentDataType.INTEGER , reports.get( index ) );
meta.getPersistentDataContainer( ).set( new NamespacedKey( main.plugin , "close" ) , PersistentDataType.STRING , "close" );
p_head.setItemMeta( meta );
inventory.addItem( p_head );
}
/////////////////////////////
}
}
}
}
}
| 50.297143
| 167
| 0.499886
|
5e208d8216bf67d664d060408359d75018da47ec
| 5,292
|
package diarg;
import net.sf.tweety.arg.dung.syntax.DungTheory;
import net.sf.tweety.arg.dung.syntax.Argument;
import net.sf.tweety.arg.dung.syntax.Attack;
/**
* Provides example argumentation frameworks for test purposes
* framework1: ({a, b, c, d, e},{(a, b), (b, c), (c, b), (c, d), (d, e), (e, c)})
* framework2: ({a, b, c}, {(a, b), (b, a), (b, c), (c, a)})
* framework3: ({a, b, c}, {(a, b), (b, c), (c, a)})
* framework4: ({a, b}, {(a, b)})
* framework5: ({a, b}, {(a, b), (b, a)})
* framework6: ({a, b, c, d}, {(a, b), (b, a), (c, d), (d, c)})
* framework7: ({a, b, c, d}, {(a, b), (b, c), (c, a), (d, a)})
* framework8 ({a, b, c, d}, {(a, b), (b, a), (b, c), (c, d), (d, c)})
* framework9: ({a, b, c, d, e}, {(e, a), (d, b), (b, d), (d, c), (c, d), (d, d), (e, e)})
* framework10: ({a, b, c, d}, {(a, b), (b, a), (c, b), (d, c)})
* @author Timotheus Kampik
*/
public final class TestFrameworks {
public DungTheory framework1 = new DungTheory();
public DungTheory framework2 = new DungTheory();
public DungTheory framework3 = new DungTheory();
public DungTheory framework4 = new DungTheory();
public DungTheory framework5 = new DungTheory();
public DungTheory framework6 = new DungTheory();
public DungTheory framework7 = new DungTheory();
public DungTheory framework8 = new DungTheory();
public DungTheory framework9 = new DungTheory();
public DungTheory framework10 = new DungTheory();
String extensionSerialization1 = "[\"a\"]";
String extensionSerialization2 = "[\"a\",\"c\"]";
String frameworkSerialization1 = "{\"arguments\":[\"a\",\"b\"],\"attacks\":[[\"a\",\"b\"]]}";
String frameworkSerialization2 = "{\"arguments\":[\"a\",\"b\",\"c\",\"d\"]," +
"\"attacks\":[[\"a\",\"b\"],[\"c\",\"d\"],[\"b\",\"a\"],[\"d\",\"c\"]]}";
String sequenceSerialization1 = "{\"semanticsType\":\"NSACF2\",\"sequenceType\":\"EXPANDING\",\"resolutionType\":\"EXPANSIONIST_REFERENCE_INDEPENDENT\",\"frameworks\":[{\"framework\":{\"arguments\":[\"a\",\"b\"],\"attacks\":[[\"a\",\"b\"]]},\"contextSummary\":[],\"contexts\":[],\"resolution\":[\"a\"]},{\"framework\":{\"arguments\":[\"a\",\"b\",\"c\",\"d\"],\"attacks\":[[\"a\",\"b\"],[\"c\",\"d\"],[\"b\",\"a\"],[\"d\",\"c\"]]},\"contextSummary\":[],\"contexts\":[]}]}";
String contextSerialization1 = "{\"name\":\"testContext\",\"arguments\":[\"a\"]}";
public TestFrameworks() {
Argument a = new Argument("a");
Argument b = new Argument("b");
Argument c = new Argument("c");
Argument d = new Argument("d");
Argument e = new Argument("e");
framework1.add(a);
framework1.add(b);
framework1.add(c);
framework1.add(d);
framework1.add(e);
framework1.add(new Attack(a,b));
framework1.add(new Attack(b,c));
framework1.add(new Attack(c,b));
framework1.add(new Attack(c,d));
framework1.add(new Attack(d,e));
framework1.add(new Attack(e,c));
framework2.add(a);
framework2.add(b);
framework2.add(c);
framework2.add(new Attack(a,b));
framework2.add(new Attack(b,a));
framework2.add(new Attack(b,c));
framework2.add(new Attack(c,a));
framework3.add(a);
framework3.add(b);
framework3.add(c);
framework3.add(new Attack(a, b));
framework3.add(new Attack(b, c));
framework3.add(new Attack(c, a));
framework4.add(a);
framework4.add(b);
framework4.add(new Attack(a, b));
framework5.add(a);
framework5.add(b);
framework5.add(new Attack(a, b));
framework5.add(new Attack(b, a));
framework6.add(a);
framework6.add(b);
framework6.add(c);
framework6.add(d);
framework6.add(new Attack(a, b));
framework6.add(new Attack(b, a));
framework6.add(new Attack(c, d));
framework6.add(new Attack(d, c));
framework7.add(a);
framework7.add(b);
framework7.add(c);
framework7.add(d);
framework7.add(new Attack(a, b));
framework7.add(new Attack(b, c));
framework7.add(new Attack(c, a));
framework7.add(new Attack(d, a));
framework8.add(a);
framework8.add(b);
framework8.add(c);
framework8.add(d);
framework8.add(new Attack (a, b));
framework8.add(new Attack (b, a));
framework8.add(new Attack (b, c));
framework8.add(new Attack (c, d));
framework8.add(new Attack (d, c));
framework9.add(a);
framework9.add(b);
framework9.add(c);
framework9.add(d);
framework9.add(e);
framework9.add(new Attack(e, a));
framework9.add(new Attack(d, b));
framework9.add(new Attack(b, d));
framework9.add(new Attack(d, c));
framework9.add(new Attack(c, d));
framework9.add(new Attack(d, d));
framework9.add(new Attack(e, e));
framework10.add(a);
framework10.add(b);
framework10.add(c);
framework10.add(d);
framework10.add(new Attack(a, b));
framework10.add(new Attack(b, a));
framework10.add(new Attack(c, b));
framework10.add(new Attack(d, c));
}
}
| 38.627737
| 476
| 0.548186
|
3e818e86ab9cecc34c70bd06b79e7747154bcb88
| 4,537
|
package com.zrlog.web.controller.admin.api;
import com.hibegin.common.util.FileUtils;
import com.zrlog.common.Constants;
import com.zrlog.common.response.UpdateRecordResponse;
import com.zrlog.common.response.UploadTemplateResponse;
import com.zrlog.common.response.WebSiteSettingUpdateResponse;
import com.zrlog.model.WebSite;
import com.zrlog.service.CacheService;
import com.zrlog.util.I18NUtil;
import com.zrlog.web.controller.BaseController;
import com.google.gson.Gson;
import com.hibegin.common.util.IOUtil;
import com.hibegin.common.util.ZipUtil;
import com.jfinal.kit.PathKit;
import javax.servlet.http.Cookie;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TemplateController extends BaseController {
private CacheService cacheService = new CacheService();
public WebSiteSettingUpdateResponse apply() {
String template = getPara("template");
new WebSite().updateByKV("template", template);
WebSiteSettingUpdateResponse webSiteSettingUpdateResponse = new WebSiteSettingUpdateResponse();
webSiteSettingUpdateResponse.setError(0);
Cookie cookie = new Cookie("template", "");
cookie.setPath("/");
cookie.setMaxAge(0);
getResponse().addCookie(cookie);
// 更新缓存数据
cacheService.refreshInitDataCache(this, true);
cacheService.removeCachedStaticFile();
return webSiteSettingUpdateResponse;
}
public WebSiteSettingUpdateResponse delete() {
String template = getPara("template");
File file = new File(PathKit.getWebRootPath() + template);
if (file.exists()) {
FileUtils.deleteFile(file.toString());
}
return new WebSiteSettingUpdateResponse();
}
public Map loadFile() {
String file = getRequest().getRealPath("/") + getPara("file");
Map<String, Object> map = new HashMap<String, Object>();
try {
String fileContent = IOUtil.getStringInputStream(new FileInputStream(file));
map.put("fileContent", fileContent);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return map;
}
public Map saveFile() {
String file = getRequest().getRealPath("/") + getPara("file");
IOUtil.writeBytesToFile(getPara("content").getBytes(), new File(file));
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", 200);
return map;
}
public UploadTemplateResponse upload() {
String uploadFieldName = "file";
String templateName = getFile(uploadFieldName).getOriginalFileName();
String finalPath = PathKit.getWebRootPath() + Constants.TEMPLATE_BASE_PATH;
String finalFile = finalPath + templateName;
FileUtils.deleteFile(finalFile);
//start extract template file
FileUtils.moveOrCopyFile(getFile(uploadFieldName).getFile().toString(), finalFile, true);
UploadTemplateResponse response = new UploadTemplateResponse();
response.setMessage(I18NUtil.getStringFromRes("templateDownloadSuccess", getRequest()));
try {
String extractFolder = finalPath + templateName.replace(".zip", "") + "/";
FileUtils.deleteFile(extractFolder);
ZipUtil.unZip(finalFile, extractFolder);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public UpdateRecordResponse setting() {
Map<String, String[]> param = getRequest().getParameterMap();
String template = getPara("template");
Map<String, Object> settingMap = new HashMap<String, Object>();
for (Map.Entry<String, String[]> entry : param.entrySet()) {
if (!entry.getKey().equals("template")) {
if (entry.getValue().length > 1) {
settingMap.put(entry.getKey(), entry.getValue());
} else {
settingMap.put(entry.getKey(), entry.getValue()[0]);
}
}
}
new WebSite().updateByKV(template + templateConfigSuffix, new Gson().toJson(settingMap));
cacheService.refreshInitDataCache(this, true);
cacheService.removeCachedStaticFile();
UpdateRecordResponse updateRecordResponse = new UpdateRecordResponse();
updateRecordResponse.setMessage("变更成功");
return updateRecordResponse;
}
}
| 39.112069
| 103
| 0.667181
|
b62435fa7291a38ec4e2a1253e0f5658f44ade28
| 1,171
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.lmu.project.NetworkGraph;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import java.util.*;
/**
*
* @author Patrick
*/
@JsonIgnoreProperties({ "type" })
public class RoadNetworkGraph {
List <Vertex> vertex = new ArrayList <> ();
List <Edge> edges = new ArrayList <>();
// Method to add Intermediate Nodes/edges to the Node List (from the edges)
//Dijkstra: distance map (recent distance from start to node i ) as hasmap; previousNode as Hashmap
// run: list of processed nodes, go to shortest distance node, traverse to all neighbourhood nodes
// Complexity is O(n^)
/**
* A* algorithm
* Optimization function f= distance + estimation/heuristics (heuristic can be e.g., euklidian distance)
*/
public RoadNetworkGraph() {
}
public String getStructure (){
return "GRAPH STRUCTURE | Vertexes:"+this.vertex.size() + " - Edges:" + this.edges.size();
}
}
| 28.560976
| 108
| 0.666951
|
270185a1ef5e75ecf9c4d4dab97509eac362706a
| 1,589
|
package japicmp.filter;
import japicmp.exception.JApiCmpException;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtField;
import java.util.regex.Pattern;
public class FieldFilter implements Filter {
private final String filterString;
private final Pattern patternClass;
private final Pattern patternField;
public FieldFilter(String filterString) {
this.filterString = filterString;
String regEx = filterString.replace(".", "\\.");
regEx = regEx.replace("*", ".*");
String[] parts = regEx.split("#");
if (parts.length != 2) {
throw new JApiCmpException(JApiCmpException.Reason.CliError, "Filter option '" + filterString + "' contains more than one '#'.");
}
this.patternClass = Pattern.compile(parts[0]);
this.patternField = Pattern.compile(parts[1]);
}
@Override
public boolean matches(CtClass ctClass) {
return this.patternClass.matcher(ctClass.getName()).matches();
}
@Override
public boolean matches(CtBehavior ctBehavior) {
return true;
}
@Override
public boolean matches(CtField ctField) {
CtClass declaringClass = ctField.getDeclaringClass();
String className = declaringClass.getName();
if (!this.patternClass.matcher(className).matches()) {
return false;
}
String fieldName = ctField.getName();
return this.patternField.matcher(fieldName).matches();
}
@Override
public String toString() {
return this.filterString;
}
}
| 29.981132
| 141
| 0.658276
|
30dba03736a99328cd945a89681be2fe62d0c671
| 5,911
|
/*******************************************************************************
* Copyright (c) Contributors to the Eclipse 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.
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
package org.osgi.service.component.runtime.dto;
import java.util.Map;
import org.osgi.dto.DTO;
import org.osgi.framework.dto.BundleDTO;
/**
* A representation of a declared component description.
*
* @since 1.3
* @NotThreadSafe
* @author $Id: 30dba03736a99328cd945a89681be2fe62d0c671 $
*/
public class ComponentDescriptionDTO extends DTO {
/**
* The name of the component.
*
* <p>
* This is declared in the {@code name} attribute of the {@code component}
* element. This must be the default name if the component description does
* not declare a name.
*/
public String name;
/**
* The bundle declaring the component description.
*/
public BundleDTO bundle;
/**
* The component factory name.
*
* <p>
* This is declared in the {@code factory} attribute of the
* {@code component} element. This must be {@code null} if the component
* description is not declared as a factory component.
*/
public String factory;
/**
* The service scope.
*
* <p>
* This is declared in the {@code scope} attribute of the {@code service}
* element. This must be {@code null} if the component description does not
* declare any service interfaces.
*/
public String scope;
/**
* The fully qualified name of the implementation class.
*
* <p>
* This is declared in the {@code class} attribute of the
* {@code implementation} element.
*/
public String implementationClass;
/**
* The initial enabled state.
*
* <p>
* This is declared in the {@code enabled} attribute of the
* {@code component} element.
*/
public boolean defaultEnabled;
/**
* The immediate state.
*
* <p>
* This is declared in the {@code immediate} attribute of the
* {@code component} element.
*/
public boolean immediate;
/**
* The fully qualified names of the service interfaces.
*
* <p>
* These are declared in the {@code interface} attribute of the
* {@code provide} elements. The array must be empty if the component
* description does not declare any service interfaces.
*/
public String[] serviceInterfaces;
/**
* The component properties.
* <p>
* These are declared in the component description by the {@code property}
* and {@code properties} elements as well as the {@code target} attribute
* of the {@code reference} elements.
*/
public Map<String, Object> properties;
/**
* The referenced services.
*
* <p>
* These are declared in the {@code reference} elements. The array must be
* empty if the component description does not declare references to any
* services.
*/
public ReferenceDTO[] references;
/**
* The name of the activate method.
*
* <p>
* This is declared in the {@code activate} attribute of the
* {@code component} element. This must be {@code null} if the component
* description does not declare an activate method name.
*/
public String activate;
/**
* The name of the deactivate method.
*
* <p>
* This is declared in the {@code deactivate} attribute of the
* {@code component} element. This must be {@code null} if the component
* description does not declare a deactivate method name.
*/
public String deactivate;
/**
* The name of the modified method.
*
* <p>
* This is declared in the {@code modified} attribute of the
* {@code component} element. This must be {@code null} if the component
* description does not declare a modified method name.
*/
public String modified;
/**
* The configuration policy.
*
* <p>
* This is declared in the {@code configuration-policy} attribute of the
* {@code component} element. This must be the default configuration policy
* if the component description does not declare a configuration policy.
*/
public String configurationPolicy;
/**
* The configuration pids.
*
* <p>
* These are declared in the {@code configuration-pid} attribute of the
* {@code component} element. This must contain the default configuration
* pid if the component description does not declare a configuration pid.
*/
public String[] configurationPid;
/**
* The factory properties.
* <p>
* These are declared in the component description by the
* {@code factory-property} and {@code factory-properties} elements. This
* must be {@code null} if the component description is not declared as a
* {@link #factory factory component}.
*
* @since 1.4
*/
public Map<String,Object> factoryProperties;
/**
* The activation fields.
* <p>
* These are declared in the {@code activation-fields} attribute of the
* {@code component} element. The array must be empty if the component
* description does not declare any activation fields.
*
* @since 1.4
*/
public String[] activationFields;
/**
* The constructor parameter count.
* <p>
* This is declared in the {@code init} attribute of the {@code component}
* element. This must be {@code 0} if the component description does not
* declare an {@code init} attribute.
*
* @since 1.4
*/
public int init;
}
| 28.282297
| 81
| 0.667907
|
45b6e258e4a48e0238d4c56feff2fda08f13f1db
| 411
|
package com.cezarykluczynski.stapi.util.constant;
import com.google.common.collect.Maps;
import java.util.Map;
public class Fraction {
public static final Map<String, Double> MAPPING = Maps.newHashMap();
static {
MAPPING.put("⅛", .125d);
MAPPING.put("¼", .25d);
MAPPING.put("⅜", .375d);
MAPPING.put("½", .5d);
MAPPING.put("⅝", .625d);
MAPPING.put("¾", .75d);
MAPPING.put("⅞", .875d);
}
}
| 18.681818
| 69
| 0.659367
|
8e796f42df7ac017b1759e8c285e52752fa54cfe
| 944
|
package com.bloomberg.system.comdb2.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class SqlTest {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Class.forName("com.bloomberg.system.comdb2.jdbc.Driver");
Connection conn = DriverManager
.getConnection("jdbc:comdb2:riversdb:ibm7");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from comdb2developers");
ResultSetMetaData md = rs.getMetaData();
int cnt = md.getColumnCount();
String[] colNames = new String[cnt];
for (int i = 0; i != cnt; ++i)
colNames[i] = md.getColumnName(i + 1);
while (rs.next()) {
for (int i = 0; i != cnt; ++i)
System.out.format("%s=%s\t ", colNames[i], rs.getString(i + 1));
System.out.println();
}
}
}
| 26.971429
| 70
| 0.702331
|
24c35798970c25f698043e6f3e4537355fd06e5b
| 10,540
|
/**
* Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.telefonica.services.service.persistence;
import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.ReferenceRegistry;
import com.liferay.portal.service.ServiceContext;
import com.telefonica.services.model.Department;
import java.util.List;
/**
* The persistence utility for the department service. This utility wraps {@link DepartmentPersistenceImpl} and provides direct access to the database for CRUD operations. This utility should only be used by the service layer, as it must operate within a transaction. Never access this utility in a JSP, controller, model, or other front-end class.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author plazaro
* @see DepartmentPersistence
* @see DepartmentPersistenceImpl
* @generated
*/
public class DepartmentUtil {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify this class directly. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
*/
/**
* @see com.liferay.portal.service.persistence.BasePersistence#clearCache()
*/
public static void clearCache() {
getPersistence().clearCache();
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#clearCache(com.liferay.portal.model.BaseModel)
*/
public static void clearCache(Department department) {
getPersistence().clearCache(department);
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#countWithDynamicQuery(DynamicQuery)
*/
public long countWithDynamicQuery(DynamicQuery dynamicQuery)
throws SystemException {
return getPersistence().countWithDynamicQuery(dynamicQuery);
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#findWithDynamicQuery(DynamicQuery)
*/
public static List<Department> findWithDynamicQuery(
DynamicQuery dynamicQuery) throws SystemException {
return getPersistence().findWithDynamicQuery(dynamicQuery);
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#findWithDynamicQuery(DynamicQuery, int, int)
*/
public static List<Department> findWithDynamicQuery(
DynamicQuery dynamicQuery, int start, int end)
throws SystemException {
return getPersistence().findWithDynamicQuery(dynamicQuery, start, end);
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#findWithDynamicQuery(DynamicQuery, int, int, OrderByComparator)
*/
public static List<Department> findWithDynamicQuery(
DynamicQuery dynamicQuery, int start, int end,
OrderByComparator orderByComparator) throws SystemException {
return getPersistence()
.findWithDynamicQuery(dynamicQuery, start, end,
orderByComparator);
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#update(com.liferay.portal.model.BaseModel, boolean)
*/
public static Department update(Department department, boolean merge)
throws SystemException {
return getPersistence().update(department, merge);
}
/**
* @see com.liferay.portal.service.persistence.BasePersistence#update(com.liferay.portal.model.BaseModel, boolean, ServiceContext)
*/
public static Department update(Department department, boolean merge,
ServiceContext serviceContext) throws SystemException {
return getPersistence().update(department, merge, serviceContext);
}
/**
* Caches the department in the entity cache if it is enabled.
*
* @param department the department
*/
public static void cacheResult(
com.telefonica.services.model.Department department) {
getPersistence().cacheResult(department);
}
/**
* Caches the departments in the entity cache if it is enabled.
*
* @param departments the departments
*/
public static void cacheResult(
java.util.List<com.telefonica.services.model.Department> departments) {
getPersistence().cacheResult(departments);
}
/**
* Creates a new department with the primary key. Does not add the department to the database.
*
* @param dpt_name the primary key for the new department
* @return the new department
*/
public static com.telefonica.services.model.Department create(
java.lang.String dpt_name) {
return getPersistence().create(dpt_name);
}
/**
* Removes the department with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param dpt_name the primary key of the department
* @return the department that was removed
* @throws com.telefonica.services.NoSuchDepartmentException if a department with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public static com.telefonica.services.model.Department remove(
java.lang.String dpt_name)
throws com.liferay.portal.kernel.exception.SystemException,
com.telefonica.services.NoSuchDepartmentException {
return getPersistence().remove(dpt_name);
}
public static com.telefonica.services.model.Department updateImpl(
com.telefonica.services.model.Department department, boolean merge)
throws com.liferay.portal.kernel.exception.SystemException {
return getPersistence().updateImpl(department, merge);
}
/**
* Returns the department with the primary key or throws a {@link com.telefonica.services.NoSuchDepartmentException} if it could not be found.
*
* @param dpt_name the primary key of the department
* @return the department
* @throws com.telefonica.services.NoSuchDepartmentException if a department with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public static com.telefonica.services.model.Department findByPrimaryKey(
java.lang.String dpt_name)
throws com.liferay.portal.kernel.exception.SystemException,
com.telefonica.services.NoSuchDepartmentException {
return getPersistence().findByPrimaryKey(dpt_name);
}
/**
* Returns the department with the primary key or returns <code>null</code> if it could not be found.
*
* @param dpt_name the primary key of the department
* @return the department, or <code>null</code> if a department with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public static com.telefonica.services.model.Department fetchByPrimaryKey(
java.lang.String dpt_name)
throws com.liferay.portal.kernel.exception.SystemException {
return getPersistence().fetchByPrimaryKey(dpt_name);
}
/**
* Returns all the departments.
*
* @return the departments
* @throws SystemException if a system exception occurred
*/
public static java.util.List<com.telefonica.services.model.Department> findAll()
throws com.liferay.portal.kernel.exception.SystemException {
return getPersistence().findAll();
}
/**
* Returns a range of all the departments.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of departments
* @param end the upper bound of the range of departments (not inclusive)
* @return the range of departments
* @throws SystemException if a system exception occurred
*/
public static java.util.List<com.telefonica.services.model.Department> findAll(
int start, int end)
throws com.liferay.portal.kernel.exception.SystemException {
return getPersistence().findAll(start, end);
}
/**
* Returns an ordered range of all the departments.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of departments
* @param end the upper bound of the range of departments (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of departments
* @throws SystemException if a system exception occurred
*/
public static java.util.List<com.telefonica.services.model.Department> findAll(
int start, int end,
com.liferay.portal.kernel.util.OrderByComparator orderByComparator)
throws com.liferay.portal.kernel.exception.SystemException {
return getPersistence().findAll(start, end, orderByComparator);
}
/**
* Removes all the departments from the database.
*
* @throws SystemException if a system exception occurred
*/
public static void removeAll()
throws com.liferay.portal.kernel.exception.SystemException {
getPersistence().removeAll();
}
/**
* Returns the number of departments.
*
* @return the number of departments
* @throws SystemException if a system exception occurred
*/
public static int countAll()
throws com.liferay.portal.kernel.exception.SystemException {
return getPersistence().countAll();
}
public static DepartmentPersistence getPersistence() {
if (_persistence == null) {
_persistence = (DepartmentPersistence)PortletBeanLocatorUtil.locate(com.telefonica.services.service.ClpSerializer.getServletContextName(),
DepartmentPersistence.class.getName());
ReferenceRegistry.registerReference(DepartmentUtil.class,
"_persistence");
}
return _persistence;
}
/**
* @deprecated
*/
public void setPersistence(DepartmentPersistence persistence) {
}
private static DepartmentPersistence _persistence;
}
| 37.375887
| 398
| 0.768501
|
7e8918af36b70c6f3fa03f9353f78e0b19527675
| 879
|
package br.com.beblue.discbackapi.spotify.client;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@SpringBootTest
@RunWith(SpringRunner.class)
@EnableFeignClients(clients = SpotifyAuthenticationClient.class)
public class SpotifyAuthenticationClientIntegrationTest {
private @Autowired SpotifyAuthenticationClient client;
@Test
public void shouldReturnAuthenticationResponse_whenGetTokenIsCalled() {
final var response = client.getToken();
assertTrue(response.isPresent());
assertNotNull(response.get());
}
}
| 31.392857
| 73
| 0.825939
|
1ddc1a024793edb9d8f2533f2c98fe710693f3ac
| 6,374
|
/*
* Charybdis - Cassandra ORM framework
*
* Copyright (C) 2020 Charybdis authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ma.markware.charybdis.query;
import com.datastax.oss.driver.api.core.cql.SimpleStatement;
import com.datastax.oss.driver.api.querybuilder.QueryBuilder;
import com.datastax.oss.driver.api.querybuilder.insert.Insert;
import com.datastax.oss.driver.api.querybuilder.insert.InsertInto;
import com.datastax.oss.driver.api.querybuilder.insert.RegularInsert;
import ma.markware.charybdis.ExecutionContext;
import ma.markware.charybdis.model.field.metadata.ColumnMetadata;
import ma.markware.charybdis.model.field.metadata.TableMetadata;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import static java.lang.String.format;
/**
* Insert query.
*
* @author Oussama Markad
*/
public class InsertQuery extends AbstractQuery {
private String keyspace;
private String table;
private ColumnNameValueMapping columnNameValueMapping = new ColumnNameValueMapping();
private Integer ttl;
private Long timestamp;
private boolean ifNotExists;
public InsertQuery(@Nonnull ExecutionContext executionContext) {
super(executionContext);
}
public String getKeyspace() {
return keyspace;
}
public String getTable() {
return table;
}
public ColumnNameValueMapping getColumnNameValueMapping() {
return columnNameValueMapping;
}
public Integer getTtl() {
return ttl;
}
public Long getTimestamp() {
return timestamp;
}
public boolean isIfNotExists() {
return ifNotExists;
}
public void setTable(TableMetadata tableMetadata) {
keyspace = tableMetadata.getKeyspaceName();
table = tableMetadata.getTableName();
columnNameValueMapping.setTableMetadata(tableMetadata);
executionContext.setDefaultConsistencyLevel(tableMetadata.getDefaultWriteConsistency());
}
public void setTableAndColumns(TableMetadata tableMetadata, ColumnMetadata... columns) {
setTable(tableMetadata);
for (int i = 0; i < columns.length; i++) {
columnNameValueMapping.setColumnName(i, columns[i].getName());
}
}
public void setValues(Object... values) {
for (int i = 0; i < values.length; i++) {
columnNameValueMapping.setColumnValue(i, values[i]);
}
}
public void setColumnNameValueMapping(Map<String, Object> columnNameValues) {
for (Entry<String, Object> entry : columnNameValues.entrySet()) {
columnNameValueMapping.setColumnNameAndValue(entry.getKey(), entry.getValue());
}
}
public <D, S> void setSet(ColumnMetadata<D, S> columnMetadata, D value) {
columnNameValueMapping.setColumnNameAndValue(columnMetadata.getName(), columnMetadata.serialize(value));
}
public void enableIfNotExists() {
this.ifNotExists = true;
}
public void setTtl(int ttl) {
this.ttl = ttl;
}
public void setTimestamp(Instant timestamp) {
this.timestamp = timestamp.toEpochMilli();
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
/**
* {@inheritDoc}
*/
@Override
public StatementTuple buildStatement() {
InsertInto insertInto = QueryBuilder.insertInto(keyspace, table);
Object[] bindValueArray = new Object[columnNameValueMapping.size()];
int bindIndex = 0;
RegularInsert regularInsert = (RegularInsert) insertInto;
for (Pair<String, Object> columnNameValuePair : columnNameValueMapping.values()) {
String columnName = columnNameValuePair.getLeft();
bindValueArray[bindIndex] = columnNameValuePair.getRight();
regularInsert = regularInsert.value(ma.markware.charybdis.model.utils.StringUtils.quoteString(columnName), QueryBuilder.bindMarker());
bindIndex++;
}
Insert insert = regularInsert;
if (ifNotExists) {
insert = insert.ifNotExists();
}
if (ttl != null) {
insert = insert.usingTtl(ttl);
}
if (timestamp != null) {
insert = insert.usingTimestamp(timestamp);
}
SimpleStatement simpleStatement = insert.build();
return new StatementTuple(simpleStatement, bindValueArray);
}
public static final class ColumnNameValueMapping {
private TableMetadata tableMetadata;
private int lastIndex = -1;
private Map<Integer, Pair<String, Object>> columnNameValuePairs = new HashMap<>();
public Map<Integer, Pair<String, Object>> getColumnNameValuePairs() {
return columnNameValuePairs;
}
public void setTableMetadata(final TableMetadata tableMetadata) {
this.tableMetadata = tableMetadata;
}
void setColumnNameAndValue(String columnName, Object value) {
columnNameValuePairs.put(++lastIndex, Pair.of(columnName, value));
}
void setColumnName(int index, String columnName) {
columnNameValuePairs.put(index, Pair.of(columnName, null));
}
@SuppressWarnings("unchecked")
void setColumnValue(int index, Object value) {
Pair<String, Object> columnNameValuePair = columnNameValuePairs.get(index);
if (columnNameValuePair == null || StringUtils.isBlank(columnNameValuePair.getLeft())) {
throw new IllegalStateException(format("Cannot bind value in position '%d' with a column", index));
}
String columnName = columnNameValuePair.getLeft();
ColumnMetadata columnMetadata = tableMetadata.getColumnMetadata(columnName);
columnNameValuePair = Pair.of(columnName, columnMetadata.serialize(value));
columnNameValuePairs.put(index, columnNameValuePair);
}
int size() {
return columnNameValuePairs.size();
}
Collection<Pair<String, Object>> values() {
return columnNameValuePairs.values();
}
}
}
| 30.941748
| 140
| 0.730468
|
6026f7e745159c8b21a6b3d7521d766077863475
| 4,584
|
package lang.relation;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.ArrayList;
import lang.ast.Constant;
import lang.ast.List;
import lang.ast.Term;
import lang.ast.Variable;
public class PseudoTuple implements Comparable<PseudoTuple> {
private int size;
private Term[] tuple;
public static final Variable uninitializedVar = new Variable("UNINITIALZIED VARIABLE");
public PseudoTuple(TreeSet<Variable> vars) {
this.size = vars.size();
this.tuple = new Term[size];
vars.toArray(this.tuple);
}
public PseudoTuple(List<Term> terms) {
this.size = terms.getNumChild();
this.tuple = new Term[size];
for(int i = 0; i != size; ++i) {
tuple[i] = terms.getChild(i);
}
}
public PseudoTuple(java.util.List<Term> terms) {
this.size = terms.size();
this.tuple = new Term[size];
for(int i = 0; i != size; ++i) {
tuple[i] = terms.get(i);
}
}
public PseudoTuple(Term ... terms) {
this.size = terms.length;
this.tuple = new Term[size];
for (int i = 0; i != size; ++i) {
tuple[i] = terms[i];
}
}
public PseudoTuple(PseudoTuple o) {
this.size = o.size;
this.tuple = new Term[size];
for (int i = 0; i != size; ++i) {
tuple[i] = o.tuple[i];
}
}
public PseudoTuple(int size) {
this.size = size;
this.tuple = new Term[size];
for (int i = 0; i != size; ++i) {
tuple[i] = uninitializedVar;
}
}
public static PseudoTuple of(Term ... consts) {
PseudoTuple pt = new PseudoTuple(consts.length);
for(int i = 0; i != consts.length; ++i) {
pt.set(i, consts[i]);
}
return pt;
}
public java.util.List<Term> toList() {
java.util.List<Term> list = new ArrayList<Term>();
for(int i = 0; i != size; ++i)
list.add(tuple[i]);
return list;
}
public void expand() {
Term[] tmp = new Term[size];
System.arraycopy(tuple, 0, tmp, 0, size);
tuple = new Term[size + 1];
System.arraycopy(tmp, 0, tuple, 0, size);
tuple[size] = uninitializedVar;
size = size + 1;
}
public int arity() {
return size;
}
public boolean instantiatedAt(int i) {
return !tuple[i].isVariable();
}
public Term coord(int i) {
return tuple[i];
}
public PseudoTuple instantiate(int i, Constant c) {
tuple[i] = c;
return this;
}
public PseudoTuple set(int i, Term t) {
tuple[i] = t;
return this;
}
public void instantiateAll(Set<Integer> positions, Constant c) {
positions.forEach(i -> tuple[i] = c);
}
public PseudoTuple project(Set<Integer> positions) {
PseudoTuple t = new PseudoTuple(positions.size());
int i = 0;
for(Integer j : positions) {
t.tuple[i++] = tuple[j];
}
return t;
}
public boolean isUniInfo() {
if(tuple.length <= 1) return true;
Term first = tuple[0];
for(int i = 1; i != tuple.length; ++i) {
if(Term.termComparator.compare(first, tuple[i]) != 0) return false;
}
return true;
}
public void collectTuple(StringBuilder sb) {
if (size == 0)
return;
if (size == 1) {
sb.append("(").append(tuple[0].toString()).append(")");
return;
}
sb.append("(");
sb.append(tuple[0].toString());
for (int i = 1; i != size; ++i) {
sb.append(",").append(tuple[i].toString());
}
sb.append(")");
}
public boolean isGround() {
for (int i = 0; i != size; ++i)
if (!instantiatedAt(i))
return false;
return true;
}
public Set<Integer> unboundPositions() {
Set<Integer> unbound = new HashSet<Integer>();
for (int i = 0; i != size; ++i) {
if(!instantiatedAt(i)) unbound.add(i);
}
return unbound;
}
public TreeSet<Variable> freeVariables() {
TreeSet<Variable> freeVars = new TreeSet<Variable>(Term.termComparator);
for(int i = 0; i != size; ++i) {
Term t = tuple[i];
if(t.isVariable()) {
freeVars.add((Variable)t);
}
}
return freeVars;
}
@Override
public int compareTo(PseudoTuple arg0) {
for (int i = 0; i != size; ++i) {
int res = Term.termComparator.compare(coord(i), arg0.coord(i));
if (res != 0)
return res;
}
return 0;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof PseudoTuple)) return false;
return compareTo((PseudoTuple) obj) == 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
collectTuple(sb);
return sb.toString();
}
public String[] toStringArray() {
String[] strs = new String[size];
for(int i = 0; i != size; ++i) {
strs[i] = tuple[i].toString();
}
return strs;
}
public static PseudoTuple cat(PseudoTuple l, PseudoTuple r) {
java.util.List<Term> ts = l.toList();
ts.addAll(r.toList());
return new PseudoTuple(ts);
}
}
| 21.622642
| 88
| 0.628709
|
37bdc9204c15efb0f212244e9ca5b35480b1da75
| 942
|
package com.ksa.web.struts2.action.data;
import com.ksa.web.struts2.action.model.GridDataModel;
import com.opensymphony.xwork2.Action;
public interface GridDataAction extends Action {
/** 降序排序 */
public static final String SORT_ORDER_DESC = "desc";
/** 升序排序 */
public static final String SORT_ORDER_ASC = "asc";
/**
* 设置所获取的分页数据的页码,起始页码为 1 。
* @param page 页码,起始页码为 1
*/
void setPage( int page );
/**
* 设置所获取的分页数据的单页数据量。
* @param rows 单页数据量
*/
void setRows( int rows );
/**
* 设置所获取的分页数据的排序列名称。
* @param sort 排序列名称
*/
void setSort( String sort );
/**
* 设置所获取的分页数据的排序顺序,'asc' 表示顺序,'desc' 表示逆序。
* @param order 'asc' 表示顺序,'desc' 表示逆序
*/
void setOrder( String order );
/**
* 获取分页数据结果。
* @return 列表数据
*/
GridDataModel getGridData();
}
| 20.933333
| 57
| 0.548832
|
99a570f147fe5b29c4da2b3172fb738c0be7fca6
| 4,171
|
package uk.ac.manchester.cs.jfact.split;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.semanticweb.owlapi.util.MultiMap;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.Axiom;
import uk.ac.manchester.cs.jfact.kernel.dl.interfaces.NamedEntity;
import conformance.Original;
import conformance.PortedFrom;
@PortedFrom(file = "SigIndex.h", name = "SigIndex")
public class SigIndex {
/** map between entities and axioms that contains them in their signature */
@PortedFrom(file = "SigIndex.h", name = "Base")
MultiMap<NamedEntity, Axiom> Base = new MultiMap<NamedEntity, Axiom>();
/** locality checker */
@PortedFrom(file = "SigIndex.h", name = "Checker")
LocalityChecker Checker;
/** sets of axioms non-local wrt the empty signature */
@Original
Set<Axiom> NonLocalTrue = new HashSet<Axiom>();
@Original
Set<Axiom> NonLocalFalse = new HashSet<Axiom>();
/** empty signature to test the non-locality */
@PortedFrom(file = "SigIndex.h", name = "emptySig")
TSignature emptySig = new TSignature();
/** number of registered axioms */
@PortedFrom(file = "SigIndex.h", name = "nRegistered")
int nRegistered = 0;
/** number of registered axioms */
@PortedFrom(file = "SigIndex.h", name = "nUnregistered")
int nUnregistered = 0;
// access to statistics
/** @return number of ever processed axioms */
@PortedFrom(file = "SigIndex.h", name = "nProcessedAx")
public int nProcessedAx() {
return nRegistered;
}
/** add axiom AX to the non-local set with top-locality value TOP */
@PortedFrom(file = "SigIndex.h", name = "checkNonLocal")
private void checkNonLocal(Axiom ax, boolean top) {
emptySig.setLocality(top);
Checker.setSignatureValue(emptySig);
if (!Checker.local(ax)) {
if (top) {
NonLocalFalse.add(ax);
} else {
NonLocalTrue.add(ax);
}
}
}
/** empty c'tor */
public SigIndex(LocalityChecker c) {
Checker = c;
}
// work with axioms
/** register an axiom */
@PortedFrom(file = "SigIndex.h", name = "registerAx")
private void registerAx(Axiom ax) {
for (NamedEntity p : ax.getSignature().begin()) {
Base.put(p, ax);
}
// check whether the axiom is non-local
checkNonLocal(ax, false);
checkNonLocal(ax, true);
++nRegistered;
}
/** unregister an axiom AX */
@PortedFrom(file = "SigIndex.h", name = "unregisterAx")
private void unregisterAx(Axiom ax) {
for (NamedEntity p : ax.getSignature().begin()) {
Base.get(p).remove(ax);
}
// remove from the non-locality
NonLocalFalse.remove(ax);
NonLocalTrue.remove(ax);
++nUnregistered;
}
/** process an axiom wrt its Used status */
@PortedFrom(file = "SigIndex.h", name = "processAx")
public void processAx(Axiom ax) {
if (ax.isUsed()) {
registerAx(ax);
} else {
unregisterAx(ax);
}
}
/** preprocess given set of axioms */
@PortedFrom(file = "SigIndex.h", name = "preprocessOntology")
public void preprocessOntology(Collection<Axiom> axioms) {
for (Axiom ax : axioms) {
processAx(ax);
}
}
/** clear internal structures */
@PortedFrom(file = "SigIndex.h", name = "clear")
public void clear() {
Base.clear();
NonLocalFalse.clear();
NonLocalTrue.clear();
}
// get the set by the index
/** given an entity, return a set of all axioms that tontain this entity in a
* signature */
@PortedFrom(file = "SigIndex.h", name = "getAxioms")
public Collection<Axiom> getAxioms(NamedEntity entity) {
final Collection<Axiom> collection = Base.get(entity);
return collection;
}
/** get the non-local axioms with top-locality value TOP */
@PortedFrom(file = "SigIndex.h", name = "getNonLocal")
public Set<Axiom> getNonLocal(boolean top) {
return top ? NonLocalFalse : NonLocalTrue;
}
}
| 32.333333
| 81
| 0.616159
|
82c662df28f7f1e520f21840cd52dbdba3d4e911
| 8,059
|
/*
* Copyright (C) 2013 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2012 Pierre-Yves Ricau <py.ricau@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hardsoftstudio.real.textview.views;
import android.content.Context;
import android.os.Build;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
import com.hardsoftstudio.real.textview.utils.AutofitHelper;
import java.util.ArrayList;
import java.util.List;
public class BaseTextView extends TextView {
protected AutofitHelper mHelper;
private static class FixingResult {
public final boolean fixed;
public final List<Object> spansWithSpacesBefore;
public final List<Object> spansWithSpacesAfter;
public static FixingResult fixed(List<Object> spansWithSpacesBefore,
List<Object> spansWithSpacesAfter) {
return new FixingResult(true, spansWithSpacesBefore, spansWithSpacesAfter);
}
public static FixingResult notFixed() {
return new FixingResult(false, null, null);
}
private FixingResult(boolean fixed, List<Object> spansWithSpacesBefore,
List<Object> spansWithSpacesAfter) {
this.fixed = fixed;
this.spansWithSpacesBefore = spansWithSpacesBefore;
this.spansWithSpacesAfter = spansWithSpacesAfter;
}
}
public BaseTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public BaseTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BaseTextView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
try {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (IndexOutOfBoundsException e) {
fixOnMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
/**
* If possible, fixes the Spanned text by adding spaces around spans when needed.
*/
private void fixOnMeasure(int widthMeasureSpec, int heightMeasureSpec) {
CharSequence text = getText();
if (text instanceof Spanned) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
fixSpannedWithSpaces(builder, widthMeasureSpec, heightMeasureSpec);
} else {
if (RealTextView.DEBUG) {
Log.d("MPB", "The text isn't a Spanned");
}
fallbackToString(widthMeasureSpec, heightMeasureSpec);
}
}
/**
* Add spaces around spans until the text is fixed, and then removes the unneeded spaces
*/
private void fixSpannedWithSpaces(SpannableStringBuilder builder, int widthMeasureSpec,
int heightMeasureSpec) {
long startFix = System.currentTimeMillis();
FixingResult result = addSpacesAroundSpansUntilFixed(builder, widthMeasureSpec,
heightMeasureSpec);
if (result.fixed) {
removeUnneededSpaces(widthMeasureSpec, heightMeasureSpec, builder, result);
} else {
fallbackToString(widthMeasureSpec, heightMeasureSpec);
}
if (RealTextView.DEBUG) {
long fixDuration = System.currentTimeMillis() - startFix;
Log.d("MPB", "fixSpannedWithSpaces() duration in ms: " + fixDuration);
}
}
private FixingResult addSpacesAroundSpansUntilFixed(SpannableStringBuilder builder,
int widthMeasureSpec, int heightMeasureSpec) {
Object[] spans = builder.getSpans(0, builder.length(), Object.class);
List<Object> spansWithSpacesBefore = new ArrayList<Object>(spans.length);
List<Object> spansWithSpacesAfter = new ArrayList<Object>(spans.length);
for (Object span : spans) {
int spanStart = builder.getSpanStart(span);
if (isNotSpace(builder, spanStart - 1)) {
builder.insert(spanStart, " ");
spansWithSpacesBefore.add(span);
}
int spanEnd = builder.getSpanEnd(span);
if (isNotSpace(builder, spanEnd)) {
builder.insert(spanEnd, " ");
spansWithSpacesAfter.add(span);
}
try {
setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
return FixingResult.fixed(spansWithSpacesBefore, spansWithSpacesAfter);
} catch (IndexOutOfBoundsException notFixed) {
notFixed.printStackTrace();
}
}
if (RealTextView.DEBUG) {
Log.d("MPB", "Could not fix the Spanned by adding spaces around spans");
}
return FixingResult.notFixed();
}
private boolean isNotSpace(CharSequence text, int where) {
if (where < 0) {
return true;
}
return text.charAt(where) != ' ';
}
private void setTextAndMeasure(CharSequence text, int widthMeasureSpec, int heightMeasureSpec) {
setText(text);
super.measure(widthMeasureSpec, heightMeasureSpec);
}
private void removeUnneededSpaces(int widthMeasureSpec, int heightMeasureSpec,
SpannableStringBuilder builder, FixingResult result) {
for (Object span : result.spansWithSpacesAfter) {
int spanEnd = builder.getSpanEnd(span);
builder.delete(spanEnd, spanEnd + 1);
try {
setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
} catch (IndexOutOfBoundsException ignored) {
builder.insert(spanEnd, " ");
}
}
boolean needReset = true;
for (Object span : result.spansWithSpacesBefore) {
int spanStart = builder.getSpanStart(span);
builder.delete(spanStart - 1, spanStart);
try {
setTextAndMeasure(builder, widthMeasureSpec, heightMeasureSpec);
needReset = false;
} catch (IndexOutOfBoundsException ignored) {
needReset = true;
int newSpanStart = spanStart - 1;
builder.insert(newSpanStart, " ");
}
}
if (needReset) {
setText(builder);
super.measure(widthMeasureSpec, heightMeasureSpec);
}
}
private void fallbackToString(int widthMeasureSpec, int heightMeasureSpec) {
if (RealTextView.DEBUG) {
Log.d("MPB", "Fallback to unspanned text");
}
String fallbackText = getText().toString();
setTextAndMeasure(fallbackText, widthMeasureSpec, heightMeasureSpec);
}
/**
* By default the autofit is enabled, it automatically disabled when using html text
* @param b true to enable, false otherwise
*/
public void setAutoFit(boolean b) {
if (mHelper!=null)
mHelper.setEnabled(b);
else
throw new NullPointerException("The autofit is not init");
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh){
super.onSizeChanged(w, h, oldw, oldh);
if (Build.VERSION.SDK_INT < 11){
mHelper.autofit();
}
// Otherwise the OnLayoutChangedListener will be used
}
}
| 35.817778
| 102
| 0.632337
|
4411f5a3aff3c49568f3e67e175fd8fe05082b06
| 334
|
package domian;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* @author Fcb
* @date 2020/2/23
* @description
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Student {
private String name;
private int id;
private int age;
}
| 14.521739
| 33
| 0.736527
|
c45282cf40e604ca88d7d63d797fb22aaf7d232a
| 3,551
|
package ie.dit;
import ddf.minim.Minim; //import the minim library
import ddf.minim.AudioPlayer; //import the minim audio player
import java.util.ArrayList;
import processing.core.PApplet; //import the processing PApplet
import processing.core.PVector; //import the processing PVector
public class Helicopter extends GameObject { //create the Helicopter class
//declare variables
public int health;
public PVector forward;
public ArrayList<GameObject> objects;
public float rotor_theta, shadow_scale, fireRate = 1f, timeSinceLastEvent = 0;
public Minim minim; // Required to use Minim.
public AudioPlayer snd_shoot;
Helicopter(PApplet applet) { //constructor
super(applet);
//set the variables
w = 30;
h = 40;
health = 50;
rotor_theta = 0.0f;
shadow_scale = 0.6f;
location = new PVector(300, 300);
objects = new ArrayList<GameObject>();
minim = new Minim(this.applet); // Required to use Minim.
snd_shoot = minim.loadFile("data/shoot.wav");
} // End Constructor.
public void update() {
rotor_theta += 0.5f;
fire_bullet();
for (int i = 0; i < objects.size(); ++i) {
objects.get(i).run();
if (!objects.get(i).alive)//if the object is not alive
objects.remove(i); // remove it
} // End loop.
} // End update.
public void display() {
applet.noStroke();
draw_helicopter_shadow();
draw_rotor_shadow();
draw_helicopter();
draw_rotor();
draw_health_bar();
applet.noFill();
//applet.noStroke();
} // End Display.
private void draw_helicopter_shadow() {
applet.pushMatrix();
applet.translate( (location.x + (w/2)) + 15, (location.y + (h/2)) + 10);
applet.rotate(theta);
applet.scale(shadow_scale);
applet.fill( 0, 0, 0, 120 );
applet.rect(-15, h, 30, 3); // Tail fin.
applet.rect(-3,h-20, 6, h-20); // Tail.
applet.ellipse(0,0, w, h); // Body.
applet.popMatrix();
} // End draw_helicopter_shadow.
private void draw_rotor_shadow() {
applet.pushMatrix();
applet.translate( (location.x + (w/2)) + 15, (location.y + (h/2)) + 10);
applet.rotate(rotor_theta);
applet.scale(shadow_scale);
applet.fill(0);
applet.rect(-1.5f, -40, 3, 80); // Vertical rotor.
applet.rect(-40, -1.5f, 80, 3); // Horizontal rotor.
applet.popMatrix();
} // End draw_rotor_shadow.
private void draw_helicopter() {
applet.pushMatrix();
applet.translate(location.x + (w/2), location.y + (h/2));
applet.rotate(theta);
applet.fill( colour.getRed(), colour.getGreen(), colour.getBlue(), colour.getAlpha() );
applet.rect(-15, h, 30, 3); // Tail fin.
applet.rect(-3,h-20, 6, h-20); // Tail.
applet.ellipse(0,0, w, h); // Body.
applet.popMatrix();
} // End draw_helicopter.
private void draw_rotor() {
applet.pushMatrix();
applet.translate(location.x + (w/2), location.y + (h/2));
applet.rotate(rotor_theta);
applet.fill(0);
applet.rect(-1.5f, -40, 3, 80); // Vertical rotor.
applet.rect(-40, -1.5f, 80, 3); // Horizontal rotor.
applet.popMatrix();
} // End draw_rotor.
public void draw_health_bar() {
applet.pushMatrix();
applet.translate(location.x, location.y);
applet.fill(255, 0, 0, 255);
applet.rect(-health/3, 20, health, 5);
applet.popMatrix();
} // End draw_health_bar.
public void fire_bullet() {
if(applet.millis() - timeSinceLastEvent >= 1000/fireRate){
snd_shoot.rewind();
snd_shoot.play();
objects.add( new Bullet(applet, location.x+(w/2), location.y+(h/2), theta) );
timeSinceLastEvent = applet.millis();
}
} // End fire_bullet.
} // End Helicopter Class.
| 30.350427
| 89
| 0.662349
|
47b155d952f531129c52503540ef97cb6286284e
| 47,666
|
package android.support.v4.widget;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build.VERSION;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.Parcelable.ClassLoaderCreator;
import android.os.Parcelable.Creator;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.AbsSavedState;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.accessibility.AccessibilityEvent;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class SlidingPaneLayout
extends ViewGroup
{
private static final int DEFAULT_FADE_COLOR = -858993460;
private static final int DEFAULT_OVERHANG_SIZE = 32;
static final SlidingPanelLayoutImpl IMPL;
private static final int MIN_FLING_VELOCITY = 400;
private static final String TAG = "SlidingPaneLayout";
private boolean mCanSlide;
private int mCoveredFadeColor;
final ViewDragHelper mDragHelper;
private boolean mFirstLayout = true;
private float mInitialMotionX;
private float mInitialMotionY;
boolean mIsUnableToDrag;
private final int mOverhangSize;
private PanelSlideListener mPanelSlideListener;
private int mParallaxBy;
private float mParallaxOffset;
final ArrayList<DisableLayerRunnable> mPostedRunnables = new ArrayList();
boolean mPreservedOpenState;
private Drawable mShadowDrawableLeft;
private Drawable mShadowDrawableRight;
float mSlideOffset;
int mSlideRange;
View mSlideableView;
private int mSliderFadeColor = -858993460;
private final Rect mTmpRect = new Rect();
static
{
if (Build.VERSION.SDK_INT >= 17) {
IMPL = new SlidingPanelLayoutImplJBMR1();
} else if (Build.VERSION.SDK_INT >= 16) {
IMPL = new SlidingPanelLayoutImplJB();
} else {
IMPL = new SlidingPanelLayoutImplBase();
}
}
public SlidingPaneLayout(Context paramContext)
{
this(paramContext, null);
}
public SlidingPaneLayout(Context paramContext, AttributeSet paramAttributeSet)
{
this(paramContext, paramAttributeSet, 0);
}
public SlidingPaneLayout(Context paramContext, AttributeSet paramAttributeSet, int paramInt)
{
super(paramContext, paramAttributeSet, paramInt);
float f = paramContext.getResources().getDisplayMetrics().density;
this.mOverhangSize = ((int)(32.0F * f + 0.5F));
setWillNotDraw(false);
ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
ViewCompat.setImportantForAccessibility(this, 1);
this.mDragHelper = ViewDragHelper.create(this, 0.5F, new DragHelperCallback());
this.mDragHelper.setMinVelocity(f * 400.0F);
}
private boolean closePane(View paramView, int paramInt)
{
if ((!this.mFirstLayout) && (!smoothSlideTo(0.0F, paramInt))) {
return false;
}
this.mPreservedOpenState = false;
return true;
}
private void dimChildView(View paramView, float paramFloat, int paramInt)
{
LayoutParams localLayoutParams = (LayoutParams)paramView.getLayoutParams();
if ((paramFloat > 0.0F) && (paramInt != 0))
{
int i = (int)(((0xFF000000 & paramInt) >>> 24) * paramFloat);
if (localLayoutParams.dimPaint == null) {
localLayoutParams.dimPaint = new Paint();
}
localLayoutParams.dimPaint.setColorFilter(new PorterDuffColorFilter(i << 24 | paramInt & 0xFFFFFF, PorterDuff.Mode.SRC_OVER));
if (paramView.getLayerType() != 2) {
paramView.setLayerType(2, localLayoutParams.dimPaint);
}
invalidateChildRegion(paramView);
}
else if (paramView.getLayerType() != 0)
{
if (localLayoutParams.dimPaint != null) {
localLayoutParams.dimPaint.setColorFilter(null);
}
paramView = new DisableLayerRunnable(paramView);
this.mPostedRunnables.add(paramView);
ViewCompat.postOnAnimation(this, paramView);
}
}
private boolean openPane(View paramView, int paramInt)
{
if ((!this.mFirstLayout) && (!smoothSlideTo(1.0F, paramInt))) {
return false;
}
this.mPreservedOpenState = true;
return true;
}
private void parallaxOtherViews(float paramFloat)
{
boolean bool1 = isLayoutRtlSupport();
Object localObject = (LayoutParams)this.mSlideableView.getLayoutParams();
boolean bool2 = ((LayoutParams)localObject).dimWhenOffset;
int i = 0;
if (bool2)
{
if (bool1) {
j = ((LayoutParams)localObject).rightMargin;
} else {
j = ((LayoutParams)localObject).leftMargin;
}
if (j <= 0)
{
j = 1;
break label63;
}
}
int j = 0;
label63:
int k = getChildCount();
while (i < k)
{
localObject = getChildAt(i);
if (localObject != this.mSlideableView)
{
float f = this.mParallaxOffset;
int m = this.mParallaxBy;
int n = (int)((1.0F - f) * m);
this.mParallaxOffset = paramFloat;
m = n - (int)((1.0F - paramFloat) * m);
n = m;
if (bool1) {
n = -m;
}
((View)localObject).offsetLeftAndRight(n);
if (j != 0)
{
if (bool1) {
f = this.mParallaxOffset - 1.0F;
} else {
f = 1.0F - this.mParallaxOffset;
}
dimChildView((View)localObject, f, this.mCoveredFadeColor);
}
}
i++;
}
}
private static boolean viewIsOpaque(View paramView)
{
boolean bool1 = paramView.isOpaque();
boolean bool2 = true;
if (bool1) {
return true;
}
if (Build.VERSION.SDK_INT >= 18) {
return false;
}
paramView = paramView.getBackground();
if (paramView != null)
{
if (paramView.getOpacity() != -1) {
bool2 = false;
}
return bool2;
}
return false;
}
protected boolean canScroll(View paramView, boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3)
{
boolean bool1 = paramView instanceof ViewGroup;
boolean bool2 = true;
if (bool1)
{
ViewGroup localViewGroup = (ViewGroup)paramView;
int i = paramView.getScrollX();
int j = paramView.getScrollY();
for (int k = localViewGroup.getChildCount() - 1; k >= 0; k--)
{
View localView = localViewGroup.getChildAt(k);
int m = paramInt2 + i;
if ((m >= localView.getLeft()) && (m < localView.getRight()))
{
int n = paramInt3 + j;
if ((n >= localView.getTop()) && (n < localView.getBottom()) && (canScroll(localView, true, paramInt1, m - localView.getLeft(), n - localView.getTop()))) {
return true;
}
}
}
}
if (paramBoolean)
{
if (!isLayoutRtlSupport()) {
paramInt1 = -paramInt1;
}
if (paramView.canScrollHorizontally(paramInt1)) {
return bool2;
}
}
paramBoolean = false;
return paramBoolean;
}
@Deprecated
public boolean canSlide()
{
return this.mCanSlide;
}
protected boolean checkLayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
boolean bool;
if (((paramLayoutParams instanceof LayoutParams)) && (super.checkLayoutParams(paramLayoutParams))) {
bool = true;
} else {
bool = false;
}
return bool;
}
public boolean closePane()
{
return closePane(this.mSlideableView, 0);
}
public void computeScroll()
{
if (this.mDragHelper.continueSettling(true))
{
if (!this.mCanSlide)
{
this.mDragHelper.abort();
return;
}
ViewCompat.postInvalidateOnAnimation(this);
}
}
void dispatchOnPanelClosed(View paramView)
{
PanelSlideListener localPanelSlideListener = this.mPanelSlideListener;
if (localPanelSlideListener != null) {
localPanelSlideListener.onPanelClosed(paramView);
}
sendAccessibilityEvent(32);
}
void dispatchOnPanelOpened(View paramView)
{
PanelSlideListener localPanelSlideListener = this.mPanelSlideListener;
if (localPanelSlideListener != null) {
localPanelSlideListener.onPanelOpened(paramView);
}
sendAccessibilityEvent(32);
}
void dispatchOnPanelSlide(View paramView)
{
PanelSlideListener localPanelSlideListener = this.mPanelSlideListener;
if (localPanelSlideListener != null) {
localPanelSlideListener.onPanelSlide(paramView, this.mSlideOffset);
}
}
public void draw(Canvas paramCanvas)
{
super.draw(paramCanvas);
Drawable localDrawable;
if (isLayoutRtlSupport()) {
localDrawable = this.mShadowDrawableRight;
} else {
localDrawable = this.mShadowDrawableLeft;
}
View localView;
if (getChildCount() > 1) {
localView = getChildAt(1);
} else {
localView = null;
}
if ((localView != null) && (localDrawable != null))
{
int i = localView.getTop();
int j = localView.getBottom();
int k = localDrawable.getIntrinsicWidth();
int m;
int n;
if (isLayoutRtlSupport())
{
m = localView.getRight();
n = k + m;
}
else
{
m = localView.getLeft();
n = m;
m -= k;
}
localDrawable.setBounds(m, i, n, j);
localDrawable.draw(paramCanvas);
return;
}
}
protected boolean drawChild(Canvas paramCanvas, View paramView, long paramLong)
{
Object localObject = (LayoutParams)paramView.getLayoutParams();
int i = paramCanvas.save(2);
if ((this.mCanSlide) && (!((LayoutParams)localObject).slideable) && (this.mSlideableView != null))
{
paramCanvas.getClipBounds(this.mTmpRect);
if (isLayoutRtlSupport())
{
localObject = this.mTmpRect;
((Rect)localObject).left = Math.max(((Rect)localObject).left, this.mSlideableView.getRight());
}
else
{
localObject = this.mTmpRect;
((Rect)localObject).right = Math.min(((Rect)localObject).right, this.mSlideableView.getLeft());
}
paramCanvas.clipRect(this.mTmpRect);
}
boolean bool = super.drawChild(paramCanvas, paramView, paramLong);
paramCanvas.restoreToCount(i);
return bool;
}
protected ViewGroup.LayoutParams generateDefaultLayoutParams()
{
return new LayoutParams();
}
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet paramAttributeSet)
{
return new LayoutParams(getContext(), paramAttributeSet);
}
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
if ((paramLayoutParams instanceof ViewGroup.MarginLayoutParams)) {
paramLayoutParams = new LayoutParams((ViewGroup.MarginLayoutParams)paramLayoutParams);
} else {
paramLayoutParams = new LayoutParams(paramLayoutParams);
}
return paramLayoutParams;
}
public int getCoveredFadeColor()
{
return this.mCoveredFadeColor;
}
public int getParallaxDistance()
{
return this.mParallaxBy;
}
public int getSliderFadeColor()
{
return this.mSliderFadeColor;
}
void invalidateChildRegion(View paramView)
{
IMPL.invalidateChildRegion(this, paramView);
}
boolean isDimmed(View paramView)
{
boolean bool1 = false;
if (paramView == null) {
return false;
}
paramView = (LayoutParams)paramView.getLayoutParams();
boolean bool2 = bool1;
if (this.mCanSlide)
{
bool2 = bool1;
if (paramView.dimWhenOffset)
{
bool2 = bool1;
if (this.mSlideOffset > 0.0F) {
bool2 = true;
}
}
}
return bool2;
}
boolean isLayoutRtlSupport()
{
int i = ViewCompat.getLayoutDirection(this);
boolean bool = true;
if (i != 1) {
bool = false;
}
return bool;
}
public boolean isOpen()
{
boolean bool;
if ((this.mCanSlide) && (this.mSlideOffset != 1.0F)) {
bool = false;
} else {
bool = true;
}
return bool;
}
public boolean isSlideable()
{
return this.mCanSlide;
}
protected void onAttachedToWindow()
{
super.onAttachedToWindow();
this.mFirstLayout = true;
}
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
this.mFirstLayout = true;
int i = this.mPostedRunnables.size();
for (int j = 0; j < i; j++) {
((DisableLayerRunnable)this.mPostedRunnables.get(j)).run();
}
this.mPostedRunnables.clear();
}
public boolean onInterceptTouchEvent(MotionEvent paramMotionEvent)
{
int i = paramMotionEvent.getActionMasked();
boolean bool1 = this.mCanSlide;
boolean bool2 = true;
if ((!bool1) && (i == 0) && (getChildCount() > 1))
{
View localView = getChildAt(1);
if (localView != null) {
this.mPreservedOpenState = (this.mDragHelper.isViewUnder(localView, (int)paramMotionEvent.getX(), (int)paramMotionEvent.getY()) ^ true);
}
}
if ((this.mCanSlide) && ((!this.mIsUnableToDrag) || (i == 0)))
{
if ((i != 3) && (i != 1))
{
float f1;
float f2;
if (i != 0)
{
if (i == 2)
{
f1 = paramMotionEvent.getX();
f2 = paramMotionEvent.getY();
f1 = Math.abs(f1 - this.mInitialMotionX);
f2 = Math.abs(f2 - this.mInitialMotionY);
if ((f1 > this.mDragHelper.getTouchSlop()) && (f2 > f1))
{
this.mDragHelper.cancel();
this.mIsUnableToDrag = true;
return false;
}
}
}
else
{
this.mIsUnableToDrag = false;
f1 = paramMotionEvent.getX();
f2 = paramMotionEvent.getY();
this.mInitialMotionX = f1;
this.mInitialMotionY = f2;
if ((this.mDragHelper.isViewUnder(this.mSlideableView, (int)f1, (int)f2)) && (isDimmed(this.mSlideableView)))
{
i = 1;
break label251;
}
}
i = 0;
label251:
bool1 = bool2;
if (!this.mDragHelper.shouldInterceptTouchEvent(paramMotionEvent)) {
if (i != 0) {
bool1 = bool2;
} else {
bool1 = false;
}
}
return bool1;
}
this.mDragHelper.cancel();
return false;
}
this.mDragHelper.cancel();
return super.onInterceptTouchEvent(paramMotionEvent);
}
protected void onLayout(boolean paramBoolean, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
boolean bool = isLayoutRtlSupport();
if (bool) {
this.mDragHelper.setEdgeTrackingEnabled(2);
} else {
this.mDragHelper.setEdgeTrackingEnabled(1);
}
int i = paramInt3 - paramInt1;
if (bool) {
paramInt1 = getPaddingRight();
} else {
paramInt1 = getPaddingLeft();
}
if (bool) {
paramInt4 = getPaddingLeft();
} else {
paramInt4 = getPaddingRight();
}
int j = getPaddingTop();
int k = getChildCount();
if (this.mFirstLayout)
{
float f;
if ((this.mCanSlide) && (this.mPreservedOpenState)) {
f = 1.0F;
} else {
f = 0.0F;
}
this.mSlideOffset = f;
}
paramInt2 = paramInt1;
for (int m = 0; m < k; m++)
{
View localView = getChildAt(m);
if (localView.getVisibility() != 8)
{
LayoutParams localLayoutParams = (LayoutParams)localView.getLayoutParams();
int n = localView.getMeasuredWidth();
int i2;
if (localLayoutParams.slideable)
{
int i1 = localLayoutParams.leftMargin;
paramInt3 = localLayoutParams.rightMargin;
i2 = i - paramInt4;
i1 = Math.min(paramInt1, i2 - this.mOverhangSize) - paramInt2 - (i1 + paramInt3);
this.mSlideRange = i1;
if (bool) {
paramInt3 = localLayoutParams.rightMargin;
} else {
paramInt3 = localLayoutParams.leftMargin;
}
if (paramInt2 + paramInt3 + i1 + n / 2 > i2) {
paramBoolean = true;
} else {
paramBoolean = false;
}
localLayoutParams.dimWhenOffset = paramBoolean;
i2 = (int)(i1 * this.mSlideOffset);
paramInt2 = paramInt3 + i2 + paramInt2;
this.mSlideOffset = (i2 / this.mSlideRange);
paramInt3 = 0;
}
else
{
if (this.mCanSlide)
{
paramInt2 = this.mParallaxBy;
if (paramInt2 != 0)
{
paramInt3 = (int)((1.0F - this.mSlideOffset) * paramInt2);
paramInt2 = paramInt1;
break label356;
}
}
paramInt2 = paramInt1;
paramInt3 = 0;
}
label356:
if (bool)
{
paramInt3 = i - paramInt2 + paramInt3;
i2 = paramInt3 - n;
}
else
{
i2 = paramInt2 - paramInt3;
paramInt3 = i2 + n;
}
localView.layout(i2, j, paramInt3, localView.getMeasuredHeight() + j);
paramInt1 += localView.getWidth();
}
}
if (this.mFirstLayout)
{
if (this.mCanSlide)
{
if (this.mParallaxBy != 0) {
parallaxOtherViews(this.mSlideOffset);
}
if (((LayoutParams)this.mSlideableView.getLayoutParams()).dimWhenOffset) {
dimChildView(this.mSlideableView, this.mSlideOffset, this.mSliderFadeColor);
}
}
else
{
for (paramInt1 = 0; paramInt1 < k; paramInt1++) {
dimChildView(getChildAt(paramInt1), 0.0F, this.mSliderFadeColor);
}
}
updateObscuredViewsVisibility(this.mSlideableView);
}
this.mFirstLayout = false;
}
protected void onMeasure(int paramInt1, int paramInt2)
{
int i = View.MeasureSpec.getMode(paramInt1);
int j = View.MeasureSpec.getSize(paramInt1);
int k = View.MeasureSpec.getMode(paramInt2);
paramInt2 = View.MeasureSpec.getSize(paramInt2);
int m;
int n;
if (i != 1073741824)
{
if (isInEditMode())
{
if (i == Integer.MIN_VALUE)
{
m = j;
n = k;
paramInt1 = paramInt2;
}
else
{
m = j;
n = k;
paramInt1 = paramInt2;
if (i == 0)
{
m = 300;
n = k;
paramInt1 = paramInt2;
}
}
}
else {
throw new IllegalStateException("Width must have an exact value or MATCH_PARENT");
}
}
else
{
m = j;
n = k;
paramInt1 = paramInt2;
if (k == 0) {
if (isInEditMode())
{
m = j;
n = k;
paramInt1 = paramInt2;
if (k == 0)
{
n = Integer.MIN_VALUE;
paramInt1 = 300;
m = j;
}
}
else
{
throw new IllegalStateException("Height must not be UNSPECIFIED");
}
}
}
if (n != Integer.MIN_VALUE)
{
if (n != 1073741824)
{
paramInt1 = 0;
paramInt2 = 0;
}
else
{
paramInt1 = paramInt1 - getPaddingTop() - getPaddingBottom();
paramInt2 = paramInt1;
}
}
else
{
paramInt2 = paramInt1 - getPaddingTop() - getPaddingBottom();
paramInt1 = 0;
}
int i1 = m - getPaddingLeft() - getPaddingRight();
int i2 = getChildCount();
if (i2 > 2) {
Log.e("SlidingPaneLayout", "onMeasure: More than two child views are not supported.");
}
this.mSlideableView = null;
i = i1;
int i3 = 0;
boolean bool1 = false;
float f1 = 0.0F;
View localView;
LayoutParams localLayoutParams;
int i4;
for (j = paramInt1; i3 < i2; j = paramInt1)
{
localView = getChildAt(i3);
localLayoutParams = (LayoutParams)localView.getLayoutParams();
float f2;
if (localView.getVisibility() == 8)
{
localLayoutParams.dimWhenOffset = false;
f2 = f1;
paramInt1 = j;
}
else
{
f2 = f1;
if (localLayoutParams.weight > 0.0F)
{
f1 += localLayoutParams.weight;
f2 = f1;
if (localLayoutParams.width == 0)
{
f2 = f1;
paramInt1 = j;
break label588;
}
}
paramInt1 = localLayoutParams.leftMargin + localLayoutParams.rightMargin;
if (localLayoutParams.width == -2) {
paramInt1 = View.MeasureSpec.makeMeasureSpec(i1 - paramInt1, Integer.MIN_VALUE);
} else if (localLayoutParams.width == -1) {
paramInt1 = View.MeasureSpec.makeMeasureSpec(i1 - paramInt1, 1073741824);
} else {
paramInt1 = View.MeasureSpec.makeMeasureSpec(localLayoutParams.width, 1073741824);
}
if (localLayoutParams.height == -2) {
k = View.MeasureSpec.makeMeasureSpec(paramInt2, Integer.MIN_VALUE);
} else if (localLayoutParams.height == -1) {
k = View.MeasureSpec.makeMeasureSpec(paramInt2, 1073741824);
} else {
k = View.MeasureSpec.makeMeasureSpec(localLayoutParams.height, 1073741824);
}
localView.measure(paramInt1, k);
k = localView.getMeasuredWidth();
i4 = localView.getMeasuredHeight();
paramInt1 = j;
if (n == Integer.MIN_VALUE)
{
paramInt1 = j;
if (i4 > j) {
paramInt1 = Math.min(i4, paramInt2);
}
}
i -= k;
boolean bool2;
if (i < 0) {
bool2 = true;
} else {
bool2 = false;
}
localLayoutParams.slideable = bool2;
if (localLayoutParams.slideable) {
this.mSlideableView = localView;
}
bool1 = bool2 | bool1;
}
label588:
i3++;
f1 = f2;
}
if ((bool1) || (f1 > 0.0F))
{
k = i1 - this.mOverhangSize;
for (n = 0; n < i2; n++)
{
localView = getChildAt(n);
if (localView.getVisibility() != 8)
{
localLayoutParams = (LayoutParams)localView.getLayoutParams();
if (localView.getVisibility() != 8)
{
if ((localLayoutParams.width == 0) && (localLayoutParams.weight > 0.0F)) {
paramInt1 = 1;
} else {
paramInt1 = 0;
}
if (paramInt1 != 0) {
i3 = 0;
} else {
i3 = localView.getMeasuredWidth();
}
if ((bool1) && (localView != this.mSlideableView))
{
if ((localLayoutParams.width < 0) && ((i3 > k) || (localLayoutParams.weight > 0.0F)))
{
if (paramInt1 != 0)
{
if (localLayoutParams.height == -2) {
paramInt1 = View.MeasureSpec.makeMeasureSpec(paramInt2, Integer.MIN_VALUE);
} else if (localLayoutParams.height == -1) {
paramInt1 = View.MeasureSpec.makeMeasureSpec(paramInt2, 1073741824);
} else {
paramInt1 = View.MeasureSpec.makeMeasureSpec(localLayoutParams.height, 1073741824);
}
}
else {
paramInt1 = View.MeasureSpec.makeMeasureSpec(localView.getMeasuredHeight(), 1073741824);
}
localView.measure(View.MeasureSpec.makeMeasureSpec(k, 1073741824), paramInt1);
}
}
else if (localLayoutParams.weight > 0.0F)
{
if (localLayoutParams.width == 0)
{
if (localLayoutParams.height == -2) {
paramInt1 = View.MeasureSpec.makeMeasureSpec(paramInt2, Integer.MIN_VALUE);
} else if (localLayoutParams.height == -1) {
paramInt1 = View.MeasureSpec.makeMeasureSpec(paramInt2, 1073741824);
} else {
paramInt1 = View.MeasureSpec.makeMeasureSpec(localLayoutParams.height, 1073741824);
}
}
else {
paramInt1 = View.MeasureSpec.makeMeasureSpec(localView.getMeasuredHeight(), 1073741824);
}
if (bool1)
{
int i5 = i1 - (localLayoutParams.leftMargin + localLayoutParams.rightMargin);
i4 = View.MeasureSpec.makeMeasureSpec(i5, 1073741824);
if (i3 != i5) {
localView.measure(i4, paramInt1);
}
}
else
{
i4 = Math.max(0, i);
localView.measure(View.MeasureSpec.makeMeasureSpec(i3 + (int)(localLayoutParams.weight * i4 / f1), 1073741824), paramInt1);
}
}
}
}
}
}
setMeasuredDimension(m, j + getPaddingTop() + getPaddingBottom());
this.mCanSlide = bool1;
if ((this.mDragHelper.getViewDragState() != 0) && (!bool1)) {
this.mDragHelper.abort();
}
}
void onPanelDragged(int paramInt)
{
if (this.mSlideableView == null)
{
this.mSlideOffset = 0.0F;
return;
}
boolean bool = isLayoutRtlSupport();
LayoutParams localLayoutParams = (LayoutParams)this.mSlideableView.getLayoutParams();
int i = this.mSlideableView.getWidth();
int j = paramInt;
if (bool) {
j = getWidth() - paramInt - i;
}
if (bool) {
paramInt = getPaddingRight();
} else {
paramInt = getPaddingLeft();
}
if (bool) {
i = localLayoutParams.rightMargin;
} else {
i = localLayoutParams.leftMargin;
}
this.mSlideOffset = ((j - (paramInt + i)) / this.mSlideRange);
if (this.mParallaxBy != 0) {
parallaxOtherViews(this.mSlideOffset);
}
if (localLayoutParams.dimWhenOffset) {
dimChildView(this.mSlideableView, this.mSlideOffset, this.mSliderFadeColor);
}
dispatchOnPanelSlide(this.mSlideableView);
}
protected void onRestoreInstanceState(Parcelable paramParcelable)
{
if (!(paramParcelable instanceof SavedState))
{
super.onRestoreInstanceState(paramParcelable);
return;
}
paramParcelable = (SavedState)paramParcelable;
super.onRestoreInstanceState(paramParcelable.getSuperState());
if (paramParcelable.isOpen) {
openPane();
} else {
closePane();
}
this.mPreservedOpenState = paramParcelable.isOpen;
}
protected Parcelable onSaveInstanceState()
{
SavedState localSavedState = new SavedState(super.onSaveInstanceState());
boolean bool;
if (isSlideable()) {
bool = isOpen();
} else {
bool = this.mPreservedOpenState;
}
localSavedState.isOpen = bool;
return localSavedState;
}
protected void onSizeChanged(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
super.onSizeChanged(paramInt1, paramInt2, paramInt3, paramInt4);
if (paramInt1 != paramInt3) {
this.mFirstLayout = true;
}
}
public boolean onTouchEvent(MotionEvent paramMotionEvent)
{
if (!this.mCanSlide) {
return super.onTouchEvent(paramMotionEvent);
}
this.mDragHelper.processTouchEvent(paramMotionEvent);
float f1;
float f4;
switch (paramMotionEvent.getActionMasked())
{
default:
break;
case 1:
if (isDimmed(this.mSlideableView))
{
f1 = paramMotionEvent.getX();
float f2 = paramMotionEvent.getY();
float f3 = f1 - this.mInitialMotionX;
f4 = f2 - this.mInitialMotionY;
int i = this.mDragHelper.getTouchSlop();
if ((f3 * f3 + f4 * f4 < i * i) && (this.mDragHelper.isViewUnder(this.mSlideableView, (int)f1, (int)f2))) {
closePane(this.mSlideableView, 0);
}
}
break;
case 0:
f4 = paramMotionEvent.getX();
f1 = paramMotionEvent.getY();
this.mInitialMotionX = f4;
this.mInitialMotionY = f1;
}
return true;
}
public boolean openPane()
{
return openPane(this.mSlideableView, 0);
}
public void requestChildFocus(View paramView1, View paramView2)
{
super.requestChildFocus(paramView1, paramView2);
if ((!isInTouchMode()) && (!this.mCanSlide))
{
boolean bool;
if (paramView1 == this.mSlideableView) {
bool = true;
} else {
bool = false;
}
this.mPreservedOpenState = bool;
}
}
void setAllChildrenVisible()
{
int i = getChildCount();
for (int j = 0; j < i; j++)
{
View localView = getChildAt(j);
if (localView.getVisibility() == 4) {
localView.setVisibility(0);
}
}
}
public void setCoveredFadeColor(int paramInt)
{
this.mCoveredFadeColor = paramInt;
}
public void setPanelSlideListener(PanelSlideListener paramPanelSlideListener)
{
this.mPanelSlideListener = paramPanelSlideListener;
}
public void setParallaxDistance(int paramInt)
{
this.mParallaxBy = paramInt;
requestLayout();
}
@Deprecated
public void setShadowDrawable(Drawable paramDrawable)
{
setShadowDrawableLeft(paramDrawable);
}
public void setShadowDrawableLeft(Drawable paramDrawable)
{
this.mShadowDrawableLeft = paramDrawable;
}
public void setShadowDrawableRight(Drawable paramDrawable)
{
this.mShadowDrawableRight = paramDrawable;
}
@Deprecated
public void setShadowResource(int paramInt)
{
setShadowDrawable(getResources().getDrawable(paramInt));
}
public void setShadowResourceLeft(int paramInt)
{
setShadowDrawableLeft(ContextCompat.getDrawable(getContext(), paramInt));
}
public void setShadowResourceRight(int paramInt)
{
setShadowDrawableRight(ContextCompat.getDrawable(getContext(), paramInt));
}
public void setSliderFadeColor(int paramInt)
{
this.mSliderFadeColor = paramInt;
}
@Deprecated
public void smoothSlideClosed()
{
closePane();
}
@Deprecated
public void smoothSlideOpen()
{
openPane();
}
boolean smoothSlideTo(float paramFloat, int paramInt)
{
if (!this.mCanSlide) {
return false;
}
boolean bool = isLayoutRtlSupport();
Object localObject = (LayoutParams)this.mSlideableView.getLayoutParams();
if (bool)
{
paramInt = getPaddingRight();
int i = ((LayoutParams)localObject).rightMargin;
int j = this.mSlideableView.getWidth();
paramInt = (int)(getWidth() - (paramInt + i + paramFloat * this.mSlideRange + j));
}
else
{
paramInt = (int)(getPaddingLeft() + ((LayoutParams)localObject).leftMargin + paramFloat * this.mSlideRange);
}
ViewDragHelper localViewDragHelper = this.mDragHelper;
localObject = this.mSlideableView;
if (localViewDragHelper.smoothSlideViewTo((View)localObject, paramInt, ((View)localObject).getTop()))
{
setAllChildrenVisible();
ViewCompat.postInvalidateOnAnimation(this);
return true;
}
return false;
}
void updateObscuredViewsVisibility(View paramView)
{
boolean bool = isLayoutRtlSupport();
int i;
if (bool) {
i = getWidth() - getPaddingRight();
} else {
i = getPaddingLeft();
}
int j;
if (bool) {
j = getPaddingLeft();
} else {
j = getWidth() - getPaddingRight();
}
int k = getPaddingTop();
int m = getHeight();
int n = getPaddingBottom();
int i1;
int i2;
int i3;
int i4;
if ((paramView != null) && (viewIsOpaque(paramView)))
{
i1 = paramView.getLeft();
i2 = paramView.getRight();
i3 = paramView.getTop();
i4 = paramView.getBottom();
}
else
{
i1 = 0;
i2 = 0;
i3 = 0;
i4 = 0;
}
int i5 = getChildCount();
for (int i6 = 0; i6 < i5; i6++)
{
View localView = getChildAt(i6);
if (localView == paramView) {
break;
}
if (localView.getVisibility() != 8)
{
if (bool) {
i7 = j;
} else {
i7 = i;
}
int i8 = Math.max(i7, localView.getLeft());
int i9 = Math.max(k, localView.getTop());
if (bool) {
i7 = i;
} else {
i7 = j;
}
int i7 = Math.min(i7, localView.getRight());
int i10 = Math.min(m - n, localView.getBottom());
if ((i8 >= i1) && (i9 >= i3) && (i7 <= i2) && (i10 <= i4)) {
i7 = 4;
} else {
i7 = 0;
}
localView.setVisibility(i7);
}
}
}
class AccessibilityDelegate
extends AccessibilityDelegateCompat
{
private final Rect mTmpRect = new Rect();
AccessibilityDelegate() {}
private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat paramAccessibilityNodeInfoCompat1, AccessibilityNodeInfoCompat paramAccessibilityNodeInfoCompat2)
{
Rect localRect = this.mTmpRect;
paramAccessibilityNodeInfoCompat2.getBoundsInParent(localRect);
paramAccessibilityNodeInfoCompat1.setBoundsInParent(localRect);
paramAccessibilityNodeInfoCompat2.getBoundsInScreen(localRect);
paramAccessibilityNodeInfoCompat1.setBoundsInScreen(localRect);
paramAccessibilityNodeInfoCompat1.setVisibleToUser(paramAccessibilityNodeInfoCompat2.isVisibleToUser());
paramAccessibilityNodeInfoCompat1.setPackageName(paramAccessibilityNodeInfoCompat2.getPackageName());
paramAccessibilityNodeInfoCompat1.setClassName(paramAccessibilityNodeInfoCompat2.getClassName());
paramAccessibilityNodeInfoCompat1.setContentDescription(paramAccessibilityNodeInfoCompat2.getContentDescription());
paramAccessibilityNodeInfoCompat1.setEnabled(paramAccessibilityNodeInfoCompat2.isEnabled());
paramAccessibilityNodeInfoCompat1.setClickable(paramAccessibilityNodeInfoCompat2.isClickable());
paramAccessibilityNodeInfoCompat1.setFocusable(paramAccessibilityNodeInfoCompat2.isFocusable());
paramAccessibilityNodeInfoCompat1.setFocused(paramAccessibilityNodeInfoCompat2.isFocused());
paramAccessibilityNodeInfoCompat1.setAccessibilityFocused(paramAccessibilityNodeInfoCompat2.isAccessibilityFocused());
paramAccessibilityNodeInfoCompat1.setSelected(paramAccessibilityNodeInfoCompat2.isSelected());
paramAccessibilityNodeInfoCompat1.setLongClickable(paramAccessibilityNodeInfoCompat2.isLongClickable());
paramAccessibilityNodeInfoCompat1.addAction(paramAccessibilityNodeInfoCompat2.getActions());
paramAccessibilityNodeInfoCompat1.setMovementGranularities(paramAccessibilityNodeInfoCompat2.getMovementGranularities());
}
public boolean filter(View paramView)
{
return SlidingPaneLayout.this.isDimmed(paramView);
}
public void onInitializeAccessibilityEvent(View paramView, AccessibilityEvent paramAccessibilityEvent)
{
super.onInitializeAccessibilityEvent(paramView, paramAccessibilityEvent);
paramAccessibilityEvent.setClassName(SlidingPaneLayout.class.getName());
}
public void onInitializeAccessibilityNodeInfo(View paramView, AccessibilityNodeInfoCompat paramAccessibilityNodeInfoCompat)
{
AccessibilityNodeInfoCompat localAccessibilityNodeInfoCompat = AccessibilityNodeInfoCompat.obtain(paramAccessibilityNodeInfoCompat);
super.onInitializeAccessibilityNodeInfo(paramView, localAccessibilityNodeInfoCompat);
copyNodeInfoNoChildren(paramAccessibilityNodeInfoCompat, localAccessibilityNodeInfoCompat);
localAccessibilityNodeInfoCompat.recycle();
paramAccessibilityNodeInfoCompat.setClassName(SlidingPaneLayout.class.getName());
paramAccessibilityNodeInfoCompat.setSource(paramView);
paramView = ViewCompat.getParentForAccessibility(paramView);
if ((paramView instanceof View)) {
paramAccessibilityNodeInfoCompat.setParent((View)paramView);
}
int i = SlidingPaneLayout.this.getChildCount();
for (int j = 0; j < i; j++)
{
paramView = SlidingPaneLayout.this.getChildAt(j);
if ((!filter(paramView)) && (paramView.getVisibility() == 0))
{
ViewCompat.setImportantForAccessibility(paramView, 1);
paramAccessibilityNodeInfoCompat.addChild(paramView);
}
}
}
public boolean onRequestSendAccessibilityEvent(ViewGroup paramViewGroup, View paramView, AccessibilityEvent paramAccessibilityEvent)
{
if (!filter(paramView)) {
return super.onRequestSendAccessibilityEvent(paramViewGroup, paramView, paramAccessibilityEvent);
}
return false;
}
}
private class DisableLayerRunnable
implements Runnable
{
final View mChildView;
DisableLayerRunnable(View paramView)
{
this.mChildView = paramView;
}
public void run()
{
if (this.mChildView.getParent() == SlidingPaneLayout.this)
{
this.mChildView.setLayerType(0, null);
SlidingPaneLayout.this.invalidateChildRegion(this.mChildView);
}
SlidingPaneLayout.this.mPostedRunnables.remove(this);
}
}
private class DragHelperCallback
extends ViewDragHelper.Callback
{
DragHelperCallback() {}
public int clampViewPositionHorizontal(View paramView, int paramInt1, int paramInt2)
{
paramView = (SlidingPaneLayout.LayoutParams)SlidingPaneLayout.this.mSlideableView.getLayoutParams();
int i;
if (SlidingPaneLayout.this.isLayoutRtlSupport())
{
paramInt2 = SlidingPaneLayout.this.getWidth() - (SlidingPaneLayout.this.getPaddingRight() + paramView.rightMargin + SlidingPaneLayout.this.mSlideableView.getWidth());
i = SlidingPaneLayout.this.mSlideRange;
paramInt1 = Math.max(Math.min(paramInt1, paramInt2), paramInt2 - i);
}
else
{
i = SlidingPaneLayout.this.getPaddingLeft() + paramView.leftMargin;
paramInt2 = SlidingPaneLayout.this.mSlideRange;
paramInt1 = Math.min(Math.max(paramInt1, i), paramInt2 + i);
}
return paramInt1;
}
public int clampViewPositionVertical(View paramView, int paramInt1, int paramInt2)
{
return paramView.getTop();
}
public int getViewHorizontalDragRange(View paramView)
{
return SlidingPaneLayout.this.mSlideRange;
}
public void onEdgeDragStarted(int paramInt1, int paramInt2)
{
SlidingPaneLayout.this.mDragHelper.captureChildView(SlidingPaneLayout.this.mSlideableView, paramInt2);
}
public void onViewCaptured(View paramView, int paramInt)
{
SlidingPaneLayout.this.setAllChildrenVisible();
}
public void onViewDragStateChanged(int paramInt)
{
if (SlidingPaneLayout.this.mDragHelper.getViewDragState() == 0)
{
SlidingPaneLayout localSlidingPaneLayout;
if (SlidingPaneLayout.this.mSlideOffset == 0.0F)
{
localSlidingPaneLayout = SlidingPaneLayout.this;
localSlidingPaneLayout.updateObscuredViewsVisibility(localSlidingPaneLayout.mSlideableView);
localSlidingPaneLayout = SlidingPaneLayout.this;
localSlidingPaneLayout.dispatchOnPanelClosed(localSlidingPaneLayout.mSlideableView);
SlidingPaneLayout.this.mPreservedOpenState = false;
}
else
{
localSlidingPaneLayout = SlidingPaneLayout.this;
localSlidingPaneLayout.dispatchOnPanelOpened(localSlidingPaneLayout.mSlideableView);
SlidingPaneLayout.this.mPreservedOpenState = true;
}
}
}
public void onViewPositionChanged(View paramView, int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
SlidingPaneLayout.this.onPanelDragged(paramInt1);
SlidingPaneLayout.this.invalidate();
}
public void onViewReleased(View paramView, float paramFloat1, float paramFloat2)
{
SlidingPaneLayout.LayoutParams localLayoutParams = (SlidingPaneLayout.LayoutParams)paramView.getLayoutParams();
int i;
int j;
if (SlidingPaneLayout.this.isLayoutRtlSupport())
{
i = SlidingPaneLayout.this.getPaddingRight() + localLayoutParams.rightMargin;
if (paramFloat1 >= 0.0F)
{
j = i;
if (paramFloat1 == 0.0F)
{
j = i;
if (SlidingPaneLayout.this.mSlideOffset <= 0.5F) {}
}
}
else
{
j = i + SlidingPaneLayout.this.mSlideRange;
}
i = SlidingPaneLayout.this.mSlideableView.getWidth();
j = SlidingPaneLayout.this.getWidth() - j - i;
}
else
{
j = SlidingPaneLayout.this.getPaddingLeft();
i = localLayoutParams.leftMargin + j;
if (paramFloat1 <= 0.0F)
{
j = i;
if (paramFloat1 == 0.0F)
{
j = i;
if (SlidingPaneLayout.this.mSlideOffset <= 0.5F) {}
}
}
else
{
j = i + SlidingPaneLayout.this.mSlideRange;
}
}
SlidingPaneLayout.this.mDragHelper.settleCapturedViewAt(j, paramView.getTop());
SlidingPaneLayout.this.invalidate();
}
public boolean tryCaptureView(View paramView, int paramInt)
{
if (SlidingPaneLayout.this.mIsUnableToDrag) {
return false;
}
return ((SlidingPaneLayout.LayoutParams)paramView.getLayoutParams()).slideable;
}
}
public static class LayoutParams
extends ViewGroup.MarginLayoutParams
{
private static final int[] ATTRS = { 16843137 };
Paint dimPaint;
boolean dimWhenOffset;
boolean slideable;
public float weight = 0.0F;
public LayoutParams()
{
super(-1);
}
public LayoutParams(int paramInt1, int paramInt2)
{
super(paramInt2);
}
public LayoutParams(Context paramContext, AttributeSet paramAttributeSet)
{
super(paramAttributeSet);
paramContext = paramContext.obtainStyledAttributes(paramAttributeSet, ATTRS);
this.weight = paramContext.getFloat(0, 0.0F);
paramContext.recycle();
}
public LayoutParams(LayoutParams paramLayoutParams)
{
super();
this.weight = paramLayoutParams.weight;
}
public LayoutParams(ViewGroup.LayoutParams paramLayoutParams)
{
super();
}
public LayoutParams(ViewGroup.MarginLayoutParams paramMarginLayoutParams)
{
super();
}
}
public static abstract interface PanelSlideListener
{
public abstract void onPanelClosed(View paramView);
public abstract void onPanelOpened(View paramView);
public abstract void onPanelSlide(View paramView, float paramFloat);
}
static class SavedState
extends AbsSavedState
{
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.ClassLoaderCreator()
{
public SlidingPaneLayout.SavedState createFromParcel(Parcel paramAnonymousParcel)
{
return new SlidingPaneLayout.SavedState(paramAnonymousParcel, null);
}
public SlidingPaneLayout.SavedState createFromParcel(Parcel paramAnonymousParcel, ClassLoader paramAnonymousClassLoader)
{
return new SlidingPaneLayout.SavedState(paramAnonymousParcel, null);
}
public SlidingPaneLayout.SavedState[] newArray(int paramAnonymousInt)
{
return new SlidingPaneLayout.SavedState[paramAnonymousInt];
}
};
boolean isOpen;
SavedState(Parcel paramParcel, ClassLoader paramClassLoader)
{
super(paramClassLoader);
boolean bool;
if (paramParcel.readInt() != 0) {
bool = true;
} else {
bool = false;
}
this.isOpen = bool;
}
SavedState(Parcelable paramParcelable)
{
super();
}
public void writeToParcel(Parcel paramParcel, int paramInt)
{
super.writeToParcel(paramParcel, paramInt);
paramParcel.writeInt(this.isOpen);
}
}
public static class SimplePanelSlideListener
implements SlidingPaneLayout.PanelSlideListener
{
public void onPanelClosed(View paramView) {}
public void onPanelOpened(View paramView) {}
public void onPanelSlide(View paramView, float paramFloat) {}
}
static abstract interface SlidingPanelLayoutImpl
{
public abstract void invalidateChildRegion(SlidingPaneLayout paramSlidingPaneLayout, View paramView);
}
static class SlidingPanelLayoutImplBase
implements SlidingPaneLayout.SlidingPanelLayoutImpl
{
public void invalidateChildRegion(SlidingPaneLayout paramSlidingPaneLayout, View paramView)
{
ViewCompat.postInvalidateOnAnimation(paramSlidingPaneLayout, paramView.getLeft(), paramView.getTop(), paramView.getRight(), paramView.getBottom());
}
}
static class SlidingPanelLayoutImplJB
extends SlidingPaneLayout.SlidingPanelLayoutImplBase
{
private Method mGetDisplayList;
private Field mRecreateDisplayList;
SlidingPanelLayoutImplJB()
{
try
{
this.mGetDisplayList = View.class.getDeclaredMethod("getDisplayList", (Class[])null);
}
catch (NoSuchMethodException localNoSuchMethodException)
{
Log.e("SlidingPaneLayout", "Couldn't fetch getDisplayList method; dimming won't work right.", localNoSuchMethodException);
}
try
{
this.mRecreateDisplayList = View.class.getDeclaredField("mRecreateDisplayList");
this.mRecreateDisplayList.setAccessible(true);
}
catch (NoSuchFieldException localNoSuchFieldException)
{
Log.e("SlidingPaneLayout", "Couldn't fetch mRecreateDisplayList field; dimming will be slow.", localNoSuchFieldException);
}
}
public void invalidateChildRegion(SlidingPaneLayout paramSlidingPaneLayout, View paramView)
{
if (this.mGetDisplayList != null)
{
Field localField = this.mRecreateDisplayList;
if (localField != null)
{
try
{
localField.setBoolean(paramView, true);
this.mGetDisplayList.invoke(paramView, (Object[])null);
}
catch (Exception localException)
{
Log.e("SlidingPaneLayout", "Error refreshing display list state", localException);
}
super.invalidateChildRegion(paramSlidingPaneLayout, paramView);
return;
}
}
paramView.invalidate();
}
}
static class SlidingPanelLayoutImplJBMR1
extends SlidingPaneLayout.SlidingPanelLayoutImplBase
{
public void invalidateChildRegion(SlidingPaneLayout paramSlidingPaneLayout, View paramView)
{
ViewCompat.setLayerPaint(paramView, ((SlidingPaneLayout.LayoutParams)paramView.getLayoutParams()).dimPaint);
}
}
}
/* Location: ~/android/support/v4/widget/SlidingPaneLayout.class
*
* Reversed by: J
*/
| 29.643035
| 174
| 0.626547
|
6cf6137832e025c0f8a99e7c266239963f8b09d5
| 13,641
|
/*
* This file is part of the ONT MAP.
* The contents of this file are subject to the Apache License, Version 2.0.
* Copyright (c) 2019, The University of Manchester, owl.cs group.
*
* 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.github.owlcs.map.spin;
import com.github.owlcs.map.*;
import com.github.owlcs.map.spin.system.SystemLibraries;
import com.github.owlcs.ontapi.*;
import com.github.owlcs.ontapi.jena.impl.OntGraphModelImpl;
import com.github.owlcs.ontapi.jena.model.OntModel;
import com.github.owlcs.ontapi.jena.utils.Graphs;
import org.apache.jena.graph.Graph;
import org.apache.jena.shared.PrefixMapping;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyID;
import java.util.HashMap;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
/**
* A SPIN-based implementation of {@link OWLMapManager}
* which is a {@link OntologyManager} and {@link MapManager} simultaneously.
* <p>
* Created by @ssz on 21.06.2018.
*/
@SuppressWarnings({"NullableProblems", "WeakerAccess"})
public class OWLMapManagerImpl extends OntologyManagerImpl implements OWLMapManager, HasConfig {
// todo: handle in serialization (see issue #10):
private final transient MapManagerImpl manager;
private transient Set<String> libs;
public OWLMapManagerImpl(Graph primary,
DataFactory dataFactory,
OntologyFactory ontologyFactory,
ReadWriteLock lock) {
this(primary, dataFactory, ontologyFactory, MapConfigImpl.INSTANCE, lock);
}
/**
* Creates a ready-to use {@link OWLMapManager} instance.
*
* @param primary {@link Graph} to store user-defined functions and other mapping-manager-specific stuff,
* cannot be {@code null}
* @param dataFactory {@link DataFactory} a facility to construct OWL-API objects, cannot be {@code null}
* @param ontologyFactory {@link OntologyFactory} a facility to create and load {@link Ontology} instances,
* cannot be {@code null}
* @param config {@link MapConfigImpl} a mapping manager config settings, cannot be {@code null}
* @param lock {@link ReadWriteLock} to ensure thread-safety,
* possible {@code null} for one-thread environment
*/
public OWLMapManagerImpl(Graph primary,
DataFactory dataFactory,
OntologyFactory ontologyFactory,
MapConfigImpl config,
ReadWriteLock lock) {
super(dataFactory, ontologyFactory, lock);
this.manager = createMapManager(
primary
, () -> {
throw new MapJenaException.IllegalState("Direct model creation is not allowed here.");
}
, getLock()
, config
, m -> ontology(m.getBaseGraph()).map(Ontology::asGraphModel).orElse(m));
}
/**
* Creates a concurrent version of {@link MapManagerImpl}.
* Since only {@link MapManager#asMapModel(OntModel)} can change the state of manager
* (if specified model has custom functions inside),
* and only {@link MapManager#functions()} returns that state (a list of functions),
* this two methods must be synchronized.
*
* @param primary {@link Graph} to store user-defined functions and other manager-specific stuff
* @param factory to produce fresh {@link Graph}s instances
* @param lock {@link ReadWriteLock}, not {@code null}
* @return {@link MapManager} instance with lock inside
*/
public static MapManagerImpl createMapManager(Graph primary, Supplier<Graph> factory, ReadWriteLock lock) {
return createMapManager(primary, factory, lock, MapConfigImpl.INSTANCE, UnaryOperator.identity());
}
protected static MapManagerImpl createMapManager(Graph library,
Supplier<Graph> factory,
ReadWriteLock lock,
MapConfigImpl config,
UnaryOperator<OntModel> map) {
boolean noOp = !NoOpReadWriteLock.isConcurrent(lock);
library = Graphs.asNonConcurrent(Objects.requireNonNull(library, "Null primary graph"));
if (!noOp) {
library = Graphs.asConcurrent(library, lock);
}
return new MapManagerImpl(library
, factory
, noOp ? new HashMap<>() : new ConcurrentHashMap<>()
, config) {
@Override
protected boolean filter(FunctionImpl f) {
lock.readLock().lock();
try {
return super.filter(f);
} finally {
lock.readLock().unlock();
}
}
@Override
public MapModelImpl asMapModel(OntModel m) throws MapJenaException {
lock.writeLock().lock();
try {
return super.asMapModel(m);
} finally {
lock.writeLock().unlock();
}
}
@Override
public Stream<OntModel> relatedModels(OntModel model) {
return super.relatedModels(model).map(map);
}
};
}
/**
* Post-processes for the ontology.
* This method is called after each creation or loading.
*
* @param ont {@link Ontology}
*/
@Override
public void ontologyCreated(OWLOntology ont) {
lock.writeLock().lock();
try {
OntModel g = ((Ontology) ont).asGraphModel();
if (manager.isMapModel(g)) {
// register custom functions
manager.asMapModel(g);
}
content.add(new OntInfo((Ontology) ont));
} finally {
lock.writeLock().unlock();
}
}
@Override
public Stream<OWLOntology> ontologies() {
lock.readLock().lock();
try {
return content.values().filter(x -> !isLibraryModel(x.getOntologyID())).map(OntInfo::get);
} finally {
lock.readLock().unlock();
}
}
@Override
public Stream<MapModel> mappings() {
lock.readLock().lock();
try {
return content.values()
.map(OntInfo::get)
.map(Ontology::asGraphModel)
.filter(this::isMapModel)
.map(manager::newMapModelImpl);
} finally {
lock.readLock().unlock();
}
}
@Override
public PrefixMapping prefixes() {
return manager.prefixes();
}
@Override
public Stream<MapFunction> functions() {
return manager.functions();
}
@Override
public Graph getGraph() {
lock.readLock().lock();
try {
return manager.getGraph();
} finally {
lock.readLock().unlock();
}
}
@Override
public void addGraph(Graph g) {
lock.writeLock().lock();
try {
manager.addGraph(g);
} finally {
lock.writeLock().unlock();
}
}
@Override
public MapModel createMapModel() {
lock.writeLock().lock();
try {
OntGraphModelImpl m = (OntGraphModelImpl) createGraphModel(null);
manager.setupMapModel(m);
return manager.newMapModelImpl(m);
} finally {
lock.writeLock().unlock();
}
}
@Override
public MapModel asMapModel(OntModel m) throws MapJenaException {
lock.readLock().lock();
try {
if (contains(m)) {
// already added -> no need to re-register the same functions (was handled by #ontologyCreated),
// therefore the state of the manager is not changed -> no need in write lock
return manager.newMapModelImpl(m);
}
} finally {
lock.readLock().unlock();
}
lock.writeLock().lock();
try {
// external ontology -> just registers functions and return the map-model without any lock
return manager.asMapModel(m);
} finally {
lock.writeLock().unlock();
}
}
/**
* Answers iff the model is present inside manager.
* The check is performed by comparing the base graphs not ontology ids.
*
* @param m {@link OntModel} to test
* @return boolean
* @see OntologyManager#contains(OWLOntology)
*/
public boolean contains(OntModel m) {
return ontology(m.getGraph()).isPresent();
}
@Override
public boolean isMapModel(OntModel m) {
lock.readLock().lock();
try {
return manager.isMapModel(m);
} finally {
lock.readLock().unlock();
}
}
/**
* Answers {@code true} if the given ontology id is reserved as system.
*
* @param id {@link OWLOntologyID} to test
* @return boolean
*/
public boolean isLibraryModel(OWLOntologyID id) {
lock.readLock().lock();
try {
if (libs == null)
libs = SystemLibraries.graphs().keySet();
return id.getOntologyIRI()
.map(IRI::getIRIString)
.filter(libs::contains)
.isPresent();
} finally {
lock.readLock().unlock();
}
}
@Override
public ClassPropertyMap getClassProperties(OntModel model) {
lock.readLock().lock();
try {
return manager.getClassProperties(model);
} finally {
lock.readLock().unlock();
}
}
@Override
public InferenceEngine getInferenceEngine(MapModel mapping) {
return new OWLInferenceEngineImpl(mapping);
}
@Override
public MapConfigImpl getMappingConfiguration() {
return manager.getMappingConfiguration();
}
public class OWLInferenceEngineImpl implements InferenceEngine {
protected final InferenceEngine delegate;
protected final Lock mappingLock;
public OWLInferenceEngineImpl(MapModel mapping) {
lock.readLock().lock();
try {
// Use a write lock in case the given mapping belongs to the manager,
// since inference engine may add temporary triples into the mapping main graph
this.mappingLock = ontology(Objects.requireNonNull(mapping, "Null mapping").asGraphModel().getGraph())
.isPresent() ? lock.writeLock() : NoOpReadWriteLock.NO_OP_LOCK;
this.delegate = manager.getInferenceEngine(mapping);
} finally {
lock.readLock().unlock();
}
}
/**
* Runs an inference process on the given mapping, source and target.
* Uses manager's write lock, if the target graph or the mapping belongs to the manager;
* or manager's read lock, if the the source graph belongs to the manager,
* otherwise uses no-op lock instance.
*
* @param source a graph with data to map.
* @param target a graph to write mapping results.
*/
@Override
public void run(Graph source, Graph target) {
Lock inferLock;
lock.readLock().lock();
try {
Optional<Ontology> dst = ontology(target);
// clears the cache (just in case): new axioms will be added to that ontology
dst.ifPresent(Ontology::clearCache);
if (mappingLock != NoOpReadWriteLock.NO_OP_LOCK) { // then write lock (mapping is in the manager)
inferLock = mappingLock;
} else {
if (dst.isPresent()) { // the target belongs to the manager
inferLock = lock.writeLock();
} else if (ontology(source).isPresent()) { // the source belongs to manager
inferLock = lock.readLock();
} else { // all - the mapping, the source and the target - are external to the manager
inferLock = NoOpReadWriteLock.NO_OP_LOCK;
}
}
} finally {
lock.readLock().unlock();
}
inferLock.lock();
try {
delegate.run(source, target);
} finally {
inferLock.unlock();
}
}
}
}
| 36.279255
| 118
| 0.574811
|
4c617325f3161fe38ec0b84696db39405eee66df
| 597
|
package linkedList;
import java.util.Iterator;
public class LinkedListIterator<T> implements Iterator<T>{
private LinkedList<T>.ListNode next;
public LinkedListIterator(LinkedList<T>.ListNode head){
next = head;
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public T next(){
LinkedList<T>.ListNode res = next;
if(hasNext()) next = next.getNext();
return res.getVal();
}
/**
* didn't really need to implement this method for the sake of the heap...
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
| 18.090909
| 75
| 0.695142
|
9977649b70510d7889791cebcba39c91c5bc2ffb
| 2,184
|
/*
* Copyright 2011-present Greg Shrago
*
* 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.intellij.grammar.inspection;
import com.intellij.codeInspection.InspectionManager;
import com.intellij.codeInspection.LocalInspectionTool;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.PsiFile;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.grammar.psi.BnfFile;
import org.intellij.grammar.psi.BnfRule;
import org.intellij.grammar.psi.impl.GrammarUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* Date: 8/29/11
* Time: 1:54 PM
*
* @author Vadim Romansky
*/
public class BnfDuplicateRuleInspection extends LocalInspectionTool {
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
ProblemsHolder problemsHolder = new ProblemsHolder(manager, file, isOnTheFly);
checkFile(file, problemsHolder);
return problemsHolder.getResultsArray();
}
private static void checkFile(PsiFile file, ProblemsHolder problemsHolder) {
if (!(file instanceof BnfFile)) return;
BnfFile bnfFile = (BnfFile)file;
Set<BnfRule> rules = ContainerUtil.newLinkedHashSet();
for (BnfRule r : GrammarUtil.bnfTraverser(bnfFile).filter(BnfRule.class)) {
BnfRule t = bnfFile.getRule(r.getName());
if (r != t) {
rules.add(t);
rules.add(r);
}
}
for (BnfRule rule : rules) {
problemsHolder.registerProblem(rule.getId(), "'" + rule.getName() + "' rule is defined more than once");
}
}
}
| 34.125
| 119
| 0.741758
|
ed484e71ab2356b51efcb297b0d5064d73853c46
| 9,114
|
package odata;
import java.io.InputStream;
import java.util.List;
import org.apache.olingo.odata2.api.batch.BatchHandler;
import org.apache.olingo.odata2.api.batch.BatchResponsePart;
import org.apache.olingo.odata2.api.exception.ODataException;
import org.apache.olingo.odata2.api.processor.ODataContext;
import org.apache.olingo.odata2.api.processor.ODataProcessor;
import org.apache.olingo.odata2.api.processor.ODataRequest;
import org.apache.olingo.odata2.api.processor.ODataResponse;
import org.apache.olingo.odata2.api.processor.ODataSingleProcessor;
import org.apache.olingo.odata2.api.uri.info.DeleteUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetComplexPropertyUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntityCountUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntityLinkCountUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntityLinkUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntitySetCountUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntitySetLinksCountUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntitySetLinksUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntitySetUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetEntityUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetFunctionImportUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetMediaResourceUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetMetadataUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetServiceDocumentUriInfo;
import org.apache.olingo.odata2.api.uri.info.GetSimplePropertyUriInfo;
import org.apache.olingo.odata2.api.uri.info.PostUriInfo;
import org.apache.olingo.odata2.api.uri.info.PutMergePatchUriInfo;
import ws.Endpoint;
public class ODataSingleProcessorWrapper extends ODataSingleProcessor {
private ODataSingleProcessor delegate;
public ODataSingleProcessorWrapper(ODataSingleProcessor delegate) {
this.delegate = delegate;
}
@Override
public void setContext(ODataContext context) {
delegate.setContext(context);
}
@Override
public ODataContext getContext() {
return delegate.getContext();
}
@Override
public ODataResponse executeBatch(BatchHandler handler, String contentType,
InputStream content) throws ODataException {
return onChange(delegate.executeBatch(handler, contentType, content));
}
@Override
public BatchResponsePart executeChangeSet(BatchHandler handler,
List<ODataRequest> requests) throws ODataException {
return onChange(delegate.executeChangeSet(handler, requests));
}
@Override
public ODataResponse executeFunctionImport(
GetFunctionImportUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.executeFunctionImport(uriInfo, contentType);
}
@Override
public ODataResponse executeFunctionImportValue(
GetFunctionImportUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.executeFunctionImportValue(uriInfo, contentType);
}
@Override
public ODataResponse readEntitySimplePropertyValue(
GetSimplePropertyUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.readEntitySimplePropertyValue(uriInfo, contentType);
}
@Override
public ODataResponse updateEntitySimplePropertyValue(
PutMergePatchUriInfo uriInfo, InputStream content,
String requestContentType, String contentType)
throws ODataException {
return onChange(delegate.updateEntitySimplePropertyValue(uriInfo, content,
requestContentType, contentType));
}
@Override
public ODataResponse deleteEntitySimplePropertyValue(DeleteUriInfo uriInfo,
String contentType) throws ODataException {
return onChange(delegate.deleteEntitySimplePropertyValue(uriInfo, contentType));
}
@Override
public ODataResponse readEntitySimpleProperty(
GetSimplePropertyUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.readEntitySimpleProperty(uriInfo, contentType);
}
@Override
public ODataResponse updateEntitySimpleProperty(
PutMergePatchUriInfo uriInfo, InputStream content,
String requestContentType, String contentType)
throws ODataException {
return onChange(delegate.updateEntitySimpleProperty(uriInfo, content,
requestContentType, contentType));
}
@Override
public ODataResponse readEntityMedia(GetMediaResourceUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.readEntityMedia(uriInfo, contentType);
}
@Override
public ODataResponse updateEntityMedia(PutMergePatchUriInfo uriInfo,
InputStream content, String requestContentType, String contentType)
throws ODataException {
return onChange(delegate.updateEntityMedia(uriInfo, content, requestContentType,
contentType));
}
@Override
public ODataResponse deleteEntityMedia(DeleteUriInfo uriInfo,
String contentType) throws ODataException {
return onChange(delegate.deleteEntityMedia(uriInfo, contentType));
}
@Override
public ODataResponse readEntityLinks(GetEntitySetLinksUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.readEntityLinks(uriInfo, contentType);
}
@Override
public ODataResponse countEntityLinks(
GetEntitySetLinksCountUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.countEntityLinks(uriInfo, contentType);
}
@Override
public ODataResponse createEntityLink(PostUriInfo uriInfo,
InputStream content, String requestContentType, String contentType)
throws ODataException {
return onChange(delegate.createEntityLink(uriInfo, content, requestContentType,
contentType));
}
@Override
public ODataResponse readEntityLink(GetEntityLinkUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.readEntityLink(uriInfo, contentType);
}
@Override
public ODataResponse existsEntityLink(GetEntityLinkCountUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.existsEntityLink(uriInfo, contentType);
}
@Override
public ODataResponse updateEntityLink(PutMergePatchUriInfo uriInfo,
InputStream content, String requestContentType, String contentType)
throws ODataException {
return onChange(delegate.updateEntityLink(uriInfo, content, requestContentType,
contentType));
}
@Override
public ODataResponse deleteEntityLink(DeleteUriInfo uriInfo,
String contentType) throws ODataException {
return onChange(delegate.deleteEntityLink(uriInfo, contentType));
}
@Override
public ODataResponse readEntityComplexProperty(
GetComplexPropertyUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.readEntityComplexProperty(uriInfo, contentType);
}
@Override
public ODataResponse updateEntityComplexProperty(
PutMergePatchUriInfo uriInfo, InputStream content,
String requestContentType, boolean merge, String contentType)
throws ODataException {
return onChange(delegate.updateEntityComplexProperty(uriInfo, content,
requestContentType, merge, contentType));
}
@Override
public ODataResponse readEntitySet(GetEntitySetUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.readEntitySet(uriInfo, contentType);
}
@Override
public ODataResponse countEntitySet(GetEntitySetCountUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.countEntitySet(uriInfo, contentType);
}
@Override
public ODataResponse createEntity(PostUriInfo uriInfo, InputStream content,
String requestContentType, String contentType)
throws ODataException {
return onChange(delegate.createEntity(uriInfo, content, requestContentType,
contentType));
}
@Override
public ODataResponse readEntity(GetEntityUriInfo uriInfo, String contentType)
throws ODataException {
return delegate.readEntity(uriInfo, contentType);
}
@Override
public ODataResponse existsEntity(GetEntityCountUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.existsEntity(uriInfo, contentType);
}
@Override
public ODataResponse updateEntity(PutMergePatchUriInfo uriInfo,
InputStream content, String requestContentType, boolean merge,
String contentType) throws ODataException {
return onChange(delegate.updateEntity(uriInfo, content, requestContentType,
merge, contentType));
}
@Override
public ODataResponse deleteEntity(DeleteUriInfo uriInfo, String contentType)
throws ODataException {
return onChange(delegate.deleteEntity(uriInfo, contentType));
}
@Override
public ODataResponse readServiceDocument(GetServiceDocumentUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.readServiceDocument(uriInfo, contentType);
}
@Override
public ODataResponse readMetadata(GetMetadataUriInfo uriInfo,
String contentType) throws ODataException {
return delegate.readMetadata(uriInfo, contentType);
}
@Override
public List<String> getCustomContentTypes(
Class<? extends ODataProcessor> processorFeature)
throws ODataException {
return delegate.getCustomContentTypes(processorFeature);
}
private<T> T onChange(T t) {
Endpoint.sendRefresh();
return t;
}
}
| 33.755556
| 82
| 0.81907
|
5998c15a5812f6dca762550aa65bbc38ce0ba095
| 858
|
/**
* 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.strategicbase.swe4j.phantom;
/**
* <p>
* Base class to export a html file into a raster image.
* </p>
*
* @author sboyina
*
*/
public abstract class BaseImageExporter extends PhantomExporter {
public BaseImageExporter(String typeExtension) {
super(typeExtension);
}
}
| 27.677419
| 75
| 0.729604
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.