text
stringlengths 10
2.72M
|
|---|
package ui;
import javax.swing.JOptionPane;
import db.회원DAO;
import db.회원DAO2;
import dto.회원Bag;
public class 회원정보UI2 {
public static void main(String[] args) {
String id = JOptionPane.showInputDialog("회원가입id입력");
String pw = JOptionPane.showInputDialog("회원가입pw입력");
String name = JOptionPane.showInputDialog("회원가입name입력");
String tel = JOptionPane.showInputDialog("회원가입tel입력");
회원DAO2 dao2 = new 회원DAO2();
회원Bag bag = new 회원Bag();
bag.setId(id);
bag.setPw(pw);
bag.setName(name);
bag.setTel(tel);
dao2.create(bag);
System.out.println("dao의 create()하고 연이어 실행됨");
}
}
|
package ex1databasewithjdcb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Adverage
{
static Connection connection = null;
static final String sql = "SELECT AVG(Price) FROM titles";
public static void main(String[] args)
{
//open connection
try
{
openDatabaseConnection();
doWork();
} catch (SQLException sqlex)
{
System.out.println("Comms error " + sqlex);
} finally
{
try
{
connection.close();
} catch (SQLException sqlex)
{
System.out.println("Error cleaning up " + sqlex);
}
}
}
//close connection
protected static void doWork() throws SQLException
{
Statement statement = null;
ResultSet resultSet = null;
try
{
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
String results = createHeadings(metaData, numberOfColumns);
results += CreateRowsData(resultSet, numberOfColumns);
System.out.println(results);
} catch (SQLException ex)
{
Logger.getLogger(Adverage.class.getName()).log(Level.SEVERE, null, ex);
} finally
{
if (resultSet != null)
{
resultSet.close();
}
if (statement != null)
{
statement.close();
}
}
}
protected static String CreateRowsData(ResultSet resultSet, int numberOfColumns) throws SQLException
{
String results = "";
while (resultSet.next())
{
for (int i = 1; i <= numberOfColumns; i++)
{
results += resultSet.getObject(i) + "\t\t";
}
results += System.lineSeparator();
}
return results;
}
protected static void openDatabaseConnection() throws SQLException
{
connection = DriverManager.getConnection(ProjectData.DataBaseServerURI, ProjectData.DataBaseServerUsername, ProjectData.DataBaseServerPassword);
}
private static String createHeadings(ResultSetMetaData metaData, int numberOfColumns) throws SQLException
{
String results = "";
for (int i = 1; i <= numberOfColumns; i++)
{
results += metaData.getColumnName(i) + "\t";
}
results += "\n";
return results;
}
}
|
/* *****************************************************************************
* Name: Alan Turing
* Coursera User ID: 123456
* Last modified: 1/1/2019
**************************************************************************** */
public class TrinomialDP {
public static long trinomial(int n, int k) {
if (n == 0 && k == 0) return 1;
if (n < -k || k > n) return 0;
long[][] a = new long[n + 1][2 * n + 2];
a[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < (2 * i + 1); j++) {
int k1 = j;
while (k1 >= 0 && j - k1 < 3) {
a[i][j] += a[i - 1][k1];
k1 = k1 - 1;
}
}
}
return a[n][n + k];
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
long a = trinomial(n, k);
System.out.println(a);
}
}
|
//----------------------------------------
//------------Акселерометр----------------
//----------------------------------------
//Файл main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>
</RelativeLayout>
//Файл MainActivity.java:
package ru.startandroid.develop.p1372acceleration;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvText;
SensorManager sensorManager;
Sensor sensorAccel;
Sensor sensorLinAccel;
Sensor sensorGravity;
StringBuilder sb = new StringBuilder();
Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText = (TextView) findViewById(R.id.tvText);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorAccel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorLinAccel = sensorManager
.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorGravity = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(listener, sensorAccel,
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorLinAccel,
SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorGravity,
SensorManager.SENSOR_DELAY_NORMAL);
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
showInfo();
}
});
}
};
timer.schedule(task, 0, 400);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(listener);
timer.cancel();
}
String format(float values[]) {
return String.format("%1$.1f\t\t%2$.1f\t\t%3$.1f", values[0], values[1],
values[2]);
}
void showInfo() {
sb.setLength(0);
sb.append("Accelerometer: " + format(valuesAccel))
.append("\n\nAccel motion: " + format(valuesAccelMotion))
.append("\nAccel gravity : " + format(valuesAccelGravity))
.append("\n\nLin accel : " + format(valuesLinAccel))
.append("\nGravity : " + format(valuesGravity));
tvText.setText(sb);
}
float[] valuesAccel = new float[3];
float[] valuesAccelMotion = new float[3];
float[] valuesAccelGravity = new float[3];
float[] valuesLinAccel = new float[3];
float[] valuesGravity = new float[3];
SensorEventListener listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
for (int i = 0; i < 3; i++) {
valuesAccel[i] = event.values[i];
valuesAccelGravity[i] = (float) (0.1 * event.values[i] + 0.9 * valuesAccelGravity[i]);
valuesAccelMotion[i] = event.values[i]
- valuesAccelGravity[i];
}
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
for (int i = 0; i < 3; i++) {
valuesLinAccel[i] = event.values[i];
}
break;
case Sensor.TYPE_GRAVITY:
for (int i = 0; i < 3; i++) {
valuesGravity[i] = event.values[i];
}
break;
}
}
};
}
//----------------------------------------
//------------Ориентация------------------
//----------------------------------------
//Файл mail.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tvText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge">
</TextView>
</RelativeLayout>
//Файл MainActivity.java:
package ru.startandroid.develop.p1373orientation;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvText;
SensorManager sensorManager;
Sensor sensorAccel;
Sensor sensorMagnet;
StringBuilder sb = new StringBuilder();
Timer timer;
int rotation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText = (TextView) findViewById(R.id.tvText);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorAccel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorMagnet = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(listener, sensorAccel, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(listener, sensorMagnet, SensorManager.SENSOR_DELAY_NORMAL);
timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
getDeviceOrientation();
getActualDeviceOrientation();
showInfo();
}
});
}
};
timer.schedule(task, 0, 400);
WindowManager windowManager = ((WindowManager) getSystemService(Context.WINDOW_SERVICE));
Display display = windowManager.getDefaultDisplay();
rotation = display.getRotation();
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(listener);
timer.cancel();
}
String format(float values[]) {
return String.format("%1$.1f\t\t%2$.1f\t\t%3$.1f", values[0], values[1], values[2]);
}
void showInfo() {
sb.setLength(0);
sb.append("Orientation : " + format(valuesResult))
.append("\nOrientation 2: " + format(valuesResult2))
;
tvText.setText(sb);
}
float[] r = new float[9];
void getDeviceOrientation() {
SensorManager.getRotationMatrix(r, null, valuesAccel, valuesMagnet);
SensorManager.getOrientation(r, valuesResult);
valuesResult[0] = (float) Math.toDegrees(valuesResult[0]);
valuesResult[1] = (float) Math.toDegrees(valuesResult[1]);
valuesResult[2] = (float) Math.toDegrees(valuesResult[2]);
return;
}
float[] inR = new float[9];
float[] outR = new float[9];
void getActualDeviceOrientation() {
SensorManager.getRotationMatrix(inR, null, valuesAccel, valuesMagnet);
int x_axis = SensorManager.AXIS_X;
int y_axis = SensorManager.AXIS_Y;
switch (rotation) {
case (Surface.ROTATION_0): break;
case (Surface.ROTATION_90):
x_axis = SensorManager.AXIS_Y;
y_axis = SensorManager.AXIS_MINUS_X;
break;
case (Surface.ROTATION_180):
y_axis = SensorManager.AXIS_MINUS_Y;
break;
case (Surface.ROTATION_270):
x_axis = SensorManager.AXIS_MINUS_Y;
y_axis = SensorManager.AXIS_X;
break;
default: break;
}
SensorManager.remapCoordinateSystem(inR, x_axis, y_axis, outR);
SensorManager.getOrientation(outR, valuesResult2);
valuesResult2[0] = (float) Math.toDegrees(valuesResult2[0]);
valuesResult2[1] = (float) Math.toDegrees(valuesResult2[1]);
valuesResult2[2] = (float) Math.toDegrees(valuesResult2[2]);
return;
}
float[] valuesAccel = new float[3];
float[] valuesMagnet = new float[3];
float[] valuesResult = new float[3];
float[] valuesResult2 = new float[3];
SensorEventListener listener = new SensorEventListener() {
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
for (int i=0; i < 3; i++){
valuesAccel[i] = event.values[i];
}
break;
case Sensor.TYPE_MAGNETIC_FIELD:
for (int i=0; i < 3; i++){
valuesMagnet[i] = event.values[i];
}
break;
}
}
};
}
//----------------------------------------
//------------Камера----------------------
//----------------------------------------
//Добавить в файл strings.xml:
<string name="photo">Photo</string>
<string name="video">Video</string>
//Файл main.xml:
//На экране только кнопки для получения фото и видео, и ImageView, в котором будем отображать полученное фото.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btnPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickPhoto"
android:text="@string/photo">
</Button>
<Button
android:id="@+id/btnVideo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnPhoto"
android:onClick="onClickVideo"
android:text="@string/video">
</Button>
<ImageView
android:id="@+id/ivPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnVideo">
</ImageView>
</RelativeLayout>
//Файл MainActivity.java:
package ru.startandroid.develop.p1311cameraintent;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
File directory;
final int TYPE_PHOTO = 1;
final int TYPE_VIDEO = 2;
final int REQUEST_CODE_PHOTO = 1;
final int REQUEST_CODE_VIDEO = 2;
final String TAG = "myLogs";
ImageView ivPhoto;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createDirectory();
ivPhoto = (ImageView) findViewById(R.id.ivPhoto);
}
public void onClickPhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, generateFileUri(TYPE_PHOTO));
startActivityForResult(intent, REQUEST_CODE_PHOTO);
}
public void onClickVideo(View view) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, generateFileUri(TYPE_VIDEO));
startActivityForResult(intent, REQUEST_CODE_VIDEO);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == REQUEST_CODE_PHOTO) {
if (resultCode == RESULT_OK) {
if (intent == null) {
Log.d(TAG, "Intent is null");
} else {
Log.d(TAG, "Photo uri: " + intent.getData());
Bundle bndl = intent.getExtras();
if (bndl != null) {
Object obj = intent.getExtras().get("data");
if (obj instanceof Bitmap) {
Bitmap bitmap = (Bitmap) obj;
Log.d(TAG, "bitmap " + bitmap.getWidth() + " x "
+ bitmap.getHeight());
ivPhoto.setImageBitmap(bitmap);
}
}
}
} else if (resultCode == RESULT_CANCELED) {
Log.d(TAG, "Canceled");
}
}
if (requestCode == REQUEST_CODE_VIDEO) {
if (resultCode == RESULT_OK) {
if (intent == null) {
Log.d(TAG, "Intent is null");
} else {
Log.d(TAG, "Video uri: " + intent.getData());
}
} else if (resultCode == RESULT_CANCELED) {
Log.d(TAG, "Canceled");
}
}
}
private Uri generateFileUri(int type) {
File file = null;
switch (type) {
case TYPE_PHOTO:
file = new File(directory.getPath() + "/" + "photo_"
+ System.currentTimeMillis() + ".jpg");
break;
case TYPE_VIDEO:
file = new File(directory.getPath() + "/" + "video_"
+ System.currentTimeMillis() + ".mp4");
break;
}
Log.d(TAG, "fileName = " + file);
return Uri.fromFile(file);
}
private void createDirectory() {
directory = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyFolder");
if (!directory.exists())
directory.mkdirs();
}
}
//Дописать в манифест
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> - право на запись на SD карту
<uses-feature android:name="android.hardware.camera" /> - ваше приложение в маркете будет видно только устройствам с камерой
//----------------------------------------
//-----Обработка поворота камеры----------
//----------------------------------------
//Файл main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/surfaceView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center">
</SurfaceView>
</FrameLayout>
//SurfaceView по центру экрана.
//В манифест добавьте права на камеру: <uses-permission an-droid:name="android.permission.CAMERA"/>
//Файл MainActivity.java:
package ru.startandroid.develop.p1321camerascreen;
import java.io.IOException;
import android.app.Activity;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.os.Bundle;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
public class MainActivity extends Activity {
SurfaceView sv;
SurfaceHolder holder;
HolderCallback holderCallback;
Camera camera;
final int CAMERA_ID = 0;
final boolean FULL_SCREEN = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
sv = (SurfaceView) findViewById(R.id.surfaceView);
holder = sv.getHolder();
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holderCallback = new HolderCallback();
holder.addCallback(holderCallback);
}
@Override
protected void onResume() {
super.onResume();
camera = Camera.open(CAMERA_ID);
setPreviewSize(FULL_SCREEN);
}
@Override
protected void onPause() {
super.onPause();
if (camera != null)
camera.release();
camera = null;
}
class HolderCallback implements SurfaceHolder.Callback {
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
camera.stopPreview();
setCameraDisplayOrientation(CAMERA_ID);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}
void setPreviewSize(boolean fullScreen) {
// получаем размеры экрана
Display display = getWindowManager().getDefaultDisplay();
boolean widthIsMax = display.getWidth() > display.getHeight();
// определяем размеры превью камеры
Size size = camera.getParameters().getPreviewSize();
RectF rectDisplay = new RectF();
RectF rectPreview = new RectF();
// RectF экрана, соотвествует размерам экрана
rectDisplay.set(0, 0, display.getWidth(), display.getHeight());
// RectF первью
if (widthIsMax) {
// превью в горизонтальной ориентации
rectPreview.set(0, 0, size.width, size.height);
} else {
// превью в вертикальной ориентации
rectPreview.set(0, 0, size.height, size.width);
}
Matrix matrix = new Matrix();
// подготовка матрицы преобразования
if (!fullScreen) {
// если превью будет "втиснут" в экран
matrix.setRectToRect(rectPreview, rectDisplay,
Matrix.ScaleToFit.START);
} else {
// если экран будет "втиснут" в превью
matrix.setRectToRect(rectDisplay, rectPreview,
Matrix.ScaleToFit.START);
matrix.invert(matrix);
}
// преобразование
matrix.mapRect(rectPreview);
// установка размеров surface из получившегося преобразования
sv.getLayoutParams().height = (int) (rectPreview.bottom);
sv.getLayoutParams().width = (int) (rectPreview.right);
}
void setCameraDisplayOrientation(int cameraId) {
// определяем насколько повернут экран от нормального положения
int rotation = getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result = 0;
// получаем инфо по камере cameraId
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(cameraId, info);
// задняя камера
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
result = ((360 - degrees) + info.orientation);
} else
// передняя камера
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
result = ((360 - degrees) - info.orientation);
result += 360;
}
result = result % 360;
camera.setDisplayOrientation(result);
}
}
//----------------------------------------
//------------GPS и Network---------------
//----------------------------------------
//Дописать в strings.xml:
<string name="provider_gps">GPS</string>
<string name="provider_network">Network</string>
<string name="location_settings">Location settings</string>
//Файл main.xml:
//Несколько TextView, в которые мы будем выводить данные, и кнопка для открытия настроек местоположения.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="@+id/tvTitleGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/provider_gps"
android:textSize="30sp">
</TextView>
<TextView
android:id="@+id/tvEnabledGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvStatusGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvLocationGPS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvTitleNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="@string/provider_network"
android:textSize="30sp">
</TextView>
<TextView
android:id="@+id/tvEnabledNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvStatusNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<TextView
android:id="@+id/tvLocationNet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp">
</TextView>
<Button
android:id="@+id/btnLocationSettings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="onClickLocationSettings"
android:text="@string/location_settings">
</Button>
</LinearLayout>
//Файл MainActivity.java:
package ru.startandroid.develop.p1381location;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvEnabledGPS;
TextView tvStatusGPS;
TextView tvLocationGPS;
TextView tvEnabledNet;
TextView tvStatusNet;
TextView tvLocationNet;
private LocationManager locationManager;
StringBuilder sbGPS = new StringBuilder();
StringBuilder sbNet = new StringBuilder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvEnabledGPS = (TextView) findViewById(R.id.tvEnabledGPS);
tvStatusGPS = (TextView) findViewById(R.id.tvStatusGPS);
tvLocationGPS = (TextView) findViewById(R.id.tvLocationGPS);
tvEnabledNet = (TextView) findViewById(R.id.tvEnabledNet);
tvStatusNet = (TextView) findViewById(R.id.tvStatusNet);
tvLocationNet = (TextView) findViewById(R.id.tvLocationNet);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
1000 * 10, 10, locationListener);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1000 * 10, 10,
locationListener);
checkEnabled();
}
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
showLocation(location);
}
@Override
public void onProviderDisabled(String provider) {
checkEnabled();
}
@Override
public void onProviderEnabled(String provider) {
checkEnabled();
showLocation(locationManager.getLastKnownLocation(provider));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if (provider.equals(LocationManager.GPS_PROVIDER)) {
tvStatusGPS.setText("Status: " + String.valueOf(status));
} else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
tvStatusNet.setText("Status: " + String.valueOf(status));
}
}
};
private void showLocation(Location location) {
if (location == null)
return;
if (location.getProvider().equals(LocationManager.GPS_PROVIDER)) {
tvLocationGPS.setText(formatLocation(location));
} else if (location.getProvider().equals(
LocationManager.NETWORK_PROVIDER)) {
tvLocationNet.setText(formatLocation(location));
}
}
private String formatLocation(Location location) {
if (location == null)
return "";
return String.format(
"Coordinates: lat = %1$.4f, lon = %2$.4f, time = %3$tF %3$tT",
location.getLatitude(), location.getLongitude(), new Date(
location.getTime()));
}
private void checkEnabled() {
tvEnabledGPS.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER));
tvEnabledNet.setText("Enabled: "
+ locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER));
}
public void onClickLocationSettings(View view) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
};
}
//----------------------------------------
//------------Google Maps-----------------
//----------------------------------------
//В манифесте необходимо добавить следующее в тег application:
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyComUhEqr9BL4JjqJE05Lck4j1uABIU08Y">
</meta-data>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version">
</meta-data>
//Первые данные, это наш ключ из гугл-консоли. Здесь вам надо в android:value поставить ваше значение API key. Этот ключ нужен, чтобы карта работала.
//Вторые данные – это версия Google Play services.
//Также, в манифесте в тег manifest нам надо добавить следующие разрешения:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission an-droid:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission an-droid:name="com.google.android.providers.gsf.permission.READ_GSERVICES"></uses-permission>
//Это доступ в интернет, проверка доступности инета, сохранение кэша карт и доступ к гугл-веб-сервисам.
//Если думаете работать с определением местоположения, то не забывайте про:
<uses-permission an-droid:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
//И туда же, в тег manifest такое требование:
<uses-feature
android:glEsVersion="0x00020000"
android:required="true">
</uses-feature>
//Гугл-карты используют OpenGL ES версии 2. На девайсах, которые это не поддержи-вают, карта просто не отобразится. Поэтому ставим ограничение.
//Теперь все. Далее продолжаем работу, как с обычным проектом.
//В strings.xml добавим строку:
<string name="test">Test</string>
//Файл main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnTest"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickTest"
android:text="@string/test">
</Button>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
//Кнопка и фрагмент-карта
//Файл MainActivity.java:
package ru.startandroid.develop.p1391googlemaps;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public class MainActivity extends FragmentActivity {
SupportMapFragment mapFragment;
GoogleMap map;
final String TAG = "myLogs";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = mapFragment.getMap();
if (map == null) {
finish();
return;
}
init();
}
private void init() {
}
public void onClickTest(View view) {
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
}
|
package soft.chess.domain;
import java.util.Set;
import soft.chess.common.BaseEntity;
//不与数据库发生关系,不需要持久化,服务器重启后刷新
public class RoomBean{
private long roomid;
private String title;
private long createtime;
private Player creater;
private Player joiner;
//用于统计房间内的人数
private int num=1;
//房间状态,0:等待中,1:游戏中
private byte roomState=0;
//房间游戏类型,0:五子棋
private byte gameType=0;
//先手后手
private Player blackPlayer;
private Player whitePlayer;
//比赛结果
private GameRecord record;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getCreatetime() {
return createtime;
}
public void setCreatetime(long createtime) {
this.createtime = createtime;
}
public Player getCreater() {
return creater;
}
public void setCreater(Player creater) {
this.creater = creater;
}
public Player getJoiner() {
return joiner;
}
public void setJoiner(Player joiner) {
this.joiner = joiner;
}
public byte getRoomState() {
return roomState;
}
public void setRoomState(byte roomState) {
this.roomState = roomState;
}
public byte getGameType() {
return gameType;
}
public void setGameType(byte gameType) {
this.gameType = gameType;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public long getRoomid() {
return roomid;
}
public void setRoomid(long roomid) {
this.roomid = roomid;
}
public Player getBlackPlayer() {
return blackPlayer;
}
public void setBlackPlayer(Player blackPlayer) {
this.blackPlayer = blackPlayer;
}
public Player getWhitePlayer() {
return whitePlayer;
}
public void setWhitePlayer(Player whitePlayer) {
this.whitePlayer = whitePlayer;
}
public GameRecord getRecord() {
return record;
}
public void setRecord(GameRecord record) {
this.record = record;
}
}
|
package actions;
import util.Cell;
import util.Grid;
public class Nothing extends Action {
@Override
public void execute(Cell cell, Grid grid) {
}
}
|
package cn.hrmzone.main;
import cn.hrmzone.util.OCRClient;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
/**
* @Author:张生
* @Blog:http://hrmnzone.cn
* @Organization:荆州青年教育平台(https://jzyouth.com),专注职业资格培训、学历提升
* @Description:
* @Date:19-1-11
*/
public class SinglePage {
// 设置APPID/AK/SK
public static final String APP_ID = "15356254";
public static final String API_KEY = "BqYACe5k8Xw73QrO9f3RKXXY";
public static final String SECRET_KEY = "o2iS5GTF53FbLnOoZiGKAXVBivGQHwu9";
public static void main(String args[]) {
// 初始化一个AipOcr
AipOcr client=new AipOcr(APP_ID,API_KEY,SECRET_KEY);
// 可选:设置网络连接参数
client.setConnectionTimeoutInMillis(2000);
client.setSocketTimeoutInMillis(60000);
// 需要进行识别的图片
String path = "imgs/1.jpg";
// 传入可选参数调用接口
// language_type:识别的语言类型,可设置文中英文
// detect_direction:是否检测图片的方向
// detect_language:检测识别的语言
// probability:检测识别的语言
HashMap<String,String> options=new HashMap<String,String>();
options.put("language_type", "CHN_ENG");
options.put("detect_direction", "true");
// options.put("detect_language", "true");
// options.put("probability", "true");
// 调用接口
JSONObject res = client.basicGeneral(path, options);
// JSONObject res=client.basicAccurateGeneral(path,options);
// System.out.println(res.toString(2));
System.out.println("===========json content=================");
/*
解析调用结果
1、res返回值是一个JSON,使用JSON工具进行解析;
2、根据百度的返回值定义,内容是一个word_result的JSON数组jsonaray;
3、根据数组长度,取得数组中的每一个对象,并根据key:words取得相应的内容。
*/
JSONArray words_result=res.getJSONArray("words_result");
int length=words_result.length();
for(int i=0;i<length;i++) {
JSONObject obj=words_result.getJSONObject(i);
System.out.println(obj.get("words"));
}
}
}
|
package com.example.android.roomwithmoreentitiesapp.database;
import android.arch.lifecycle.LiveData;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Query;
import com.example.android.roomwithmoreentitiesapp.model.Iphone;
import java.util.List;
@Dao
public interface IphoneDao extends BaseDao<Iphone> {
@Query("select * from iphone")
LiveData<List<Iphone>> getAllIphones();
@Query("delete from iphone")
void deleteAllIphones();
}
|
package com.bonc.upms.controller;
import com.bonc.upms.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Title: vms
* @Package: com.bonc.upms.controller
* @Description: 用户表 前端控制器
* @Author: dreamcc
* @Date: 2020/1/4 19:19
* @Version: V1.0
*/
@RestController
@RequestMapping("/upms/sys-user")
public class SysUserController {
@Autowired
private ISysUserService sysUserService;
}
|
import javafx.scene.paint.Color;
public class VerticalGamePiece extends GamePiece {
public VerticalGamePiece(int h, Color c, int x, int y) {
super(1, h, c, x, y);
}
public boolean canMoveDownIn(GameBoard b) {
// REPLACE THE CODE BELOW WITH YOUR OWN CODE
boolean checker = true;
if(this.topLeftY+this.height==6)//wall
checker=false;
if(this.topLeftY+this.height<6){//not hitting bottom wall
for (int i = 0; i < b.getNumGamePieces(); i++) {// go through game pieces
if(this.topLeftY< b.getGamePieces()[i].topLeftY){//only checking pieces on bottom of this.
if(this.topLeftY+this.height==b.getGamePieces()[i].topLeftY){//checking if y-axis line up
if(this.topLeftX>=b.getGamePieces()[i].topLeftX){
if(b.getGamePieces()[i].topLeftX+ b.getGamePieces()[i].width>this.topLeftX){
checker=false;//then cant move
break;
}
}
}
}
}
}return checker;
}
public boolean canMoveUpIn(GameBoard b) {
// REPLACE THE CODE BELOW WITH YOUR OWN CODE
boolean checker = true;
if(this.topLeftY==0) //wall
checker = false;
if(this.topLeftY>0){//not hitting top wall
for (int i = 0; i < b.getNumGamePieces(); i++) {//go through game pieces
if(b.getGamePieces()[i].topLeftY< this.topLeftY){//only checking pieces on above of this.
if(b.getGamePieces()[i].topLeftY + b.getGamePieces()[i].height == this.topLeftY){//checking if y-axis line up
if(this.topLeftX>=b.getGamePieces()[i].topLeftX){
if(b.getGamePieces()[i].topLeftX+ b.getGamePieces()[i].width>this.topLeftX){//checking if x blocks
checker=false;//then cant move
break;
}
}
}
}
}
}return checker;
}
}
|
/* Copyright (c) 2007-2017 MIT 6.005 course staff, all rights reserved.
* Redistribution of original or derived work requires permission of course staff.
*/
package minesweeper;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* TODO: Specification
*/
public class Board {
public final String BOOM_MESSAGE = "BOOM!";
// TODO: Abstraction function, rep invariant, rep exposure, thread safety
// TODO: Specify, test, and implement in problem 2
private final Square[][] board;
private final int rows;
private final int cols;
private final double BOMB_PERCENTAGE = 0.10;
private class Coordinate {
public int col;
public int row;
public Coordinate(int col, int row) {
this.col = col;
this.row = row;
}
}
public Board(int x, int y) {
rows = x;
cols = y;
board = new Square[rows][cols];
for(int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
boolean hasBomb = Math.random() < BOMB_PERCENTAGE;
board[row][col] = new Untouched(hasBomb);
}
}
for(int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
List<Coordinate> neighbors = getNeighbors(col, row);
int bombsInNeighbors = 0;
for (Coordinate c : neighbors) {
if (board[c.row][c.col].hasBomb()) bombsInNeighbors++;
}
board[row][col].setCount(bombsInNeighbors);
}
}
}
public Board(BufferedReader in) throws IOException{
String[] firstLine = in.readLine().split(" ");
cols = Integer.parseInt(firstLine[0]);
rows = Integer.parseInt(firstLine[1]);
board = new Square[rows][cols];
int row = 0;
while (in.ready()) {
String[] line = in.readLine().split(" ");
int col = 0;
for (String v : line) {
boolean hasBomb = (v.equals("1")) ? true : false;
board[row][col] = new Untouched(hasBomb);
col++;
}
row++;
}
for(row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
List<Coordinate> neighbors = getNeighbors(col, row);
int bombsInNeighbors = 0;
for (Coordinate c : neighbors) {
if (board[c.row][c.col].hasBomb()) bombsInNeighbors++;
}
board[row][col].setCount(bombsInNeighbors);
}
}
}
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
synchronized public String dig(int col, int row) {
String message = null;
if (checkCoordinates(col, row)) {
Square sq = board[row][col];
if (sq.isUntouched()) {
int oldCount = sq.getCount();
board[row][col] = new Dug();
board[row][col].setCount(oldCount);
if (sq.hasBomb()) {
message = BOOM_MESSAGE;
List<Coordinate> neighbors = getNeighbors(col, row);
for (Coordinate c : neighbors) {
board[c.row][c.col].decrementCount();
}
}
// always check after a boom. If debug, that's the thing to do.
// If not, the boom message disconnects, so no harm's done.
checkAndDigNeighbors(col, row);
}
}
message = message == null ? this.toString() : message;
return message;
}
synchronized public String flag(int col, int row) {
if (checkCoordinates(col, row)) {
Square sq = board[row][col];
if (sq.isUntouched()) board[row][col] = sq.flag();
}
return this.toString();
}
synchronized public String deflag(int col, int row) {
if (checkCoordinates(col, row)) {
Square sq = board[row][col];
if (sq.isFlagged()) board[row][col] = sq.deflag();
}
return this.toString();
}
synchronized private void checkAndDigNeighbors(int col, int row) {
List<Coordinate> neighbors = getNeighbors(col, row);
List<Coordinate> toCheck = new ArrayList<Coordinate>();
boolean noBombsInNeighbors = true;
for (Coordinate c : neighbors) {
Square sq = board[c.row][c.col];
if (sq.hasBomb()) {
noBombsInNeighbors = false;
break;
}
else if (sq.isUntouched() && !sq.isDug()) {
toCheck.add(c);
}
}
if (noBombsInNeighbors) {
for (Coordinate c : toCheck) {
int oldCount = board[c.row][c.col].getCount();
board[c.row][c.col] = new Dug();
board[c.row][c.col].setCount(oldCount);
checkAndDigNeighbors(c.col, c.row);
}
}
}
private List<Coordinate> getNeighbors(int col, int row) {
List<Coordinate> n = new ArrayList<Coordinate>();
int prevRow = row - 1;
int nextRow = row + 1;
int prevCol = col - 1;
int nextCol = col + 1;
if (checkCoordinates(prevCol, prevRow)) n.add(new Coordinate(prevCol, prevRow)); // TOP LEFT
if (checkCoordinates(col, prevRow)) n.add(new Coordinate(col, prevRow)); // TOP MIDDLE
if (checkCoordinates(nextCol, prevRow)) n.add(new Coordinate(nextCol, prevRow)); // TOP RIGHT
if (checkCoordinates(prevCol, row)) n.add(new Coordinate(prevCol, row)); // MIDDLE LEFT
if (checkCoordinates(nextCol, row)) n.add(new Coordinate(nextCol, row)); // MIDDLE RIGHT
if (checkCoordinates(prevCol, nextRow)) n.add(new Coordinate(prevCol, nextRow)); // BOTTOM LEFT
if (checkCoordinates(col, nextRow)) n.add(new Coordinate(col, nextRow)); // BOTTOM MIDDLE
if (checkCoordinates(nextCol, nextRow)) n.add(new Coordinate(nextCol, nextRow)); // BOTTOM RIGHT
return n;
}
public void boom(int col, int row) {
System.out.println(String.format("boom at row: %d, col: %d\n", row, col));
}
private boolean checkCoordinates(int col, int row) {
return col >= 0 && row >= 0 && row < rows && col < cols;
}
@Override
synchronized public String toString() {
String result = "";
for(int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
Square sq = board[row][col];
String strSq = sq.toString();
result += (col == 0) ? strSq : String.format(" %s", strSq);
}
if (row < rows -1 )result += '\n';
}
return result;
}
}
|
package mmazurkiewicz.springframework;
import mmazurkiewicz.springframework.controllers.ConstructorInjectedController;
import mmazurkiewicz.springframework.controllers.MyController;
import mmazurkiewicz.springframework.controllers.PropertyInjectedController;
import mmazurkiewicz.springframework.controllers.SetterInjectedController;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
//@ComponentScan(basePackages = {"mmazurkiewicz.springframework.services", "mmazurkiewicz.springframework"})
public class DiDemoApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(DiDemoApplication.class, args);
MyController controller = (MyController) ctx.getBean("myController");
System.out.println(controller.hello());
System.out.println(ctx.getBean(PropertyInjectedController.class).sayHello());
System.out.println(ctx.getBean(SetterInjectedController.class).sayHello());
System.out.println(ctx.getBean(ConstructorInjectedController.class).sayHello());
}
}
|
package controller.datamapper;
import controller.dtos.AfspeellijstDTO;
import controller.dtos.TrackDTO;
import domain.Afspeellijst;
import domain.Lied;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class AfspeellijstDTODataMapperTest {
private static final int ID = 1;
private AfspeellijstDTODataMapper afspeellijstDTODataMapperUnderTest;
private TrackDTODataMapper mockedTrackDTODataMapper;
@BeforeEach
void setUp() {
afspeellijstDTODataMapperUnderTest = new AfspeellijstDTODataMapper();
this.mockedTrackDTODataMapper = mock(TrackDTODataMapper.class);
this.afspeellijstDTODataMapperUnderTest.setTrackDTODataMapper(mockedTrackDTODataMapper);
}
@Test
void testMapToDomain() {
// Arrange
var afspeellijstDTO = new AfspeellijstDTO();
afspeellijstDTO.setId(ID);
afspeellijstDTO.setName("name");
afspeellijstDTO.setOwner(false);
var trackDTO = new TrackDTO();
var track = new Lied(ID, "a", 2,true, "a", "a");
afspeellijstDTO.setTracks(Arrays.asList(trackDTO));
when(mockedTrackDTODataMapper.mapToDomain(trackDTO)).thenReturn(track);
// Act
Afspeellijst actual = afspeellijstDTODataMapperUnderTest.mapToDomain(afspeellijstDTO);
// Assert
assertEquals(actual.getNaam(), afspeellijstDTO.getName());
assertEquals(actual.getId(), afspeellijstDTO.getId());
assertEquals(actual.getEigenaar(), null);
assertEquals(actual.getTracks().get(0),track);
}
@Test
void testMapToDTO() {
// Arrange
var afspeellijst = new Afspeellijst();
afspeellijst.setId(ID);
afspeellijst.setNaam("name");
afspeellijst.setEigenaar("gebruiker0");
var track = new Lied(ID, "a", 2,true, "a", "a");
var trackDTO = new TrackDTO();
afspeellijst.setTracks(Arrays.asList(track));
when(mockedTrackDTODataMapper.mapToDTO(track)).thenReturn(trackDTO);
// Act
AfspeellijstDTO actual = afspeellijstDTODataMapperUnderTest.mapToDTO(afspeellijst);
// Assert
assertEquals(actual.getName(), afspeellijst.getNaam());
assertEquals(actual.getId(), afspeellijst.getId());
assertEquals(actual.getOwner(), true);
assertEquals(actual.getTracks().get(0),trackDTO);
}
}
|
package ga.islandcrawl.action;
import ga.islandcrawl.action.Face;
import ga.islandcrawl.action.MoveAction;
import ga.islandcrawl.building.Constructor;
import ga.islandcrawl.map.O;
import ga.islandcrawl.map.Observer;
import ga.islandcrawl.object.unit.Unit;
/**
* Created by Ga on 9/7/2015.
*/
public class Build extends MoveAction {
private Face face;
public Build() {
super();
face = new Face();
animation = 2;
}
@Override
public void init(Unit host){
super.init(host);
face.init(host);
}
@Override
public boolean perform(O target){
if (inInteractRange(target)) { //range
if (getAdvTarget(target) instanceof Constructor) {
if (((Constructor) target.occupant).build()){
face.perform(target);
host.stop();
}
Observer.overlay.nextMinute();
frame++;
return true;
}
}
return false;
}
}
|
package com.shangcai.action.customer.material;
import java.io.IOException;
public interface IDesignAction {
/**
* 发布作品-模板
*/
public void publish() throws IOException;
}
|
package cn.edu.hebtu.software.sharemate.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import cn.edu.hebtu.software.sharemate.Adapter.LetterListAdapter;
import cn.edu.hebtu.software.sharemate.Bean.LetterBean;
import cn.edu.hebtu.software.sharemate.Bean.UserBean;
import cn.edu.hebtu.software.sharemate.R;
public class LetterActivity extends AppCompatActivity {
private List<LetterBean> letters = new ArrayList<>();
private ListView listView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_letter);
//准备数据源
UserBean user1 = new UserBean("白敬亭",R.drawable.baijingting);
UserBean user2 = new UserBean("王鸥",R.drawable.wangou);
UserBean user3 = new UserBean("你的小可爱",R.drawable.mengfeifei);
UserBean user4 = new UserBean("plly",R.drawable.sunliying);
//将字符串格式化为日期
Date date1 = new Date();
Date date2 = new Date();
Date date3= new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
date1 = format.parse("2018-12-2");
date2 = format.parse("2018-10-5");
date3 = format.parse("2018-9-30");
} catch (ParseException e) {
e.printStackTrace();
}
letters.add(new LetterBean(user1,"那明天我们一起去吃火锅!",date1));
letters.add(new LetterBean(user2,"说定了呀",date1));
letters.add(new LetterBean(user3,"你是魔鬼么做个人不好么?",date2));
letters.add(new LetterBean(user4,"天哪!时间过的也太快了吧!已经开学了!",date3));
//绑定适配器
listView = findViewById(R.id.lv_contact);
LetterListAdapter adapter = new LetterListAdapter(this,R.layout.letter_list_item_layout,letters);
listView.setAdapter(adapter);
//为每一个子项绑定上点击事件
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(LetterActivity.this,ChatActivity.class);
intent.putExtra("user",letters.get(position).getUser());
startActivity(intent);
}
});
//为返回按钮绑定事件
Button back = findViewById(R.id.btn_back);
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
package com.incuube.bot.util;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.log4j.Log4j2;
import java.io.IOException;
import java.util.Optional;
@Log4j2
public class JsonConverter {
private static final ObjectMapper MAPPER;
static {
MAPPER = new ObjectMapper();
MAPPER.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
}
public static Optional<String> convertObject(Object object) {
try {
return Optional.of(MAPPER.writeValueAsString(object));
} catch (JsonProcessingException e) {
log.error("Error serialization object. " + e.getMessage());
return Optional.empty();
}
}
public static <T> Optional<T> convertJson(String json, Class<T> tClass) {
try {
return Optional.of(MAPPER.readValue(json, tClass));
} catch (IOException e) {
log.error("Error deserialization object. " + e.getMessage());
return Optional.empty();
}
}
}
|
package com.lock;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
//火箭发射 所有的步骤都完成 才能执行最后一步 ,
public class CountDownLatchTest {
public static void main(String[] args) throws Exception {
//定义总量6 设置status 的状态为6
CountDownLatch countDownLatc = new CountDownLatch(6);
for (int i = 0; i <6 ; i++) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""+Thread.currentThread().getName()+"完成");
// if(false){
// 每执行一次线程 ,释放锁 , status的值减 1
countDownLatc.countDown();
// }
}
},String.valueOf(i));
thread.start();
// new Thread(()->{
// System.out.println(""+Thread.currentThread().getName()+"完成");
// countDownLatc.countDown();
// },String.valueOf(i)).start();
}
//等待CountDownLatch到0才继续往下执行
//加入等待队列
countDownLatc.await();
System.out.println("发射");
}
}
|
package com.xuecheng.manage_course.client;
import com.xuecheng.manage_cms.api.CmsPageApi;
import org.springframework.cloud.openfeign.FeignClient;
@FeignClient(value = "xc-service-manage-cms")
public interface CmsPageClient extends CmsPageApi {
}
|
package com.ironyard.music.controller;
import com.ironyard.music.dto.GeoLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by favianalopez on 10/26/16.
*/
@RestController
public class GeoLocationController {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@RequestMapping( value="/service/geolocation", method= RequestMethod.GET)
public Iterable<GeoLocation> listGeoLocation (@RequestParam(value ="filter",required= false)String filter){
log.debug("Request to list geographic locations.");
RestTemplate restTemplate = new RestTemplate();
GeoLocation[] geoLocations = restTemplate.getForObject("http://ip-api.com/docs/api:json", GeoLocation[].class);
log.info(geoLocations.toString()) ;
log.debug("Get Geographic Location");
List<GeoLocation> foundAllList = Arrays.asList(geoLocations);
List<GeoLocation> filteredList = new ArrayList<>();
if(filter != null){
//filter the list
for(GeoLocation aLocation: foundAllList){
if (aLocation.getCountry().startsWith(filter)){
filteredList.add(aLocation);
}
}
}else{
//just return all
filteredList = foundAllList;
}
return filteredList;
}
}
|
/**
* TestVids class: used to test the queries to the database
* @author Andrea Bugin and Ilie Sarpe
*/
package test_Db;
class TestVids
{
public static void main(String[] args)
{
/*
Cluster cluster;
Session session;
cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
session = cluster.connect();
String query = null;
session.execute("USE streaming;");
// if it's the first time you execute the class, uncomment the following lines
query = UtilitiesDb.insertChannelVids("dellimellow", "https://www.youtube.com/watch?v=gVpYcpmNRb4");
session.execute(query);
System.out.println(query);
// this query is used to update a row in the database
query = UtilitiesDb.updateChannelVids("dellimellow", "https://www.youtube.com/watch?v=gVpYcpmNRb5");
session.execute(query);
// query to select all the records in the channel_vids
ResultSet results = session.execute("SELECT vids FROM channel_vids WHERE channel_name='dellimellow';");
System.out.println("Results = " + results);
for (Row row : results)
{
System.out.println(row);
}
query = UtilitiesDb.insertUrlPath("tesserato", "media//media_db//tesseratoPD.mp4");
System.out.println(query);
session.execute(query);
results = session.execute("SELECT * FROM vid_path;");
for (Row row : results)
{
System.out.println(row);
}
/*
Map<String, String> m = null;
for(Row row: results)
{
System.out.println(row);
m = row.getMap("vids", TypeToken.of(String.class), TypeToken.of(String.class));
//this returns a Map for each row in the table //this lambda expression is used, in this case, to
// print all the values
m.forEach((key, value) -> {
System.out.println(key);
System.out.println(value);
});
}
session.close();
cluster.close();
*/
}
}
|
package Listeners;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import FramesComponets.Wypozyczenie;
import model.Model;
import model.WypozyczenieModel;
import control.AbstractContoler;
import control.AbstractSingleControler;
import control.Controler;
import entity.*;
public class KartyListener extends AbstractSingleControler implements ChangeListener{
public KartyListener(Model m, Component c) {
super(m, c);
}
private void setTableRows(Wypozyczenie wypozyczenie, WypozyczenieModel model){
List<Rezerwacja> rezerwacje = model.getWszytkieRezerwacje();
List<Object[]> rows = new ArrayList<Object[]>(rezerwacje.size());
for (Rezerwacja r : rezerwacje) {
Klient k = r.getKlient();
Pojazd p = r.getDaneWypozyczenia().getPojazd();
DaneModeluPojazdu daneP = p.getDanePojazdu();
String status = r.getCzyPotwierdzona() ? "Potwiedzona"
: "Nie potwierdzona";
Object[] row = new Object[] {
r.getID(),
k.getImie(),
k.getNazwisko(),
daneP.getMarka() + " " + daneP.getModel() + " "
+ daneP.getTyp(),
r.getDataRezerwacji().toString(), status };
rows.add(row);
}
System.out.println(rows);
wypozyczenie.setRezerwacjeTable(rows);
}
private void setComboMarka(Wypozyczenie wypozyczenie, WypozyczenieModel model){
}
@Override
public void stateChanged(ChangeEvent e) {
Wypozyczenie wypozyczenie = (Wypozyczenie) this.getView();
WypozyczenieModel model = (WypozyczenieModel)this.getModel();
switch (wypozyczenie.getKarty().getSelectedIndex()) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3: {
setTableRows(wypozyczenie, model);
}
break;
default:
break;
}
}
}
|
package fr.cg95.cvq.testtool;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.hibernate.SessionFactory;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import fr.cg95.cvq.authentication.IAuthenticationService;
import fr.cg95.cvq.business.authority.Agent;
import fr.cg95.cvq.business.authority.SiteProfile;
import fr.cg95.cvq.business.authority.SiteRoles;
import fr.cg95.cvq.business.users.Address;
import fr.cg95.cvq.business.users.Adult;
import fr.cg95.cvq.business.users.Child;
import fr.cg95.cvq.business.users.CreationBean;
import fr.cg95.cvq.business.users.FamilyStatusType;
import fr.cg95.cvq.business.users.HomeFolder;
import fr.cg95.cvq.business.users.RoleType;
import fr.cg95.cvq.business.users.TitleType;
import fr.cg95.cvq.dao.IGenericDAO;
import fr.cg95.cvq.dao.hibernate.HibernateUtil;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.exception.CvqObjectNotFoundException;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.service.authority.IAgentService;
import fr.cg95.cvq.service.authority.ILocalAuthorityRegistry;
import fr.cg95.cvq.service.authority.IRecreationCenterService;
import fr.cg95.cvq.service.authority.ISchoolService;
import fr.cg95.cvq.service.users.IHomeFolderService;
import fr.cg95.cvq.service.users.IIndividualService;
import fr.cg95.cvq.util.Critere;
import fr.cg95.cvq.util.development.BusinessObjectsFactory;
@ContextConfiguration({ "/applicationContext.xml", "/applicationContext-deployment.xml",
"/applicationContext-test.xml", "/applicationContext-admin.xml",
"classpath*:pluginContext.xml", "classpath:/localAuthority-dummy.xml"})
public class ServiceTestCase extends AbstractJUnit4SpringContextTests {
// some tests data that can (have to) be used inside tests
public String localAuthorityName = "dummy";
public String agentNameWithCategoriesRoles = "agent";
public String agentNameWithManageRoles = "manager";
public String agentNameWithSiteRoles = "admin";
// some ecitizen-related objects that can be reused in tests
// they are created by the {@link #gimmeAnHomeFolder} method
protected Child child1;
protected Child child2;
protected Adult homeFolderResponsible;
protected Adult homeFolderWoman;
protected Adult homeFolderUncle;
protected Address address;
protected List<Long> homeFolderIds = new ArrayList<Long>();
// users related services
@Resource(name="individualService")
protected IIndividualService individualService;
@Autowired
protected IHomeFolderService homeFolderService;
@Autowired
protected IAuthenticationService authenticationService;
// authority related services
@Autowired
protected ISchoolService schoolService;
@Autowired
protected IRecreationCenterService recreationCenterService;
@Autowired
protected IAgentService agentService;
@Autowired
protected ILocalAuthorityRegistry localAuthorityRegistry;
@Resource(name="sessionFactory_dummy")
private SessionFactory sessionFactory;
protected static Boolean isInitialized = Boolean.FALSE;
@Before
public void onSetUp() throws Exception {
synchronized(isInitialized) {
if (!isInitialized.booleanValue()) {
startTransaction();
IGenericDAO genericDAO = getApplicationBean("genericDAO");
SecurityContext.setCurrentSite(localAuthorityName,
SecurityContext.BACK_OFFICE_CONTEXT);
try {
SecurityContext.setCurrentAgent(agentNameWithSiteRoles);
logger.debug("onSetUp() fixture data already created");
rollbackTransaction();
isInitialized = Boolean.TRUE;
startTransaction();
return;
} catch (CvqObjectNotFoundException confe) {
// ok, so we have to add fixture data
}
Agent admin = new Agent();
admin.setActive(Boolean.TRUE);
admin.setLogin(agentNameWithSiteRoles);
SiteRoles siteRoles = new SiteRoles(SiteProfile.ADMIN, admin);
Set<SiteRoles> siteRolesSet = new HashSet<SiteRoles>();
siteRolesSet.add(siteRoles);
admin.setSitesRoles(siteRolesSet);
genericDAO.create(admin);
continueWithNewTransaction();
SecurityContext.setCurrentAgent(agentNameWithSiteRoles);
bootstrapAgent(agentNameWithCategoriesRoles, SiteProfile.AGENT);
bootstrapAgent(agentNameWithManageRoles, SiteProfile.AGENT);
genericDAO.create(BusinessObjectsFactory.gimmeSchool("École Jean Jaurès"));
genericDAO.create(BusinessObjectsFactory.gimmeRecreationCenter("Centre de loisirs Louise Michel"));
commitTransaction();
isInitialized = Boolean.TRUE;
}
}
startTransaction();
}
private void bootstrapAgent(String agentName, SiteProfile siteProfile) throws CvqException {
Agent agent = new Agent();
agent.setActive(Boolean.TRUE);
agent.setLogin(agentName);
SiteRoles siteRoles = new SiteRoles(siteProfile, agent);
Set<SiteRoles> siteRolesSet = new HashSet<SiteRoles>();
siteRolesSet.add(siteRoles);
agent.setSitesRoles(siteRolesSet);
agentService.create(agent);
}
protected void startTransaction() throws CvqException {
try {
HibernateUtil.setSessionFactory(sessionFactory);
HibernateUtil.beginTransaction();
} catch (Exception e) {
logger.error("got exception while starting new tx");
e.printStackTrace();
throw new CvqException("");
}
}
protected void commitTransaction() {
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
}
protected void rollbackTransaction() throws CvqException {
try {
HibernateUtil.rollbackTransaction();
HibernateUtil.closeSession();
} catch (Exception e) {
throw new CvqException("");
}
}
protected void continueWithNewTransaction() {
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
HibernateUtil.beginTransaction();
}
@After
public void onTearDown() throws Exception {
try {
continueWithNewTransaction();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
// to force re-association of agent within current session
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
for (Long homeFolderId : homeFolderIds) {
homeFolderService.delete(homeFolderId);
try {
homeFolderService.getById(homeFolderId);
fail("should have thrown an exception");
} catch (CvqObjectNotFoundException confe) {
// ok, that was expected
}
}
homeFolderIds.clear();
continueWithNewTransaction();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.BACK_OFFICE_CONTEXT);
// to force re-association of agent within current session
SecurityContext.setCurrentAgent(agentNameWithCategoriesRoles);
// ensure all requests have been deleted after each test
assertEquals(0, individualService.get(new HashSet<Critere>(), null, true).size());
rollbackTransaction();
SecurityContext.resetCurrentSite();
} catch (Exception e) {
e.printStackTrace();
fail("Error during tear down : " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
protected <T> T getApplicationBean(String beanName) {
return (T) applicationContext.getBean(beanName);
}
/**
* Returns a file descriptor to a file that resides in the test
* hierarchy. The base directory is taken from the
* "test.resource.dir" system property.
*/
protected static File getResourceFile(String path) {
return new File(System.getProperty("test.resource.dir"), path);
}
/**
* Returns a file descriptor to a file that resides in the test
* data hierarchy. The base directory is taken from the
* "test.data.dir" system property.
*/
protected static File getTestDataFile(String path) {
return new File(System.getProperty("test.data.dir"), path);
}
public CreationBean gimmeMinimalHomeFolder() throws CvqException {
// keep current context to reset it after home folder creation
String currentContext = SecurityContext.getCurrentContext();
Agent currentAgent = SecurityContext.getCurrentAgent();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
address = BusinessObjectsFactory.gimmeAdress("12","Rue d'Aligre", "Paris", "75012");
homeFolderResponsible = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER, "lastName",
"firstName", address, FamilyStatusType.SINGLE);
homeFolderResponsible.setAdress(address);
homeFolderService.addHomeFolderRole(homeFolderResponsible, RoleType.HOME_FOLDER_RESPONSIBLE);
HomeFolder homeFolder = homeFolderService.create(homeFolderResponsible);
CreationBean cb = new CreationBean();
cb.setHomeFolderId(homeFolder.getId());
cb.setLogin(homeFolderResponsible.getLogin());
homeFolderIds.add(homeFolder.getId());
if (currentContext != null)
SecurityContext.setCurrentContext(currentContext);
if (currentAgent != null)
SecurityContext.setCurrentAgent(currentAgent);
continueWithNewTransaction();
return cb;
}
public CreationBean gimmeAnHomeFolder() throws CvqException {
// keep current context to reset it after home folder creation
String currentContext = SecurityContext.getCurrentContext();
Agent currentAgent = SecurityContext.getCurrentAgent();
SecurityContext.setCurrentSite(localAuthorityName, SecurityContext.FRONT_OFFICE_CONTEXT);
address = BusinessObjectsFactory.gimmeAdress("12","Rue d'Aligre", "Paris", "75012");
homeFolderResponsible = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER, "lastName",
"firstName", address, FamilyStatusType.SINGLE);
homeFolderService.addHomeFolderRole(homeFolderResponsible, RoleType.HOME_FOLDER_RESPONSIBLE);
homeFolderWoman = BusinessObjectsFactory.gimmeAdult(TitleType.MISTER, "lastName",
"woman", address, FamilyStatusType.SINGLE);
List<Adult> adults = new ArrayList<Adult>();
adults.add(homeFolderResponsible);
adults.add(homeFolderWoman);
HomeFolder homeFolder = homeFolderService.create(adults, null, new Address());
CreationBean cb = new CreationBean();
cb.setHomeFolderId(homeFolder.getId());
cb.setLogin(homeFolderResponsible.getLogin());
homeFolderIds.add(homeFolder.getId());
if (currentContext != null)
SecurityContext.setCurrentContext(currentContext);
if (currentAgent != null)
SecurityContext.setCurrentAgent(currentAgent);
continueWithNewTransaction();
return cb;
}
}
|
package banking.exceptions;
public class TooManyArgumentsException extends Exception {
/**
*
*/
private static final long serialVersionUID = 5417416424661983240L;
}
|
import java.util.ArrayList;
public class AddressBook {
private ArrayList<BuddyInfo> buddies;
public AddressBook(){
buddies = new ArrayList<BuddyInfo>();
}
public void addBuddy(BuddyInfo buddy){
if (buddy != null){
buddies.add(buddy);
}
}
public void removeBuddy(int index){
if(index < buddies.size() && index >= 0)
buddies.remove(index);
}
public void removeBuddy(BuddyInfo buddy){
if (buddy != null && buddies.contains(buddy)){
buddies.remove(buddy);
}
}
public static void main(String[] args) {
BuddyInfo Jimbo = new BuddyInfo("Jimbo","123 Fake Street", "(555) 555-5555");
BuddyInfo Name = new BuddyInfo();
AddressBook buddies = new AddressBook();
Jimbo.printName();
Name.setName("John Doe");
Name.setAddress("321 Faker Street");
Name.setPhoneNumber("(613) 555-5555");
Name.printName();
buddies.addBuddy(Jimbo);
buddies.addBuddy(Name);
buddies.removeBuddy(Name);
}
}
|
/* (Geometry: area of a pentagon) The area of a pentagon can be computed using the
* following formula:
*/
import java.util.Scanner;
public class Exercise6_35 {
/** Main method */
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter the side of a pentagon
System.out.print("Enter the side: ");
double side = input.nextDouble();
// Display its area
System.out.printf("The area of the pentagon is %.4f", area(side));
}
/* method area computes the value of area opf pentagon */
public static double area(double side) {
return (5 * Math.pow(side, 2)) / (4 * Math.tan(Math.PI / 5));
}
}
|
package bartender.services;
import bartender.bardatabase.BarStorage;
import bartender.items.NewDiscountBroadcast;
import bartender.mics.MicroService;
import bartender.mics.ProtocolCallback;
import bartender.services.MessageBusImpl;
public class BroadcastListenerService extends MicroService {
private int mbt;
private ProtocolCallback<String> callback;
public BroadcastListenerService(ProtocolCallback<String> callback ,MessageBusImpl MessageBusImpl, BarStorage BarStorage, String [] args) {
super("listner", MessageBusImpl);
this.callback=callback;
try {
mbt = Integer.parseInt(args[0]);
} catch (NumberFormatException ex) {
throw new IllegalArgumentException("Listener expecting the argument mbt to be a number > 0, instead received: " + args[0]);
}
if (mbt <= 0) {
throw new IllegalArgumentException("Listener expecting the argument mbt to be a number > 0, instead received: " + args[0]);
}
}
@Override
protected void initialize() {
System.out.println("Listener " + getName() + " started");
subscribeBroadcast(NewDiscountBroadcast.class, message -> {
mbt--;
try {
callback.sendMessage("you have discount: "+message.getItem()+""+message.getAmount()+"");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mbt == 0) {
System.out.println("Listener " + getName() + " terminating.");
terminate();
}
});
}
}
|
package com.javakc.ssm.modules.customerIn.service;
import com.javakc.ssm.base.page.Page;
import com.javakc.ssm.base.service.BaseService;
import com.javakc.ssm.modules.customerIn.dao.CustomerInDao;
import com.javakc.ssm.modules.customerIn.entity.CustomerInEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @ClassName CustomerInService
* @Description TODO
* @Author Administrator
* @Date 2020/3/21 12:03
* @Version 1.0
**/
@Service
public class CustomerInService extends BaseService<CustomerInDao, CustomerInEntity> {
@Autowired
CustomerInDao customerInDao;
public Page querycustomerIn(CustomerInEntity customerInEntity, Page page){
// ##设置分页参数
customerInEntity.setPage(page);
// ##调用dao方法,进行数据查询
List<CustomerInEntity> list = customerInDao.findList(customerInEntity);
page.setList(list);
return page;
}
}
|
package com.tencent.mm.plugin.facedetect.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import com.tencent.mm.plugin.facedetect.FaceProNative;
import com.tencent.mm.plugin.facedetect.FaceProNative.FaceResult;
import com.tencent.mm.plugin.facedetect.e.a;
import com.tencent.mm.plugin.facedetect.model.FaceContextData;
import com.tencent.mm.plugin.facedetect.model.f;
import com.tencent.mm.plugin.facedetect.model.g;
import com.tencent.mm.plugin.facedetect.model.o;
import com.tencent.mm.plugin.facedetect.model.p;
import com.tencent.mm.sdk.platformtools.x;
public class FaceDetectProcessService extends Service {
public g iPA = null;
private Messenger iPB = null;
private a iPC = null;
private a iPz = new a(this);
public void onCreate() {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo service onCreate hashCode: %d", new Object[]{Integer.valueOf(hashCode())});
super.onCreate();
this.iPA = new g();
}
public int onStartCommand(Intent intent, int i, int i2) {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo onStartCommand");
if (intent == null) {
x.e("MicroMsg.FaceDetectProcessService", "intent is null!!");
return super.onStartCommand(intent, i, i2);
}
Messenger messenger = (Messenger) intent.getParcelableExtra("k_messenger");
if (messenger != null) {
this.iPB = messenger;
return super.onStartCommand(intent, i, i2);
}
x.i("MicroMsg.FaceDetectProcessService", "hy: get command: %d", new Object[]{Integer.valueOf(intent.getIntExtra("k_cmd", -1))});
switch (intent.getIntExtra("k_cmd", -1)) {
case 0:
a aVar;
int engineInit;
String stringExtra = intent.getStringExtra("k_bio_id");
byte[] byteArrayExtra = intent.getByteArrayExtra("k_bio_config");
FaceContextData.a((FaceContextData) intent.getParcelableExtra("k_ontext_data"));
switch (intent.getIntExtra("k_server_scene", 2)) {
case 0:
case 1:
aVar = null;
break;
case 2:
case 5:
aVar = new b();
break;
default:
aVar = null;
break;
}
this.iPC = aVar;
g gVar = this.iPA;
if (gVar.iNy != null) {
x.w("MicroMsg.FaceDetectNativeManager", "hy: last detection not destroyed");
gVar.aJS();
}
if (o.aJW()) {
gVar.iNy = new FaceProNative();
engineInit = gVar.iNy.engineInit(stringExtra, byteArrayExtra, o.aJY(), o.aJZ());
x.i("MicroMsg.FaceDetectNativeManager", "hy: init result : %d", new Object[]{Integer.valueOf(engineInit)});
} else {
x.w("MicroMsg.FaceDetectNativeManager", "hy: model file not valid");
engineInit = -4;
}
cz(0, engineInit);
break;
case 1:
f.y(new 2(this, new p() {
public final void b(FaceResult faceResult) {
int i = -1;
String str = "MicroMsg.FaceDetectProcessService";
String str2 = "alvinluo release out result == null:%b, result: %d";
Object[] objArr = new Object[2];
objArr[0] = Boolean.valueOf(faceResult == null);
objArr[1] = Integer.valueOf(faceResult != null ? faceResult.result : -1);
x.i(str, str2, objArr);
if (faceResult == null || faceResult.result != 0) {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo release out data not valid");
if (faceResult != null) {
i = faceResult.result;
}
FaceDetectProcessService.this.cz(1, i);
return;
}
f.y(new 1(this, faceResult));
}
}));
break;
case 4:
a.aKA().iSn = intent.getBooleanExtra("key_is_need_video", false);
break;
case 5:
if (this.iPC != null) {
this.iPC.C(intent);
break;
}
break;
default:
x.e("MicroMsg.FaceDetectProcessService", "hy: unsupported cmd");
break;
}
return super.onStartCommand(intent, i, i2);
}
public IBinder onBind(Intent intent) {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo service onBind hashCode: %d", new Object[]{Integer.valueOf(hashCode())});
this.iPz = new a(this);
return this.iPz;
}
public boolean onUnbind(Intent intent) {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo service onUnbind");
return super.onUnbind(intent);
}
public void onDestroy() {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo service onDestroy");
super.onDestroy();
}
private void n(Message message) {
try {
if (this.iPB != null) {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo serivce send msg to client: %d, msg: %s, client hashCode: %d", new Object[]{Integer.valueOf(message.what), message.toString(), Integer.valueOf(this.iPB.hashCode())});
this.iPB.send(message);
}
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.FaceDetectProcessService", e, "", new Object[0]);
}
}
private void cz(int i, int i2) {
x.i("MicroMsg.FaceDetectProcessService", "alvinluo replyToClient requestCode: %d, resultCode: %d", new Object[]{Integer.valueOf(i), Integer.valueOf(i2)});
Message message = new Message();
message.what = i;
message.arg1 = i2;
n(message);
}
}
|
package com.example.demo.Status.Exception;
import com.example.demo.Status.GlobalException;
public class NotFoundException extends GlobalException {
public NotFoundException(String message, int code) {
super(message, code);
}
}
|
package Controller;
import DBConnection.DBQuery;
import Model.Customer;
import Model.User;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
import static Controller.Customers.*;
public class AddCustomers implements Initializable {
@FXML
private TableView<Customer> customersTable;
@FXML
private TableColumn<Customer, Integer> customerIDCol;
@FXML
private TableColumn<Customer, String> customerNameCol;
@FXML
private TableColumn<Customer, Integer> addressIDCol;
@FXML
private TableColumn<Customer, Boolean> activeCol;
@FXML
private TableColumn<Customer, Date> createdDateCol;
@FXML
private TableColumn<Customer, String> createdByCol;
@FXML
private TableColumn<Customer, Timestamp> lastUpdateCol;
@FXML
private TableColumn<Customer, String> lastUpdatedByCol;
@FXML
private ChoiceBox<Boolean> activeCB;
@FXML
private TextField customerNameField;
@FXML
private TextField address;
@FXML
private TextField address2;
@FXML
private Label address2Lbl;
@FXML
private TextField city;
@FXML
private TextField country;
@FXML
private TextField postal;
@FXML
private TextField phoneNumber;
@FXML
private Label addCustomers;
@FXML
private Button addCustomer;
@FXML
private Button exitBtn;
@FXML
private Label customerName;
@FXML
private Label address1;
@FXML
private Label postalCode;
@FXML
private Label phone;
@FXML
private Label active;
Statement statement = DBQuery.getStatement();
String deleteAll = "DELETE FROM customers WHERE customerId >= " + 0 + ";";
public void addCustomer(ActionEvent event) throws IOException {
Parent projectParent = FXMLLoader.load(getClass().getResource("../View/AddCustomers.fxml"));
Scene projectScene = new Scene(projectParent);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(projectScene);
window.setTitle("Add Customer");
window.show();
}
public void deleteCustomer(ActionEvent event) {
try {
statement.execute(deleteAll);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void goToUpdateCustomer(ActionEvent event) throws IOException {
Parent projectParent = FXMLLoader.load(getClass().getResource("../View/UpdateCustomer.fxml"));
Scene projectScene = new Scene(projectParent);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(projectScene);
window.setTitle("Update Customer");
window.show();
}
public void saveCustomer(ActionEvent event) throws IOException, SQLException {
boolean valid = true;
Boolean newCountry = true;
Boolean newCity = true;
Boolean newAddress = true;
Boolean newCustomer = true;
Boolean newUser = true;
ResultSet DBCustomer = statement.executeQuery("SELECT * FROM customer;");
while (DBCustomer.next()) {
String DBCustomerId = DBCustomer.getString("customerId");
String DBCustomerName = DBCustomer.getString("customerName");
System.out.println(DBCustomerName + " is under ID: " + DBCustomerId);
}
/**
* Gets countryId Count
*/
int countryCounter = 0;
ResultSet countryCount = statement.executeQuery("SELECT *" +
" FROM country;");
while (countryCount.next()) {
countryCounter = countryCount.getRow();
}
System.out.println("Country has " + countryCounter + " row(s).");
countryCount.close();
/**
* Gets cityId Count
*/
int cityCounter = 0;
ResultSet cityCount = statement.executeQuery("SELECT *" +
" FROM city;");
while (cityCount.next()) {
cityCounter = cityCount.getRow();
}
System.out.println("City has " + cityCounter + " row(s).");
cityCount.close();
/**
* Gets userId Count
*/
int userCounter = 0;
ResultSet userCount = statement.executeQuery("SELECT *" +
" FROM user;");
while (userCount.next()) {
userCounter = userCount.getRow();
}
System.out.println("User has " + userCounter + " row(s).");
userCount.close();
/**
* Gets addressId Count
*/
int addressCounter = 0;
ResultSet addressCount = statement.executeQuery("SELECT *" +
" FROM address;");
while (addressCount.next()) {
addressCounter = addressCount.getRow();
}
System.out.println("Address has " + addressCounter + " row(s).");
addressCount.close();
/**
* Gets customerId Count
*/
int customerCounter = 0;
ResultSet customerCount = statement.executeQuery("SELECT *" +
" FROM customer;");
while (customerCount.next()) {
customerCounter = customerCount.getRow();
}
System.out.println("Customer has " + customerCounter + " row(s).");
customerCount.close();
Integer newActive = null;
if (activeCB.getValue() == false) {
newActive = 0;
} else if (activeCB.getValue() == true) {
newActive = 1;
}
String active = newActive.toString();
String customerId = String.valueOf(getAllCustomers().get(customerCounter - 1).getCustomerID() + 1);
String customerName = customerNameField.getText();
String createDate = String.valueOf(new Date(System.currentTimeMillis()));
String createdBy = LogIn.getUsername();
String lastUpdate = String.valueOf(new Timestamp(System.currentTimeMillis()));
String lastUpdateBy = LogIn.getUsername();
String address1 = address.getText();
String addressTwo = address2.getText();
String cityName = city.getText();
String addressId = String.valueOf(addressCounter + 1);
ResultSet DBaddress = statement.executeQuery("SELECT * FROM address;");
while (DBaddress.next()) {
String DBaddressId = DBaddress.getString("addressId");
String DBaddressName = DBaddress.getString("address");
if (address.getText().compareTo(DBaddress.getString("address")) == 0) {
System.out.println(DBaddressName + " already exists under ID: " + DBaddressId + "!");
newAddress = false;
addressId = String.valueOf(DBaddress.getString("addressId"));
}
}
String countryName = country.getText();
String countryId = String.valueOf(countryCounter + 1);
ResultSet DBCountry = statement.executeQuery("SELECT * FROM country;");
while (DBCountry.next()) {
String DBCountryId = DBCountry.getString("countryId");
String DBCountryName = DBCountry.getString("country");
if (country.getText().compareTo(DBCountry.getString("country")) == 0) {
System.out.println(DBCountryName + " already exists under ID: " + DBCountryId + "!");
newCountry = false;
countryId = String.valueOf(DBCountry.getString("countryId"));
}
}
String cityId = String.valueOf(cityCounter + 1);
ResultSet DBCity = statement.executeQuery("SELECT * FROM city;");
while (DBCity.next()) {
String DBCityId = DBCity.getString("cityId");
String DBCityName = DBCity.getString("city");
if ((city.getText().compareTo(DBCity.getString("city")) == 0) && !newCountry) {
System.out.println(DBCityName + " already exists under ID: " + DBCityId + "!");
newCity = false;
cityId = String.valueOf(DBCity.getString("cityId"));
}
}
String postalAdd = postal.getText();
String phoneNumberAdd = phoneNumber.getText();
String userId = String.valueOf(userCounter + 1);
ResultSet DBUser = statement.executeQuery("SELECT * FROM user;");
while (DBUser.next()) {
String DBUserId = DBUser.getString("userId");
String DBUserName = DBUser.getString("userName");
if ((LogIn.username.compareTo(DBUser.getString("userName")) == 0)) {
System.out.println(DBUserName + " already exists under ID: " + DBUserId + "!");
newUser = false;
userId = String.valueOf(DBUser.getString("userId"));
}
}
String userName = User.getUsername();
String password = User.getPassword();
/**
* Insert into table
*/
String insertUser = "INSERT INTO user(userId, userName, password, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(" +
"'" + userId + "'," +
"'" + userName + "'," +
"'" + password + "'," +
"'" + active + "'," +
"'" + createDate + "'," +
"'" + createdBy + "'," +
"'" + lastUpdate + "'," +
"'" + lastUpdateBy + "');";
String insertCustomer = "INSERT INTO customer(customerId, customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(" +
"'" + customerId + "'," +
"'" + customerName + "'," +
"'" + addressId + "'," +
"'" + active + "'," +
"'" + createDate + "'," +
"'" + createdBy + "'," +
"'" + lastUpdate + "'," +
"'" + lastUpdateBy + "');";
String insertAddress = "INSERT INTO address(addressId, address, address2, cityId, postalCode, phone, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(" +
"'" + addressId + "'," +
"'" + address1 + "'," +
"'" + addressTwo + "'," +
"'" + cityId + "'," +
"'" + postalAdd + "'," +
"'" + phoneNumberAdd + "'," +
"'" + createDate + "'," +
"'" + createdBy + "'," +
"'" + lastUpdate + "'," +
"'" + lastUpdateBy + "');";
String insertCity = "INSERT INTO city(cityId, city, countryId, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(" +
"'" + cityId + "'," +
"'" + cityName + "'," +
"'" + countryId + "'," +
"'" + createDate + "'," +
"'" + createdBy + "'," +
"'" + lastUpdate + "'," +
"'" + lastUpdateBy + "');";
String insertCountry = "INSERT INTO country(countryId, country, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(" +
"'" + countryId + "'," +
"'" + countryName + "'," +
"'" + createDate + "'," +
"'" + createdBy + "'," +
"'" + lastUpdate + "'," +
"'" + lastUpdateBy + "'" +
");";
/**
* Checks if forms are completed
*/
if (customerNameField == null ||
address.getText().isEmpty() ||
address2.getText().isEmpty() ||
city.getText().isEmpty() ||
country.getText().isEmpty() ||
postal.getText().isEmpty() ||
phoneNumber.getText().isEmpty() ||
activeCB.getValue() == null) {
Alert nullFields = new Alert(Alert.AlertType.WARNING);
nullFields.setTitle("Incomplete Data");
nullFields.setContentText("Please check all forms for missing data.");
nullFields.showAndWait();
valid = false;
}
/**
* Checks for non-conforming data
*/
try {
Integer.parseInt(phoneNumber.getText());
Integer.parseInt(postal.getText());
} catch (NumberFormatException e) {
valid = false;
Appointments.alertType();
}
if (valid) {
Customer customer = new Customer(Integer.parseInt(customerId), customerName, Integer.valueOf(addressId), newActive, Date.valueOf(createDate), createdBy, Timestamp.valueOf(lastUpdate), lastUpdateBy);
addNewCustomer(customer);
if (newUser) {
statement.execute(insertUser);
}
if (newCountry) {
statement.execute(insertCountry);
}
if (newCity) {
statement.execute(insertCity);
}
if (newAddress) {
statement.execute(insertAddress);
}
if (newCustomer) {
statement.execute(insertCustomer);
}
Parent projectParent = FXMLLoader.load(getClass().getResource("../View/Customers.fxml"));
Scene projectScene = new Scene(projectParent);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(projectScene);
window.setTitle("Customers");
window.show();
}
}
public void goToCustomer(ActionEvent event) throws IOException {
Parent projectParent = FXMLLoader.load(getClass().getResource("../View/Customers.fxml"));
Scene projectScene = new Scene(projectParent);
Stage window = (Stage) ((Node) event.getSource()).getScene().getWindow();
window.setScene(projectScene);
window.setTitle("Customers");
window.show();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
ObservableList choiceBox = FXCollections.observableArrayList();
choiceBox.addAll(false, true);
activeCB.setItems(choiceBox);
customersTable.getSortOrder().setAll();
//set up initial values in table
customersTable.setItems(getAllCustomers());
//Setup customer table
customerIDCol.setCellValueFactory(new PropertyValueFactory<>("customerID"));
customerNameCol.setCellValueFactory(new PropertyValueFactory<>("customerName"));
addressIDCol.setCellValueFactory(new PropertyValueFactory<>("addressId"));
activeCol.setCellValueFactory(new PropertyValueFactory<>("active"));
createdDateCol.setCellValueFactory(new PropertyValueFactory<>("createdDate"));
createdByCol.setCellValueFactory(new PropertyValueFactory<>("createdBy"));
lastUpdateCol.setCellValueFactory(new PropertyValueFactory<>("lastUpdate"));
lastUpdatedByCol.setCellValueFactory(new PropertyValueFactory<>("lastUpdatedBy"));
}
}
|
package com.tencent.mm.ui.tools;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.ac.d;
import com.tencent.mm.storage.ab;
class b$1 implements OnClickListener {
final /* synthetic */ Activity ews;
final /* synthetic */ ab hMD;
final /* synthetic */ d uvL;
final /* synthetic */ boolean uvM;
final /* synthetic */ int uvN;
final /* synthetic */ Runnable uvO;
b$1(d dVar, Activity activity, ab abVar, boolean z, int i, Runnable runnable) {
this.uvL = dVar;
this.ews = activity;
this.hMD = abVar;
this.uvM = z;
this.uvN = i;
this.uvO = runnable;
}
public final void onClick(DialogInterface dialogInterface, int i) {
b.a(this.uvL, this.ews, this.hMD, this.uvM, this.uvN);
if (this.uvO != null) {
this.uvO.run();
}
}
}
|
package com.mkyong;
import org.junit.*;
import org.springframework.boot.builder.SpringApplicationBuilder;
public class SpringBootWebApplicationTest {
@Test
public void SpringBootWebApplicatioTest(){
SpringBootWebApplication sbw = new SpringBootWebApplication();
SpringApplicationBuilder sab = new SpringApplicationBuilder();
SpringApplicationBuilder resab = new SpringApplicationBuilder();
resab = sbw.configure(sab);
Assert.assertEquals(resab,sab);
}
}
|
package de.madjosz.adventofcode.y2020;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Day15 {
private final int[] startingNumbers;
public Day15(String input) {
this.startingNumbers = Arrays.stream(input.split(",")).mapToInt(Integer::parseInt).toArray();
}
public int a1() {
return getNumber(2020);
}
private int getNumber(int n) {
Map<Integer, Integer> occurences = new HashMap<>();
for (int i = 0; i < startingNumbers.length - 1; ++i)
occurences.put(startingNumbers[i], i);
int last = startingNumbers[startingNumbers.length - 1];
for (int i = startingNumbers.length; i < n; ++i) {
Integer pos = occurences.get(last);
occurences.put(last, i - 1);
if (pos == null) last = 0;
else last = i - 1 - pos;
}
return last;
}
public int a2() {
return getNumber(30000000);
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.plugin.sns.lucky.a.m;
import com.tencent.mm.plugin.sns.lucky.ui.a;
import com.tencent.mm.plugin.sns.storage.n;
import com.tencent.mm.plugin.sns.ui.SnsCommentFooter.c;
import com.tencent.mm.protocal.c.bon;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.x;
class SnsCommentDetailUI$14 implements c {
final /* synthetic */ n nMf;
final /* synthetic */ SnsCommentDetailUI nUO;
SnsCommentDetailUI$14(SnsCommentDetailUI snsCommentDetailUI, n nVar) {
this.nUO = snsCommentDetailUI;
this.nMf = nVar;
}
public final void NJ(String str) {
int i = 1;
if (m.LS(this.nMf.bBe())) {
bon commentInfo = SnsCommentDetailUI.b(this.nUO).getCommentInfo();
if (SnsCommentDetailUI.b(this.nUO).getSendType() != 1) {
i = 0;
}
SnsCommentDetailUI.a(this.nUO, str, commentInfo, i);
SnsCommentDetailUI.b(this.nUO).ir(false);
x.i("MicroMsg.SnsCommentDetailUI", "comment send imp!");
SnsCommentDetailUI.s(this.nUO);
new ag().postDelayed(new 1(this), 100);
return;
}
a.e(this.nUO.mController.tml, this.nUO.nUK.xm(0));
}
}
|
package jp.juggler.subwaytooter;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
// Android instrumentation test は run configuration を編集しないと Empty tests とかいうエラーになります
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception{
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals( "jp.juggler.subwaytooter", appContext.getPackageName() );
}
}
|
package com.github.io24m.validate4java.validator;
import com.github.io24m.validate4java.ValidateMetadata;
/**
* @author lk1
* @description
* @create 2021-02-01 13:25
*/
public abstract class AbstractValidator<T> implements BaseValidator<T> {
@Override
public boolean pass(ValidateMetadata<T> metadata) {
return false;
}
@Override
public boolean filter(ValidateMetadata<T> metadata) {
return true;
}
}
|
package com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.goldgov.dygl.ShConstant;
import com.goldgov.dygl.module.partyMemberDuty.duty.dao.IDutyDao;
import com.goldgov.dygl.module.partyMemberDuty.duty.domain.Duty;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.dao.IMutualEvaluationDao;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.dao.IQualitativeConditionsDao;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.domain.MutualEvaluation;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.domain.MutualEvaluationBean;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.domain.QualitativeConditions;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.service.IMutualEvaluationService;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.service.MutualEvaluationQuery;
import com.goldgov.dygl.module.partyMemberDuty.mutualevaluation.service.QualitativeConditionsQuery;
import com.goldgov.dygl.module.partymember.exception.NoAuthorizedFieldException;
import com.goldgov.dygl.module.partymember.service.IPartyMemberService_AA;
import com.goldgov.dygl.module.partyorganization.service.PartyOrganization;
import com.goldgov.gtiles.core.security.AuthorizedDetails;
import com.goldgov.gtiles.core.web.UserHolder;
import com.goldgov.gtiles.module.user.service.User;
@Service("mutualevaluationServiceImpl")
public class MutualEvaluationServiceImpl implements IMutualEvaluationService {
@Autowired
@Qualifier("mutualevaluationDao")
private IMutualEvaluationDao mutualevaluationDao;
@Autowired
@Qualifier("qualitativeconditionsDao")
private IQualitativeConditionsDao qualitativeconditionsDao;
@Autowired
@Qualifier("dutyDao")
private IDutyDao dutyDao;
@Autowired
@Qualifier("partyMemberService_AA")
private IPartyMemberService_AA partyMemberService;
@Override
public void addInfo(MutualEvaluation mutualevaluation) throws NoAuthorizedFieldException {
mutualevaluationDao.addInfo(mutualevaluation);
}
@Override
public void updateInfo(MutualEvaluation mutualevaluation) throws NoAuthorizedFieldException {
mutualevaluationDao.updateInfo(mutualevaluation);
}
@Override
public void deleteInfo(String[] entityIDs) throws NoAuthorizedFieldException {
mutualevaluationDao.deleteInfo(entityIDs);
}
public List<String> findHpUserIdsByDuty(Duty dp,String dutyID){
if(dp==null){
dp=dutyDao.findInfoById(dutyID);
}
String[] userIds=dp.getDutyMemberid().split(",");
if(dp.getHpfw().intValue()==1){
return Arrays.asList(userIds);
}else if(dp.getHpfw().intValue()==2){
String belongOrgID = "";
AuthorizedDetails details = (AuthorizedDetails)UserHolder.getUserDetails();
User user = (User) details.getCustomDetails(ShConstant.USER_INFO);
//获取用户所在党小组ID
List<String> groupIDs = partyMemberService.findUserGroupID(user.getEntityID());
String groupID = "";
if(groupIDs != null && groupIDs.size() > 0){
groupID = groupIDs.get(0);
}
if(groupID != null && !"".equals(groupID)){
belongOrgID = groupID;
}else{
PartyOrganization currentPartyOrg = (PartyOrganization)details.getCustomDetails(ShConstant.CURRENT_PARTY_ORGANZATION);
belongOrgID = currentPartyOrg.getEntityID();
}
//获取党小组 用户ids
List<String> userIDList = partyMemberService.findUserIDByPoAaID(belongOrgID);
List<String> userIDArr = new ArrayList<String>();
for(String userID : userIds){
if(userIDList.contains(userID)){
userIDArr.add(userID);
}
}
return userIDArr;
}
return null;
}
@Override
public List<MutualEvaluationBean> findInfoList(MutualEvaluationQuery query) throws NoAuthorizedFieldException {
List<MutualEvaluationBean> relList=new ArrayList<MutualEvaluationBean>();
Duty dp=dutyDao.findInfoById(query.getSearchDutyId());
//获取 定性条件数量
QualitativeConditionsQuery query2=new QualitativeConditionsQuery();
query2.setPageSize(-1);
List<QualitativeConditions> list=qualitativeconditionsDao.findInfoListByPage(query2);
int wf=0;//违反合格党员标准数量
int js=0;//警示行为
if(list!=null&&list.size()>0){
for (QualitativeConditions qc:list) {
if(qc.getConditionsType()!=null&&qc.getConditionsType().intValue()==1){
wf++;
}else if(qc.getConditionsType()!=null&&qc.getConditionsType().intValue()==2){
js++;
}
}
}
if(dp!=null&&dp.getDutyMemberid()!=null){
List<String>userIDArr=findHpUserIdsByDuty(dp,null);
if(!userIDArr.isEmpty()){
query.setDutyMemberids(userIDArr.toArray(new String[0]));
query.setPageSize(-1);
relList=mutualevaluationDao.findInfoList(query);
}
//设置 违反合格党员标准 警示行为 数量
if(relList!=null&&relList.size()>0){
for (MutualEvaluationBean meb:relList) {
meb.setQualifiedStandardCount(wf);
meb.setWarningBehaviorCount(js);
meb.setQualifiedStandardSize(0);
meb.setWarningBehaviorSize(0);
if(meb.getQualifiedStandard()!=null){
meb.setQualifiedStandardSize(meb.getQualifiedStandard().split("@@SPLIT@@").length);
}
if(meb.getWarningBehavior()!=null){
meb.setWarningBehaviorSize(meb.getWarningBehavior().split("@@SPLIT@@").length);
}
}
}
}
return relList;
}
@Override
public MutualEvaluation findInfoById(String entityID) throws NoAuthorizedFieldException {
return mutualevaluationDao.findInfoById(entityID);
}
@Override
public List<QualitativeConditions> findInfoAllList(
QualitativeConditionsQuery query) throws NoAuthorizedFieldException {
if(query==null)query=new QualitativeConditionsQuery();
query.setPageSize(-1);
return qualitativeconditionsDao.findInfoListByPage(query);
}
@Override
public List<MutualEvaluationBean> findInfoListMutual(MutualEvaluationQuery query)
throws NoAuthorizedFieldException {
Duty dp=dutyDao.findInfoById(query.getSearchDutyId());
List<MutualEvaluationBean> relList = mutualevaluationDao.findInfoListByPage(query);
//获取 定性条件数量
QualitativeConditionsQuery query2=new QualitativeConditionsQuery();
query2.setPageSize(-1);
List<QualitativeConditions> list=qualitativeconditionsDao.findInfoListByPage(query2);
int wf=0;//违反合格党员标准数量
int js=0;//警示行为
if(list!=null&&list.size()>0){
for (QualitativeConditions qc:list) {
if(qc.getConditionsType()!=null&&qc.getConditionsType().intValue()==1){
wf++;
}else if(qc.getConditionsType()!=null&&qc.getConditionsType().intValue()==2){
js++;
}
}
}
if(dp!=null&&dp.getDutyMemberid()!=null){
//设置 违反合格党员标准 警示行为 数量
if(relList!=null&&relList.size()>0){
for (MutualEvaluationBean meb:relList) {
meb.setQualifiedStandardCount(wf);
meb.setWarningBehaviorCount(js);
meb.setQualifiedStandardSize(0);
meb.setWarningBehaviorSize(0);
if(meb.getQualifiedStandard()!=null){
meb.setQualifiedStandardSize(meb.getQualifiedStandard().split("@@SPLIT@@").length);
}
if(meb.getWarningBehavior()!=null){
meb.setWarningBehaviorSize(meb.getWarningBehavior().split("@@SPLIT@@").length);
}
}
}
}
return relList;
}
}
|
package com.xiaoxiao.service.backend.impl;
import com.xiaoxiao.feign.BlogsFeignServiceClient;
import com.xiaoxiao.pojo.XiaoxiaoArticles;
import com.xiaoxiao.pojo.XiaoxiaoImg;
import com.xiaoxiao.service.backend.ArticleFeignService;
import com.xiaoxiao.utils.Result;
import com.xiaoxiao.utils.StatusCode;
import com.xiaoxiao.utils.UploadOSSUtils;
import com.xiaoxiao.utils.UploadResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* .' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
* 佛祖保佑 永无BUG
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*
* @project_name:xiaoxiao_final_blogs
* @date:2019/11/29:16:37
* @author:shinelon
* @Describe:
*/
@Service
public class ArticleFeignServiceImpl implements ArticleFeignService
{
@Autowired
private BlogsFeignServiceClient blogsFeignServiceClient;
@Value("${ENDPOINT}")
private String ENDPOINT;
@Value("${ACCESSKEYSECRET}")
private String ACCESSKEYSECRET;
@Value("${ACCESSKEYID}")
private String ACCESSKEYID;
@Value("${BUCKETNAME}")
private String BUCKETNAME;
@Value("${ARTICLE_FILE_PATH}")
private String ARTICLE_FILE_PATH;
@Value("${REQUEST_HEAD}")
private String REQUEST_HEAD;
/**
* 查询全部的文章信息
*
* @param page
* @param rows
* @return
*/
@Override
public Result findAllArticle(Integer page, Integer rows)
{
return this.blogsFeignServiceClient.findAllArticle(page, rows);
}
/**
* 删除文章
*
* @param articleId
* @return
*/
@Override
public Result delete(Long articleId)
{
return this.blogsFeignServiceClient.deleteArticle(articleId);
}
/**
* 查找一个文章
*
* @param articleId
* @return
*/
@Override
public Result findArticleById(Long articleId)
{
return this.blogsFeignServiceClient.findArticleById(articleId);
}
/**
* 插入
*
* @param xiaoxiaoArticles
* @return
*/
@Override
public Result insert(XiaoxiaoArticles xiaoxiaoArticles)
{
return this.blogsFeignServiceClient.insert(xiaoxiaoArticles);
}
/**
* 修改
*
* @param xiaoxiaoArticles
* @return
*/
@Override
public Result update(XiaoxiaoArticles xiaoxiaoArticles)
{
return this.blogsFeignServiceClient.update(xiaoxiaoArticles);
}
/**
* 根据标题,分类,是否推荐查询信息
*
* @param page
* @param rows
* @param xiaoxiaoArticles
* @return
*/
@Override
public Result findArticleByTitleOrSorts(Integer page, Integer rows, XiaoxiaoArticles xiaoxiaoArticles)
{
return this.blogsFeignServiceClient.findArticleByTitleOrSorts(page, rows, xiaoxiaoArticles);
}
/**
* 修改推荐信息
*
* @param articleId
* @param articleRecommend
* @return
*/
@Override
public Result updateRecommend(Long articleId, String articleRecommend)
{
return this.blogsFeignServiceClient.updateRecommend(articleId, articleRecommend);
}
/**
* https://xiaoxiao-xiaoxiao.oss-cn-beijing.aliyuncs.com/xiaoxiao-and-me/cdb43b35a1204d739bab09e84101f6eb.jpg
*
* https://xiaoxiao-xiaoxiao.oss-cn-beijing.aliyuncs.comxiaoxiao-and-me/4d70a38edd344a4598c8cd4c2de34ee1.jpg
* 上传文件
* @param file
* @return
*/
@Override
public UploadResult upload(MultipartFile file) throws IOException
{
String fileName = null;
try
{
fileName = UploadOSSUtils.upload(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET, BUCKETNAME,ARTICLE_FILE_PATH, file.getInputStream());
Result result = this.blogsFeignServiceClient.insert(new XiaoxiaoImg("", this.ENDPOINT + fileName, new Date(), ""));
if(result != null && result.getCode() == StatusCode.OK){
return UploadResult.ok(StatusCode.UPLOADSUCCESS, "", this.REQUEST_HEAD+ARTICLE_FILE_PATH+fileName);
}
} catch (Exception e)
{
e.printStackTrace();
}
return UploadResult.error(StatusCode.UPLOADERROR,"","");
}
}
|
public class BankCharges
{
private double fee = 10.0;
private double lowBalance = 400.0;
private double lowBalanceFee = 15.0;
private int checksWritten;
private double balance;
public BankCharges(double b, int c)
{
balance = b;
checksWritten = c;
}
public void setChecksWritten(int c)
{
checksWritten = c;
}
public void setBalance(double b)
{
balance = b;
}
public int getChecksWritten()
{
return checksWritten;
}
public double getBalance()
{
return balance;
}
public double getFees()
{
double fees = fee;
if(balance < lowBalance)
{
fees += lowBalanceFee;
}
if(checksWritten >= 60)
{
fees += (checksWritten * 0.04);
}
else if(checksWritten >= 40)
{
fees += (checksWritten * .06);
}
else if(checksWritten >= 20)
{
fees += (checksWritten * 0.08);
}
else
{
fees += (checksWritten * 0.1);
}
return fees;
}
}
|
/*
* Copyright 2018 The Apache Software 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.
*
* Contributors:
* Damon Brown
*/
package org.nuxeo.ecm.maintenance.operation;
import org.nuxeo.ecm.automation.core.Constants;
import org.nuxeo.ecm.automation.core.annotations.Operation;
import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
import org.nuxeo.ecm.maintenance.MaintenanceStatus;
import org.nuxeo.ecm.maintenance.api.MaintenanceAdmin;
import org.nuxeo.runtime.api.Framework;
/**
* Get the current maintenance status of the system.
*
* @since 9.10
*/
@Operation(id = MaintenanceStatusOp.ID, category = Constants.CAT_SERVICES, label = "Get Maintenance Status", description = "Retrieve the maintenance status.")
public class MaintenanceStatusOp {
public static final String ID = "System.MaintenanceStatus";
@OperationMethod
public MaintenanceStatus run() {
MaintenanceAdmin admin = Framework.getService(MaintenanceAdmin.class);
MaintenanceStatus status = admin.getStatus();
return status;
}
}
|
package exceptions;
// Referenced classes of package exceptions:
// OberonException
public class LexicalException extends OberonException
{
public LexicalException()
{
this("Lexical error.");
}
public LexicalException(String s)
{
super("LexicalException : \n" + s);
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.ShapeDrawable.ShaderFactory;
class SnsHeader$3 extends ShaderFactory {
final /* synthetic */ SnsHeader nWo;
final /* synthetic */ int nWr;
SnsHeader$3(SnsHeader snsHeader, int i) {
this.nWo = snsHeader;
this.nWr = i;
}
public final Shader resize(int i, int i2) {
return new LinearGradient(0.0f, 0.0f, 0.0f, (float) i2, new int[]{this.nWr, 0}, new float[]{0.0f, 1.0f}, TileMode.CLAMP);
}
}
|
package com.bozhong.lhdataaccess.restful.resources.baseController;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bozhong.common.util.ResultMessageBuilder;
import com.bozhong.lhdataaccess.application.Context;
import com.bozhong.lhdataaccess.client.common.constants.ServiceErrorEnum;
/**
* @author bin
* @create 2018-04-28 下午5:24
**/
public class BaseController {
private static final String DEFAULE_DATA_FOMATE = "yyyy-MM-dd HH:mm:ss";
protected String toJSON(Context context) {
if(context.getResult().isSuccess()){
return ResultMessageBuilder.build(context.getResult().getModule()).toJSONString();
}else{
ServiceErrorEnum serviceErrorEnum= context.getResult().getServiceError();
return ResultMessageBuilder.build(false,serviceErrorEnum.getName(),serviceErrorEnum.getErrMsg()).toJSONString();
}
}
/**
* 根据日期格式格式化返回数据
* @param context
* @param dateFormat
* @return
*/
protected String toJSONByDateFormat(Context context, String dateFormat) {
if(context.getResult().isSuccess()){
return ResultMessageBuilder.build(context.getResult().getModule()).toJSONString(dateFormat);
}else{
ServiceErrorEnum serviceErrorEnum= context.getResult().getServiceError();
return ResultMessageBuilder.build(false,serviceErrorEnum.getName(),serviceErrorEnum.getErrMsg()).toJSONString();
}
}
/**
* 根据日期格式格式化返回数据
* @param context
* @return
*/
protected String toJSONByDateFormat(Context context) {
return toJSONByDateFormat(context,DEFAULE_DATA_FOMATE);
}
/**
* 返回实体类无参数时 带 null
* @param context
* @return
*/
protected String toJSONByNull(Context context){
return JSONObject.toJSONStringWithDateFormat(ResultMessageBuilder.build(context.getResult().getModule()),"yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue);
}
}
|
/**
* @Title: ExpStoreInfo.java
* @package com.rofour.baseball.idl.storecenter.service
* @Project: axp-idl
* @Description: (用一句话描述该文件做什么)
* @author heyi
* @date 2016年4月8日 下午3:48:24
* @version V1.0
* ──────────────────────────────────
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.controller.model.store;
import java.io.Serializable;
import java.util.List;
/**
* @ClassName: ExpStoreInfo
* @Description: TODO(逻辑层快递站点实体)
* @author heyi
* @date 2016年4月8日 下午3:48:24
*
*/
public class ExpStoreInfo implements Serializable{
private static final long serialVersionUID = -3248954995789718518L;
/**
* 快递站点编号
*/
private Long storeId;
/**
* 快递站点编码
*/
private String storeCode;
/**
* 快递站点名称
*/
private String storeName;
/**
* 联系地址
*/
private String location;
/**
* 状态 0 禁用 1启用
*/
private Integer status;
/**
* 类型 1 快递站点 2 门店
*/
private Byte type;
/**
* 手机号
*/
private String phone;
/**
* 负责人名称
*/
private String supervisorName;
/**
* 物流商名称(多个逗号隔开)
*/
private String ecName;
/**
* 物流商编码(多个逗号隔开)
*/
private String ecGcode;
/**
* 学校编号,多个逗号隔开
*/
private String colCode;
/**
* 学校名称,多个逗号隔开
*/
private String colName;
/**
* 是否删除,0:存在 1:删除
*/
private Integer beDeleted;
/**
* 快递公司编码集合
*/
private List<Long> ecList;
/**
* 学校编码集合
*/
private List<Long> colList;
/**
* 默认物流商编码
*/
private Long defaultECId;
/**
* 默认物流商名称
*/
private String defaultECName;
/**
* 派件模式 0 关闭 1 开启
*/
private Byte packetModeMgr;
/**
* 寄件模式 0 关闭 1 开启
*/
private Byte packetModeSend;
/**
* 打烊模式 0 关闭 1 开启
* wuhongxue 2016.9.18增加打烊状态字段
*/
private Byte closeMode;
public Byte getPacketModeSend() {
return packetModeSend;
}
public void setPacketModeSend(Byte packetModeSend) {
this.packetModeSend = packetModeSend;
}
public ExpStoreInfo() {
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Byte getType() {
return type;
}
public void setType(Byte type) {
this.type = type;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSupervisorName() {
return supervisorName;
}
public void setSupervisorName(String supervisorName) {
this.supervisorName = supervisorName;
}
public String getEcName() {
return ecName;
}
public void setEcName(String ecName) {
this.ecName = ecName;
}
public String getEcGcode() {
return ecGcode;
}
public void setEcGcode(String ecGcode) {
this.ecGcode = ecGcode;
}
public Long getStoreId() {
return storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
public String getStoreCode() {
return storeCode;
}
public void setStoreCode(String storeCode) {
this.storeCode = storeCode;
}
public String getStoreName() {
return storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
public List<Long> getEcList() {
return ecList;
}
public void setEcList(List<Long> ecList) {
this.ecList = ecList;
}
public Integer getBeDeleted() {
return beDeleted;
}
public void setBeDeleted(Integer beDeleted) {
this.beDeleted = beDeleted;
}
public List<Long> getColList() {
return colList;
}
public void setColList(List<Long> colList) {
this.colList = colList;
}
public String getColCode() {
return colCode;
}
public void setColCode(String colCode) {
this.colCode = colCode;
}
public String getColName() {
return colName;
}
public void setColName(String colName) {
this.colName = colName;
}
public Long getDefaultECId() {
return defaultECId;
}
public void setDefaultECId(Long defaultECId) {
this.defaultECId = defaultECId;
}
public String getDefaultECName() {
return defaultECName;
}
public void setDefaultECName(String defaultECName) {
this.defaultECName = defaultECName;
}
public Byte getPacketModeMgr() {
return packetModeMgr;
}
public void setPacketModeMgr(Byte packetModeMgr) {
this.packetModeMgr = packetModeMgr;
}
public Byte getCloseMode() {
return closeMode;
}
public void setCloseMode(Byte closeMode) {
this.closeMode = closeMode;
}
}
|
package com.onplan.adviser.predicate;
import com.google.common.collect.ImmutableList;
import com.onplan.adviser.AdviserPredicateInfo;
import com.onplan.adviser.TemplateInfo;
import com.onplan.adviser.TemplateMetaData;
import static com.google.common.base.Preconditions.checkNotNull;
public final class AdviserPredicateUtil {
public static TemplateInfo createAdviserPredicateTemplateInfo(
Class<? extends AdviserPredicate> clazz) {
checkNotNull(clazz);
TemplateMetaData adviserTemplate = clazz.getAnnotation(TemplateMetaData.class);
checkNotNull(adviserTemplate, String.format(
"Adviser predicate [%s] does not implement the annotation [%s].",
clazz.getName(),
TemplateMetaData.class.getName()));
return new TemplateInfo(
adviserTemplate.displayName(),
clazz.getName(),
ImmutableList.copyOf(adviserTemplate.availableParameters()));
}
public static AdviserPredicateInfo createAdviserPredicateInfo(
final AdviserPredicate adviserPredicate) {
checkNotNull(adviserPredicate);
TemplateInfo templateInfo = createAdviserPredicateTemplateInfo(adviserPredicate.getClass());
return new AdviserPredicateInfo(
templateInfo.getDisplayName(),
templateInfo.getClassName(),
templateInfo.getAvailableParameters(),
adviserPredicate.getParametersCopy());
}
}
|
package com.example.inputclient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
private TabHost mTabHost=null;
public final static String TAG = "InputTest";
public static final int REQUEST_TO_ENABLE_BT = 100;
private BluetoothAdapter mBluetoothAdapter;
private UUID MY_UUID = UUID
.fromString("D04E3068-E15B-4482-8306-4CABFA1726E7");
private final static String CBT_SERVER_DEVICE_NAME = "Galaxy Nexus 2";
private BluetoothSocket sock;
private ArrayList<EventData> queue=new ArrayList<MainActivity.EventData>();
private int width;
private int height;
private class EventData{
int type;
float x;
float y;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display=((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
width=display.getWidth();
height=display.getHeight();
Log.d(TAG, "width : "+width+" height :"+height);
/* mTabHost=(TabHost)findViewById(R.id.tabhost);
mTabHost.setup();
TabHost.OnTabChangeListener tabChangeListener = new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
FragmentManager fm = getSupportFragmentManager();
OneFragment one = (OneFragment) fm.findFragmentByTag("TAB1");
TwoFragment two = (TwoFragment) fm.findFragmentByTag("TAB2");
ThreeFragment three=(ThreeFragment) fm.findFragmentByTag("TAB3");
FragmentTransaction ft = fm.beginTransaction();
if(one!=null)
ft.detach(one);
if(two !=null)
ft.detach(two);
if(three !=null)
ft.detach(three);
if(tabId.equalsIgnoreCase("TAB1")){
if(one==null){
ft.add(R.id.content,new OneFragment(), "TAB1");
}else{
// ft.replace(R.id.content,one);
ft.attach(one);
}
}else if(tabId.equalsIgnoreCase("TAB2")){
if(two==null){
ft.add(R.id.content,new TwoFragment(), "TAB2");
}else{
//ft.replace(R.id.content, two);
ft.attach(two);
}
}else{
if(three==null){
ft.add(R.id.content,new ThreeFragment(), "TAB3");
}else{
ft.replace(R.id.content, three);
}
}
ft.commit();
fm.executePendingTransactions();
}
};
mTabHost.setOnTabChangedListener(tabChangeListener);
TabSpec ts1 = mTabHost.newTabSpec("TAB1");
ts1.setIndicator("tab1");
ts1.setContent(new DummyTabContent(getBaseContext()));
mTabHost.addTab(ts1);
TabSpec ts2 = mTabHost.newTabSpec("TAB2");
ts2.setIndicator("tab2");
ts2.setContent(new DummyTabContent(getBaseContext()));
mTabHost.addTab(ts2);
TabSpec ts3 = mTabHost.newTabSpec("TAB3");
ts3.setIndicator("tab3");
ts3.setContent(new DummyTabContent(getBaseContext()));
mTabHost.addTab(ts3);
mTabHost.setCurrentTab(0);*/
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.v(TAG, "Device does not support Bluetooth");
} else {
if (!mBluetoothAdapter.isEnabled()) {
Log.v(TAG, "Bluetooth supported but not enabled");
Toast.makeText(MainActivity.this,
"Bluetooth supported but not enabled",
Toast.LENGTH_LONG).show();
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_TO_ENABLE_BT);
} else {
Log.v(TAG, "Bluetooth supported and enabled");
// discover new Bluetooth devices
discoverBluetoothDevices();
// find devices that have been paired
getBondedDevices();
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
super.onTouchEvent(event);
EventData data=new EventData();
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
data.type=0;
break;
case MotionEvent.ACTION_MOVE:
data.type=1;
break;
case MotionEvent.ACTION_UP:
data.type=2;
break;
}
data.x=event.getX()/width*720;
data.y=event.getY()/height*1280;
Log.d(TAG, "touch x:"+data.x + "y:"+data.y);
queue.add(data);
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TO_ENABLE_BT) {
discoverBluetoothDevices();
getBondedDevices();
return;
}
}
private void discoverBluetoothDevices() {
// register a BroadcastReceiver for the ACTION_FOUND Intent
// to receive info about each device discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mBluetoothAdapter.startDiscovery();
}
// for each device discovered, the broadcast info is received
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.v(TAG, "BroadcastReceiver on Receive - " + device.getName()
+ ": " + device.getAddress());
String name = device.getName();
// found another Android device of mine and start communication
if (name != null
&& name.equalsIgnoreCase(CBT_SERVER_DEVICE_NAME)) {
new ConnectThread(device).start();
}
}
}
};
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
// bonded devices are those that have already paired with the current device
// sometime in the past (and have not been unpaired)
private void getBondedDevices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.v(TAG, "bonded device - " + device.getName() + ": "
+ device.getAddress());
if (device.getName().equalsIgnoreCase(CBT_SERVER_DEVICE_NAME)) {
Log.d(TAG, CBT_SERVER_DEVICE_NAME);
new ConnectThread(device).start();
break;
}
}
} else {
Toast.makeText(MainActivity.this, "No bonded devices",
Toast.LENGTH_LONG).show();
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
private BluetoothDevice device;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
this.device=device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server
// code
Log.v(TAG, "before createRfcommSocketToServiceRecord");
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
Log.v(TAG, "after createRfcommSocketToServiceRecord");
} catch (IOException e) {
Log.v(TAG,
" createRfcommSocketToServiceRecord exception: "
+ e.getMessage());
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "ready to connect");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
if(!mmSocket.isConnected())
mmSocket.connect();
} catch (IOException e) {
Log.v(TAG, e.getMessage());
try {
mmSocket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
mmSocket.connect();
} catch (Exception ex) {
Log.v(TAG, ex.getMessage());
}
//return;
}
Log.d(TAG, "success to connect");
sock = mmSocket;
manageConnectedSocket(sock);
}
private void manageConnectedSocket(BluetoothSocket socket) {
DataOutputStream out=null;
OutputStream mOutStream = null;
try {
mOutStream = socket.getOutputStream();
out=new DataOutputStream(mOutStream);
} catch (IOException e1) {
// TODO Auto-generated catch block
Log.d(TAG, "cant get stream");
e1.printStackTrace();
}
/* byte[] b=new byte[2];
b[0]=0;
b[1]=1;
try {
Log.d(TAG, "send data in Bluetooth");
for(int i=0;i<3;i++)
{
mOutStream.write(b);
mOutStream.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
while(true)
{
while(!queue.isEmpty())
{
EventData data=queue.remove(0);
Log.d(TAG, "send x:"+data.x+" y:"+data.y);
try {
out.writeInt(data.type);
out.writeFloat(data.x);
out.writeFloat(data.y);
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
|
class Point {
int x,y;
}
Point p = new Point();
p.x == 0
attribútum nullaszerű értékkel inicializálva
egész: 0
lebegőp. : 0.0
boolean: false
char: \u0000
referencia: null
void m(){ // forditasi hiba (statikus szemantikai szabaly megsertese)
Point p;
System.out.println(p.x);
}
void m(){ // minden ok
Point p = new Point();
System.out.println(p.x);
}
void m(){ // futasi hiba: NullPointerException (dinamikus szemantikai szabaly megsertese)
Point p = null;
System.out.println(p.x);
}
void m( Point p ){
System.out.println(p.x);
}
m(new Point()) m(null)
public class Person {
String name;
int age;
}
new Person().age == 0
new Person().name == null
// dokumentacios megjegyzes kovetkezik...
/**
Mutable implementacio.
Tipusinvarians: age >= 0 & name != null
*/
// a tipusinvarianst a muveletek megorzik
public class Person {
private String name;
private int age;
public Person( String name, int age ){
// elofeltetel ellenorzese
if( name == null ) throw new IllegalArgumentException("...");
if( age < 0 ) throw new IllegalArgumentException("...");
this.name = name;
this.age = age;
}
public void setAge( int age ){
if( age < 0 ) throw new IllegalArgumentException("...");
this.age = age;
}
public void setName(){
if( name == null ) throw new IllegalArgumentException("...");
this.name = name;
}
public int getAge(){ return age; }
public String getName(){ return name; }
}
Person pityu = new Person("Kis Istvan", 24);
pityu.setName("Kis István");
// imperativ stilus
private void muvelet( int parameter ){
assert parameter != 0;
...
}
/**
Immutable implementacio.
A Person objektumok belso allapota nem valtozhat meg a letrehozas
utan.
Tipusinvarians: age >= 0 & name != null
*/
public class Person {
private final String name;
private final int age;
public Person( String name, int age ){
// elofeltetel ellenorzese
if( name == null ) throw new IllegalArgumentException("...");
if( age < 0 ) throw new IllegalArgumentException("...");
this.name = name;
this.age = age;
}
public int getAge(){ return age; }
public String getName(){ return name; }
}
Person pityu = new Person("Kis Istvan", 24);
pityu = new Person("Kis István",pityu.getAge());
// funkcionalis stilus
public class Point {
private final int x,y;
public Point( int x, int y ){
this.x = x;
this.y = y;
}
public int getX(){ return x; }
public int getY(){ return y; }
}
public class Point {
private final int[] coords;
public Point( int x, int y ){
coords = new int[]{x, y};
}
public int getX(){ return coords[0]; }
public int getY(){ return coords[1]; }
public int[] coords(){ return coords; }
}
Point p = new Point(1,1);
int[] c = p.coords();
c[0] = 5;
p.getX() == 5
a coords() metódus engedi kiszökni a Point belső állapotát
amin keresztül direkt manipulálható kívülről a belső állapot
sérti az OOP elveket (private)
itt most az immutable designt is tönkreteszi
public class Point {
private final int[] coords;
public Point( int x, int y ){
coords = new int[]{x, y};
}
public int getX(){ return coords[0]; }
public int getY(){ return coords[1]; }
public int[] coords(){ return new int[]{coords[0],coords[1]}; }
// masolatot adok vissza, raadasul erdemes mely masolatot csinalni
// HF: lehet ezen gyengiteni?
}
Point p = new Point(1,3);
Point q = p;
elettartam vege: ha egy referencian keresztul sem erheto el az objektum
garbage collector begyujtheti
tömb: egy objektum, a heapen tárolódik
tömb típus: speciális "osztály", speciális szintaxissal
|
package cn.wycclub.dto;
/**
* @author WuYuchen
* @Description 管理员订单信息
* @Date 2018-03-15 14:19
*/
public class AdminOrder extends Order {
protected String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
|
public class StringTest {
public static void main(String[] args) {
String b=new String("venkat");
String b1=b.intern();
System.out.println("b==b1"+ (b==b1));
System.out.println(b.equals(b1));
System.out.println(b.hashCode() + " "+ b1.hashCode());
String s="venkat";
String s1="venkat";
System.out.println("s==s1 "+ (s==s1));
System.out.println(s.hashCode() + " "+ s1.hashCode());
System.out.println(System.console());
}
}
|
public class Application
{
public static void main( String[] args )
{
Verre verre = new Verre( 50, 300 );
int volumeVide = verre.vider( 25 );
System.out.println( volumeVide + " cl sont tombés du verre" );
volumeVide = verre.vider( 50 );
System.out.println( volumeVide + " cl sont tombés du verre" );
}
}
|
package thsst.calvis.configuration.model.engine;
import thsst.calvis.editor.model.Flag;
import java.util.ArrayList;
public class EFlags extends Register {
private ArrayList<Flag> flags;
public EFlags() {
this.value = "00000002";
buildFlags();
initializeValue();
}
@Override
public void initializeValue() {
this.value = "00000002";
for ( Flag flag : flags )
flag.setValue("0");
}
public void buildFlags() {
this.flags = new ArrayList<>();
this.flags.add(new Flag("Carry", getCarryFlag()));
this.flags.add(new Flag("Parity", getParityFlag()));
this.flags.add(new Flag("Auxiliary", getAuxiliaryFlag()));
this.flags.add(new Flag("Zero", getZeroFlag()));
this.flags.add(new Flag("Sign", getSignFlag()));
this.flags.add(new Flag("Overflow", getOverflowFlag()));
this.flags.add(new Flag("Interrupt", getInterruptFlag()));
this.flags.add(new Flag("Direction", getDirectionFlag()));
}
public void refreshFlags() {
for ( int i = 0; i < flags.size(); i++ ) {
String flagName = flags.get(i).getName();
switch ( flagName ) {
case "Carry":
flags.get(i).setValue(getCarryFlag());
break;
case "Sign":
flags.get(i).setValue(getSignFlag());
break;
case "Overflow":
flags.get(i).setValue(getOverflowFlag());
break;
case "Zero":
flags.get(i).setValue(getZeroFlag());
break;
case "Parity":
flags.get(i).setValue(getParityFlag());
break;
case "Auxiliary":
flags.get(i).setValue(getAuxiliaryFlag());
break;
case "Direction":
flags.get(i).setValue(getDirectionFlag());
break;
case "Interrupt":
flags.get(i).setValue(getInterruptFlag());
break;
default:
}
}
}
public ArrayList<Flag> getFlagList() {
return this.flags;
}
public char getFlagIndex(int index) {
int hex = Integer.parseInt(this.value, 16);
String val = Integer.toBinaryString(hex);
int missingZeroes = 32 - val.length();
//zero extend
for ( int k = 0; k < missingZeroes; k++ ) {
val = "0" + val;
}
return val.charAt(32 - 1 - index);
}
public void setFlagIndex(int index, String a) {
if ( a.equals("0") || a.equals("1") ) {
int hex = Integer.parseInt(this.value, 16);
String val = Integer.toBinaryString(hex);
int missingZeroes = 32 - val.length();
//zero extend
for ( int k = 0; k < missingZeroes; k++ ) {
val = "0" + val;
}
char[] extended = val.toCharArray();
extended[32 - 1 - index] = a.charAt(0);
val = new String(extended);
String hexValue = Integer.toHexString(Integer.parseInt(val, 2));
int zeroExtendHexValue = 8 - hexValue.length();
//zero extend
for ( int k = 0; k < zeroExtendHexValue; k++ ) {
hexValue = "0" + hexValue;
}
this.value = hexValue.toUpperCase();
} else {
}
}
public String getCarryFlag() {
return getFlagIndex(0) + "";
}
public String getParityFlag() {
return getFlagIndex(2) + "";
}
public String getAuxiliaryFlag() {
return getFlagIndex(4) + "";
}
public String getZeroFlag() {
return getFlagIndex(6) + "";
}
public String getSignFlag() {
return getFlagIndex(7) + "";
}
public String getOverflowFlag() {
return getFlagIndex(11) + "";
}
public String getDirectionFlag() {
return getFlagIndex(10) + "";
}
public String getInterruptFlag() {
return getFlagIndex(9) + "";
}
public void setCarryFlag(String value) {
setFlagIndex(0, value);
setFlag("Carry", value);
}
public void setParityFlag(String value) {
setFlagIndex(2, value);
setFlag("Parity", value);
}
public void setAuxiliaryFlag(String value) {
setFlagIndex(4, value);
setFlag("Auxiliary", value);
}
public void setZeroFlag(String value) {
setFlagIndex(6, value);
setFlag("Zero", value);
}
public void setSignFlag(String value) {
setFlagIndex(7, value);
setFlag("Sign", value);
}
public void setOverflowFlag(String value) {
setFlagIndex(11, value);
setFlag("Overflow", value);
}
public void setDirectionFlag(String value) {
setFlagIndex(10, value);
setFlag("Direction", value);
}
public void setInterruptFlag(String value) {
setFlagIndex(9, value);
setFlag("Interrupt", value);
}
private void setFlag(String name, String value) {
for ( int i = 0; i < flags.size(); i++ ) {
if ( flags.get(i).getName().equals(name) ) {
flags.get(i).setValue(value);
break;
}
}
}
}
|
package com.runningphotos.ui;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by Tensa on 06.02.2016.
*/
@Controller
public class BasketController {
@RequestMapping(value = "/basket")
public ModelAndView getBasket(){
ModelAndView model = new ModelAndView("basket");
return model;
}
}
|
package com.github.morihara.transactional.sample.service;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;
import java.math.BigDecimal;
import java.util.Optional;
import java.util.UUID;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.github.morihara.transactional.sample.config.UpdateQuantityServiceTestConfig;
import com.github.morihara.transactional.sample.dao.QuantityDao;
import com.github.morihara.transactional.sample.dto.GoodsReceiptTrnDto;
import com.github.morihara.transactional.sample.dto.QuantityTrnDto;
import lombok.extern.slf4j.Slf4j;
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
UpdateQuantityServiceTestConfig.class
})
@Slf4j
public class UpdateQuantityServiceImplTest {
@Autowired
private QuantityDao quantityDao;
@Autowired
@Qualifier("updateQuantityServiceForCommit")
private UpdateQuantityService updateQuantityServiceForCommit;
@Autowired
@Qualifier("updateQuantityServiceForRollback")
private UpdateQuantityService updateQuantityServiceForRollback;
private static final String TEST_QUANTITY_CODE = "junit_test";
private static final QuantityTrnDto BASE_QUANTITY = QuantityTrnDto.builder()
.quantityCode(TEST_QUANTITY_CODE)
.quantity(BigDecimal.TEN)
.build();
@Before
public void setup() {
quantityDao.remove(TEST_QUANTITY_CODE);
quantityDao.insert(BASE_QUANTITY);
}
@Test
public void increaseQuantity_rollbackTest() {
GoodsReceiptTrnDto receiptDto = GoodsReceiptTrnDto.builder()
.goodsReceiptTrnId(UUID.randomUUID())
.quantity(BigDecimal.TEN)
.build();
try {
updateQuantityServiceForRollback.increaseQuantity("GOODS_RECEIPT", TEST_QUANTITY_CODE, receiptDto);
} catch (RuntimeException e) {
log.info("Catch Exception");
}
Optional<QuantityTrnDto> actual = quantityDao.getQuantity(TEST_QUANTITY_CODE);
if (!actual.isPresent()) {
log.error("quantity_trn_dto is gone");
fail();
}
assertThat(actual.get().getQuantity(), is(BASE_QUANTITY.getQuantity()));
}
@Test
public void increaseQuantity_commitTest() {
BigDecimal additionalQuantity = BigDecimal.TEN;
GoodsReceiptTrnDto receiptDto = GoodsReceiptTrnDto.builder()
.goodsReceiptTrnId(UUID.randomUUID())
.quantity(additionalQuantity)
.build();
BigDecimal expectedQuantity = BASE_QUANTITY.getQuantity().add(additionalQuantity);
try {
updateQuantityServiceForCommit.increaseQuantity("GOODS_RECEIPT", TEST_QUANTITY_CODE, receiptDto);
} catch (RuntimeException e) {
log.error("Catch Exception", e);
fail();
}
Optional<QuantityTrnDto> actual = quantityDao.getQuantity(TEST_QUANTITY_CODE);
if (!actual.isPresent()) {
log.error("quantity_trn_dto is gone");
fail();
}
assertThat(actual.get().getQuantity(), is(expectedQuantity));
}
}
|
package com.keytop.changeicon;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private PackageManager mPm;
private ComponentName mDefault;
private ComponentName mAfter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDefault = getComponentName();
mAfter = new ComponentName(
getBaseContext(),
"com.keytop.changeicon.Main2Activity");
mPm = getApplicationContext().getPackageManager();
}
/**
* 替换图标名称
*/
public void btnChange(View v){
changeIcon65(mDefault, mAfter);
}
/**
* 换回默认图标名称
*/
public void btnBack(View v){
changeIcon65(mAfter, mDefault);
}
/**
* 隐藏桌面图标名称
* todo 记得测试前先安装hiddenapp
*/
public void btnHidden(View v){
Intent intent = new Intent();
ComponentName cn = new ComponentName("com.keytop.hiddenapp",//即将启动app的包名
"com.keytop.hiddenapp.MainActivity");//即将启动app的隐式意图 scheme + "." + host
intent.setComponent(cn);
Uri uri = Uri.parse("com.keytop.hiddenapp.MainActivity");//即将启动app的隐式意图scheme + "." + host
intent.setData(uri);
startActivity(intent);
}
public void changeIcon65(ComponentName disable, ComponentName enable) {
disableComponent(this, disable);
enableComponent(this, enable);
}
/**
* 启用组件 *
* @param componentName
* 重要方法
*/
private void enableComponent(Activity activity, ComponentName componentName) {
PackageManager pm = activity.getPackageManager();
int state = pm.getComponentEnabledSetting(componentName);
if (PackageManager.COMPONENT_ENABLED_STATE_ENABLED == state) {
//已经启用
return;
}
pm.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
/**
* 禁用组件 *
* @param componentName
* 重要方法
*/
private void disableComponent(Activity activity, ComponentName componentName) {
PackageManager pm = activity.getPackageManager();
int state = pm.getComponentEnabledSetting(componentName);
if (PackageManager.COMPONENT_ENABLED_STATE_DISABLED == state) {
//已经禁用
return;
}
pm.setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
|
package com.abraham.dj;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.abraham.dj.model.Department;
import com.abraham.dj.service.IDepartmentService;
import net.sf.json.JSONObject;
/**
* Handles requests for the application home page.
*/
@Controller
@RequestMapping(value="/department")
public class DepartmentController {
private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);
@Resource
private IDepartmentService departmentService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home2";
}
@ResponseBody
@RequestMapping(value="delete",method= RequestMethod.POST)
public JSONObject delete(Department department){
JSONObject result = new JSONObject();
boolean flag = departmentService.delete(department);
result.put("flag", flag);
return result;
}
@ResponseBody
@RequestMapping(value="/deleteMore",method = RequestMethod.POST)
public void deleteMore(int[] ids){
for (int id:ids) {
Department department = new Department();
department.setId(id);
departmentService.delete(department);
}
}
@ResponseBody
@RequestMapping(value = "/save", method = RequestMethod.GET)
public JSONObject save(Department department) {
JSONObject result = new JSONObject();
boolean flag = false;
if(department.getId() > 0)
flag = departmentService.save(department);
else {
flag = departmentService.update(department);
}
result.put("flag", flag);
return result;
}
@ResponseBody
@RequestMapping(value="/get",method= RequestMethod.GET)
public JSONObject get(Department department){
JSONObject result = new JSONObject();
Department department2 = (Department)departmentService.get(department);
result.put("admin", department2);
return result;
}
@RequestMapping(value = "/list", method = RequestMethod.GET)
public @ResponseBody JSONObject list() {
JSONObject result = new JSONObject();
@SuppressWarnings("unchecked")
List<Department> list = (List<Department>) departmentService.getAll();
result.put("array", list);
return result;
}
}
|
/**
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.dao.manager.bean;
import java.io.Serializable;
/**
* @ClassName: MsgConfigBean
* @Description: 消息配置表实体类
* @author xzy
* @date 2016年3月28日 上午10:04:09
*
*/
public class MsgConfigBean implements Serializable {
private static final long serialVersionUID = -8272812972151083371L;
private Long messageConfigId;
/**
* 消息类型
*/
private String messageTypeId;
/**
* 发送类型
*/
private String sendTypeId;
/**
* 等级
*/
private Byte level;
/**
* 是否及时发送
*/
private Byte beImmediateSend;
/**
* 最大长度
*/
private Integer maxLength;
/**
* 是否启用
*/
private Byte beEnabled;
/**
* 发送角色
*/
private Long sendRoleId;
/**
* 扩展码
*/
private String extendCode;
public MsgConfigBean(Long messageConfigId, String messageTypeId, String sendTypeId, Byte level,
Byte beImmediateSend, Integer maxLength, Byte beEnabled, Long sendRoleId, String extendCode) {
this.messageConfigId = messageConfigId;
this.messageTypeId = messageTypeId;
this.sendTypeId = sendTypeId;
this.level = level;
this.beImmediateSend = beImmediateSend;
this.maxLength = maxLength;
this.beEnabled = beEnabled;
this.sendRoleId = sendRoleId;
this.extendCode = extendCode;
}
public MsgConfigBean() {
super();
}
public Long getMessageConfigId() {
return messageConfigId;
}
public void setMessageConfigId(Long messageConfigId) {
this.messageConfigId = messageConfigId;
}
public String getMessageTypeId() {
return messageTypeId;
}
public void setMessageTypeId(String messageTypeId) {
this.messageTypeId = messageTypeId;
}
public String getSendTypeId() {
return sendTypeId;
}
public void setSendTypeId(String sendTypeId) {
this.sendTypeId = sendTypeId;
}
public Byte getLevel() {
return level;
}
public void setLevel(Byte level) {
this.level = level;
}
public Byte getBeImmediateSend() {
return beImmediateSend;
}
public void setBeImmediateSend(Byte beImmediateSend) {
this.beImmediateSend = beImmediateSend;
}
public Integer getMaxLength() {
return maxLength;
}
public void setMaxLength(Integer maxLength) {
this.maxLength = maxLength;
}
public Byte getBeEnabled() {
return beEnabled;
}
public void setBeEnabled(Byte beEnabled) {
this.beEnabled = beEnabled;
}
public Long getSendRoleId() {
return sendRoleId;
}
public void setSendRoleId(Long sendRoleId) {
this.sendRoleId = sendRoleId;
}
public String getExtendCode() {
return extendCode;
}
public void setExtendCode(String extendCode) {
this.extendCode = extendCode == null ? null : extendCode.trim();
}
}
|
/**
* Represents an Athlete that can play sports at the Olympics!
*
* @author Confused Coder
* @version 1.0
*/
public class Athlete {
protected int hunger;
protected String name;
protected boolean isACheater;
/**
* Public constructor.
*
* @param name the name of the athlete.
* @param sport the sport the athlete plays.
* @param serveSpeed the tennis serve speed of the athlete.
* @param canScoreGoal whether or not this athlete can score a soccer goal.
* @param javelinDamage how much damage this athlete's javelin inflcits.
* @param isACheater if this athlete is a cheater or not.
*/
public Athlete(String name, boolean isACheater) {
this.hunger = 0;
this.name = name;
this.isACheater = isACheater;
}
/**
* @return the hunger of this athlete.
*/
public int getHunger() {
return this.hunger;
}
/**
* @return the name of this athlete.
*/
public String getName() {
return this.name;
}
/**
* @return the tennis serve speed of this athlete.
*/
public int getServeSpeed() {
return this.serveSpeed;
}
/**
* @return whether or not this athlete is good at soccer.
*/
public boolean getCanScoreGoal() {
return this.canScoreGoal;
}
/**
* @return the damage this athlete's javelin inflicts.
*/
public double getJavelinDamage() {
return this.javelinDamage;
}
/**
* @return whether or not this athlete is a cheater.
*/
public boolean getIsACheater() {
return this.isACheater;
}
/**
* Has the athlete exercise. Will make the athlete hungry by increasing
* their hunger by the number of pushups.
*
* @param numberOfPushups the number of pushups the athlete should do.
*/
public void exercise(int numberOfPushups) {
System.out.println(String.format("%s does %d pushups and works up"
+ " quite an appetite!", getName(), numberOfPushups));
this.hunger += numberOfPushups;
}
/**
* Has the athlete eat some food to decrease their hunger by foodAmount.
*
* @param foodAmount how much to decrease hunger by.
* @param foodType the type of food the athlete eats.
*/
public void eat(int foodAmount, String foodType) {
System.out.println(String.format("%s eats %d of the %s!",
getName(), foodAmount, foodType));
this.hunger = Math.max(this.hunger - foodAmount, 0);
}
/**
* Has the athlete play something for their particular sport.
*/
public void play() {
System.out.println(String.format("%s can't play a sport!", getName()));
}
}
|
package top.piao888.hbgc.mapper;
import java.util.List;
import top.piao888.hbgc.domain.Report;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ReportMapper {
int deleteByPrimaryKey(Long rid);
int insert(Report record);
Report selectByPrimaryKey(Long rid);
List<Report> selectAll();
int updateByPrimaryKey(Report record);
}
|
package com.facebook.react.modules.fresco;
import com.facebook.common.e.a;
import com.facebook.drawee.a.a.c;
import com.facebook.imagepipeline.b.a.a;
import com.facebook.imagepipeline.e.h;
import com.facebook.imagepipeline.e.i;
import com.facebook.imagepipeline.n.ai;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.common.ModuleDataCleaner;
import com.facebook.react.modules.network.CookieJarContainer;
import com.facebook.react.modules.network.ForwardingCookieHandler;
import com.facebook.react.modules.network.OkHttpClientProvider;
import java.net.CookieHandler;
import java.util.HashSet;
import okhttp3.m;
import okhttp3.v;
import okhttp3.y;
@ReactModule(name = "FrescoModule")
public class FrescoModule extends ReactContextBaseJavaModule implements LifecycleEventListener, ModuleDataCleaner.Cleanable {
private static boolean sHasBeenInitialized;
private final boolean mClearOnDestroy;
private i mConfig;
public FrescoModule(ReactApplicationContext paramReactApplicationContext) {
this(paramReactApplicationContext, true, null);
}
public FrescoModule(ReactApplicationContext paramReactApplicationContext, boolean paramBoolean) {
this(paramReactApplicationContext, paramBoolean, null);
}
public FrescoModule(ReactApplicationContext paramReactApplicationContext, boolean paramBoolean, i parami) {
super(paramReactApplicationContext);
this.mClearOnDestroy = paramBoolean;
this.mConfig = parami;
}
private static i getDefaultConfig(ReactContext paramReactContext) {
return getDefaultConfigBuilder(paramReactContext).a();
}
public static i.a getDefaultConfigBuilder(ReactContext paramReactContext) {
HashSet<SystraceRequestListener> hashSet = new HashSet();
hashSet.add(new SystraceRequestListener());
y y = OkHttpClientProvider.createClient();
((CookieJarContainer)y.k).setCookieJar((m)new v((CookieHandler)new ForwardingCookieHandler(paramReactContext)));
return a.a(paramReactContext.getApplicationContext(), y).a((ai)new ReactOkHttpNetworkFetcher(y)).a(false).a(hashSet);
}
public static boolean hasBeenInitialized() {
return sHasBeenInitialized;
}
public void clearSensitiveData() {
h h = c.c();
h.a();
h.b.a();
h.c.a();
}
public String getName() {
return "FrescoModule";
}
public void initialize() {
super.initialize();
getReactApplicationContext().addLifecycleEventListener(this);
if (!hasBeenInitialized()) {
if (this.mConfig == null)
this.mConfig = getDefaultConfig((ReactContext)getReactApplicationContext());
c.a(getReactApplicationContext().getApplicationContext(), this.mConfig);
sHasBeenInitialized = true;
} else if (this.mConfig != null) {
a.b("ReactNative", "Fresco has already been initialized with a different config. The new Fresco configuration will be ignored!");
}
this.mConfig = null;
}
public void onHostDestroy() {
if (hasBeenInitialized() && this.mClearOnDestroy)
c.c().a();
}
public void onHostPause() {}
public void onHostResume() {}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\fresco\FrescoModule.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package ro.msg.cm.configuration;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
public class StartYearProperties {
@Value("${ro.msg.cm.university-year-start:10-01}")
private String startYearDate;
}
|
package main.java.model.calculator;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import static main.java.model.calculator.DataKey.*;
// Author: Alexander Larnemo Ask, Jonatan Bunis, Vegard Landrö, Mohamad Melhem, Alexander Larsson Vahlberg
// Responsibility: Calculator implementation.
// Used by: CalculatorFacade.
// Uses: Handles all calculations related to a property's installation cost of solar panels
final class InstallationCostCalculator implements Calculator {
InstallationCostCalculator() {
}
// Returns the InstallationCostCalculator output consisting of installation cost, subvented amount and subvented installation cost
@Override
public HashMap<DataKey, Double> calculate(HashMap<DataKey, Double> input) {
HashMap<DataKey, Double> data = new HashMap<>(input);
double availableSpace = input.get(AVAILABLE_SPACE);
double panelSize = input.get(PANEL_SIZE);
double panelPrice = input.get(PANEL_PRICE);
double installationCost = installationCost(availableSpace, panelSize, panelPrice);
double governmentSubvention = subventionAmount(installationCost);
double subventedInstallationCost = subventedCost(installationCost);
data.put(INSTALLATION_COST, installationCost);
data.put(GOVERNMENT_SUBVENTION, governmentSubvention);
data.put(SUBVENTED_INSTALLATION_COST, subventedInstallationCost);
return data;
}
// Calculates installationCost based on how many solar panels there's room for in the availableSpace of a property
private double installationCost(double availableSpace, double panelSize, double panelPrice) {
return Math.floor(availableSpace / panelSize) * panelPrice;
}
// Returns the subvented amount based on installationCost
private double subventionAmount(double installationCost) {
return installationCost * 0.2;
}
// Returns installationCost after subvention
private double subventedCost(double installationCost) {
return installationCost * 0.8;
}
@Override
public Set<DataKey> getKeysOfRequiredInput() {
return new HashSet<>(Arrays.asList(AVAILABLE_SPACE, PANEL_SIZE, PANEL_PRICE));
}
@Override
public Set<DataKey> getKeysOfOutput() {
return new HashSet<>(Arrays.asList(INSTALLATION_COST, GOVERNMENT_SUBVENTION, SUBVENTED_INSTALLATION_COST));
}
@Override
public String toString(){
return "InstallationCostCalculator";
}
}
|
package com.tfq.manager.web.model.response;
import lombok.Data;
/**
* 统计信息基类
*/
@Data
public class BaseStatisticsResponseVO {
/**
* 统计信息的类型
*/
private String type;
/**
* 统计信息的标题
*/
private String title;
}
|
package com.facebook.react.modules.debug;
import android.content.Context;
import android.widget.Toast;
import com.a;
import com.facebook.common.e.a;
import com.facebook.react.bridge.JSApplicationCausedNativeException;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.modules.core.ChoreographerCompat;
import com.facebook.react.modules.debug.interfaces.DeveloperSettings;
import java.util.Locale;
@ReactModule(name = "AnimationsDebugModule")
public class AnimationsDebugModule extends ReactContextBaseJavaModule {
private final DeveloperSettings mCatalystSettings;
private FpsDebugFrameCallback mFrameCallback;
public AnimationsDebugModule(ReactApplicationContext paramReactApplicationContext, DeveloperSettings paramDeveloperSettings) {
super(paramReactApplicationContext);
this.mCatalystSettings = paramDeveloperSettings;
}
public String getName() {
return "AnimationsDebugModule";
}
public void onCatalystInstanceDestroy() {
FpsDebugFrameCallback fpsDebugFrameCallback = this.mFrameCallback;
if (fpsDebugFrameCallback != null) {
fpsDebugFrameCallback.stop();
this.mFrameCallback = null;
}
}
@ReactMethod
public void startRecordingFps() {
DeveloperSettings developerSettings = this.mCatalystSettings;
if (developerSettings != null) {
if (!developerSettings.isAnimationFpsDebugEnabled())
return;
if (this.mFrameCallback == null) {
this.mFrameCallback = new FpsDebugFrameCallback(ChoreographerCompat.getInstance(), (ReactContext)getReactApplicationContext());
this.mFrameCallback.startAndRecordFpsAtEachFrame();
return;
}
throw new JSApplicationCausedNativeException("Already recording FPS!");
}
}
@ReactMethod
public void stopRecordingFps(double paramDouble) {
FpsDebugFrameCallback fpsDebugFrameCallback = this.mFrameCallback;
if (fpsDebugFrameCallback == null)
return;
fpsDebugFrameCallback.stop();
FpsDebugFrameCallback.FpsInfo fpsInfo = this.mFrameCallback.getFpsInfo((long)paramDouble);
if (fpsInfo == null) {
Toast.makeText((Context)getReactApplicationContext(), "Unable to get FPS info", 1);
} else {
String str2 = a.a(Locale.US, "FPS: %.2f, %d frames (%d expected)", new Object[] { Double.valueOf(fpsInfo.fps), Integer.valueOf(fpsInfo.totalFrames), Integer.valueOf(fpsInfo.totalExpectedFrames) });
String str3 = a.a(Locale.US, "JS FPS: %.2f, %d frames (%d expected)", new Object[] { Double.valueOf(fpsInfo.jsFps), Integer.valueOf(fpsInfo.totalJsFrames), Integer.valueOf(fpsInfo.totalExpectedFrames) });
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str2);
stringBuilder.append("\n");
stringBuilder.append(str3);
stringBuilder.append("\nTotal Time MS: ");
stringBuilder.append(a.a(Locale.US, "%d", new Object[] { Integer.valueOf(fpsInfo.totalTimeMs) }));
String str1 = stringBuilder.toString();
a.a("ReactNative", str1);
_lancet.com_ss_android_ugc_aweme_lancet_DesignBugFixLancet_show(Toast.makeText((Context)getReactApplicationContext(), str1, 1));
}
this.mFrameCallback = null;
}
class AnimationsDebugModule {}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\modules\debug\AnimationsDebugModule.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package cn.com.custom.widgetproject.activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.util.ArrayList;
import java.util.List;
import cn.com.custom.widgetproject.R;
import cn.com.custom.widgetproject.adapter.CompareShopAdapter;
import cn.com.custom.widgetproject.callback.ResponseCallback;
import cn.com.custom.widgetproject.callback.TanslationHttpCallback;
import cn.com.custom.widgetproject.constant.Constant;
import cn.com.custom.widgetproject.manager.ApiManager;
import cn.com.custom.widgetproject.manager.StorageManager;
import cn.com.custom.widgetproject.model.DetailItemModel;
import cn.com.custom.widgetproject.utils.DevUtil;
import cn.com.custom.widgetproject.utils.StringUtil;
import cn.com.custom.widgetproject.widget.CheckableView;
import cn.com.custom.widgetproject.widget.ErrorTipsView;
import cn.com.custom.widgetproject.widget.ImageViewpagerView;
import cn.com.custom.widgetproject.widget.LoadingBallView;
import cn.com.custom.widgetproject.widget.TranslateCheckableLayout;
import cn.com.custom.widgetproject.widget.XScrollView;
/**
* 产品详情画面
* Created by custom on 2016/6/14.
*/
public class ProductDetailAcitvity extends AppCompatActivity implements CheckableView.OnCheckedChangeListener, XScrollView.IXScrollViewListener {
private static final int REQUEST_DETAIL_FAIL = 0;
private static final int REQUEST_DETAIL_SUCCESE = 1;
private static final int REREFSH_DETAIL_SUCCESE = 2;
//图片切换控件
private ImageViewpagerView productGallaryView;
//比较商店列表控件
private ListView compareListview;
//产品详细控件
private TextView tvProductIntrduce;
//产品标题控件
private TextView tvProductTitle;
//产品详细的数据模型
private DetailItemModel prouctDetail;
//翻译控件
RadioButton translateRadioButton;
//加载小球的视图控件
LoadingBallView loadBallView;
//是否已经从中文翻译成了日文的标志位,默认是false
private boolean isChinaToJapan;
//是否已经从日文翻译成了中文的标志位,默认是false
private boolean isJanToChina;
//是否已经从保存翻译结果
private RelativeLayout topPanel;
private XScrollView mScrollView;
private LinearLayout detailLayout;
private TranslateCheckableLayout rl_translate;
private ErrorTipsView errorTipsView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
initFindView();
initBtnListner();
requestDetail();
}
/**
* 初始化按钮监听
*/
private void initBtnListner() {
findViewById(R.id.detail_iv_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProductDetailAcitvity.this.finish();
}
});
findViewById(R.id.detail_rl_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ProductDetailAcitvity.this.finish();
}
});
}
/**
* 初始化控件
*/
private void initFindView() {
topPanel = (RelativeLayout) findViewById(R.id.topPanel);
mScrollView = (XScrollView) findViewById(R.id.detail_scrollview);
loadBallView = (LoadingBallView) findViewById(R.id.detail_loadball);
mScrollView.setPullLoadEnable(false);
mScrollView.setPullRefreshEnable(true);
mScrollView.setIXScrollViewListener(this);
mScrollView.setActivity(this);
mScrollView.setFootVisily(true);
mScrollView.setFootViewGo(true);
View content = LayoutInflater.from(this).inflate(R.layout.xscrollview_content_detail, null);
initContentView(content);
mScrollView.setView(content);
}
/**
* 请求数据
*/
void requestDetail() {
ApiManager.getInstance(ProductDetailAcitvity.this).requestProductDeatilModel(getIntent().getStringExtra(Constant.PRODUCT_CODE), new ResponseCallback<DetailItemModel>() {
@Override
public void onFailure(Request request, Exception e) {
mHandler.sendEmptyMessage(REQUEST_DETAIL_FAIL);
}
@Override
public void onResponse(Response response, DetailItemModel model) {
if (model != null) {
Message message = mHandler.obtainMessage();
message.obj = model;
message.what = REQUEST_DETAIL_SUCCESE;
mHandler.sendMessage(message);
} else {
mHandler.sendEmptyMessage(REQUEST_DETAIL_FAIL);
}
}
});
}
/**
* 请求刷新数据
*/
void refreshDetail() {
detailLayout.setVisibility(View.INVISIBLE);
StorageManager.clearTranslationResult(this);
ApiManager.getInstance(ProductDetailAcitvity.this).requestProductDeatilModel(getIntent().getStringExtra(Constant.PRODUCT_CODE), new ResponseCallback<DetailItemModel>() {
@Override
public void onFailure(Request request, Exception e) {
mHandler.sendEmptyMessage(REQUEST_DETAIL_FAIL);
}
@Override
public void onResponse(Response response, DetailItemModel model) {
if (model != null) {
Message message = mHandler.obtainMessage();
message.obj = model;
message.what = REREFSH_DETAIL_SUCCESE;
mHandler.sendMessage(message);
} else {
mHandler.sendEmptyMessage(REQUEST_DETAIL_FAIL);
}
}
});
}
/**
* 初始化中间内容视图
*
* @param content
*/
private void initContentView(View content) {
translateRadioButton = (RadioButton) content.findViewById(R.id.translateRadioButton);
compareListview = (ListView) content.findViewById(R.id.compareListview);
tvProductIntrduce = (TextView) content.findViewById(R.id.tv_productIntrduce);
errorTipsView = (ErrorTipsView) content.findViewById(R.id.error_tipsview);
tvProductTitle = (TextView) content.findViewById(R.id.productdetail_title);
productGallaryView = (ImageViewpagerView) content.findViewById(R.id.productGallaryView);
detailLayout = (LinearLayout) content.findViewById(R.id.detail_layout);
rl_translate = (TranslateCheckableLayout) content.findViewById(R.id.rl_translate);
rl_translate.setOnCheckedChangeListener(this);
rl_translate.setChecked(false);
}
/**
* handler更新UI
*/
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.1f);
alphaAnimation.setDuration(2000);
prouctDetail = (DetailItemModel) msg.obj;
switch (msg.what) {
case REQUEST_DETAIL_FAIL:
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
int height = wm.getDefaultDisplay().getHeight();
FrameLayout.LayoutParams lp2 = (FrameLayout.LayoutParams) errorTipsView.getLayoutParams();
lp2.height = height - topPanel.getMeasuredHeight() - 40;
errorTipsView.setLayoutParams(lp2);
errorTipsView.requestLayout();
loadBallView.setVisibility(View.GONE);
errorTipsView.setVisibility(View.VISIBLE);
detailLayout.setVisibility(View.INVISIBLE);
errorTipsView.setLoadGoneAndErrorTipsVisiable();
mScrollView.stopRefresh();
break;
case REQUEST_DETAIL_SUCCESE:
if (prouctDetail != null) {
initProductGalleryView(prouctDetail);
initDetail(prouctDetail);
}
loadBallView.startAnimation(alphaAnimation);
alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation arg0) {
loadBallView.setVisibility(View.GONE);
detailLayout.setVisibility(View.VISIBLE);
mScrollView.stopRefresh();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
break;
case REREFSH_DETAIL_SUCCESE:
errorTipsView.setVisibility(View.GONE);
detailLayout.setVisibility(View.VISIBLE);
if (prouctDetail != null) {
initProductGalleryView(prouctDetail);
initDetail(prouctDetail);
}
mScrollView.stopRefresh();
break;
default:
break;
}
}
};
/**
* 初始化详细页面的信息
*
* @param prouctDetail
*/
private void initDetail(DetailItemModel prouctDetail) {
//比价商店集合
ArrayList<DetailItemModel.Item.Shops> shopses = new ArrayList<>();
for (int i = 0; i < prouctDetail.item.shops.size(); i++) {
shopses.add(prouctDetail.item.shops.get(i));
}
tvProductTitle.setText(Html.fromHtml(prouctDetail.item.name));
compareListview.setAdapter(new CompareShopAdapter(ProductDetailAcitvity.this, shopses));
tvProductIntrduce.setText(prouctDetail.item.detail);
if (StringUtil.isEqual("cn", prouctDetail.item.language)) {
rl_translate.setVisibility(View.INVISIBLE);
} else {
rl_translate.setVisibility(View.VISIBLE);
}
detailLayout.setVisibility(View.VISIBLE);
loadBallView.setVisibility(View.GONE);
}
/**
* 初始化产品图册切换视图控件
*
* @param prouctDetail
*/
private void initProductGalleryView(DetailItemModel prouctDetail) {
productGallaryView.setLoadViewName(false);
List<String> bannerList = new ArrayList<>();
bannerList.add("http://p0.so.qhmsg.com/bdr/_240_/t016013b0d70e221a30.png");
bannerList.add("");
bannerList.add("http://p4.so.qhmsg.com/bdr/_240_/t014a150e180202e074.jpg");
for (int i = 0; i < prouctDetail.item.images.size(); i++) {
bannerList.add(prouctDetail.item.images.get(i));
}
productGallaryView.setAutoPlayAble(false);
productGallaryView.setImagesUrl(bannerList);
}
@Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
refreshDetail();
}
}, 2000);
}
@Override
public void onLoadMore() {
}
@Override
public void onScrollGetVerticalValue(int scrollYvalue) {
}
/**
* 点击翻译按钮进行中英文切换翻译,如果内容是中文翻译按钮是不显示的,如果简介是日文,翻译成中文
*
* @param buttonView The compound button view whose state has changed.
* @param isChecked The new checked state of buttonView.
*/
@Override
public void onCheckedChanged(CheckableView buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
if (prouctDetail != null) {
if (!StringUtil.isEmpty(prouctDetail.item.detail) && StringUtil.isEqual("jp", prouctDetail.item.language)) {
if (StringUtil.isEmpty(StorageManager.getTranslationResult(ProductDetailAcitvity.this, prouctDetail.item.code))) {
String str = prouctDetail.item.detail.replace("\n", "|");
try {
ApiManager.translate(str, "jp", "zh", new TanslationHttpCallback() {
@Override
public void onTranslateSuccess(String result) {
if (!StringUtil.isEqual(StorageManager.getTranslationResult(ProductDetailAcitvity.this, prouctDetail.item.code), result)) {
StorageManager.saveTranslationResult(ProductDetailAcitvity.this, result, prouctDetail.item.code);
}
tvProductIntrduce.setText(result.toString());
}
@Override
public void onTranslateFailure(String exception) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
DevUtil.e("fdsf", "fdsfds");
tvProductIntrduce.setText(StorageManager.getTranslationResult(ProductDetailAcitvity.this, prouctDetail.item.code));
}
}
}
} else {
tvProductIntrduce.setText(prouctDetail.item.detail);
}
}
}
|
package ca.ubc.cs304.model;
public class VehicleModel {
private final String license;
private final String make;
private final String model;
private final String year;
private final String color;
private final int odometer;
private final String status;
private final String branch;
private final String vtname;
public VehicleModel(String license, String make, String model, String year, String color, String status, String branch, String vtname, int odometer){
this.license = license;
this.make = make;
this.model = model;
this.year = year;
this.color = color;
this.status = status;
this.branch = branch;
this.vtname = vtname;
this.odometer = odometer;
}
public String getLicense() {
return license;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getYear() {
return year;
}
public String getColor() {
return color;
}
public String getStatus() {
return status;
}
public String getBranch() {
return branch;
}
public String getVtname() {
return vtname;
}
public int getOdometer() {
return odometer;
}
}
|
package edu.tecnasa.ecommerce.controller;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import edu.tecnasa.ecommerce.dao.IProductDAO;
import edu.tecnasa.ecommerce.dto.ProductDto;
import edu.tecnasa.ecommerce.entities.Product;
import edu.tecnasa.ecommerce.errors.ResourceNotFoundException;
import edu.tecnasa.ecommerce.service.FileStorageService;
@RestController("productController")
public class ProductController {
@Inject
private IProductDAO productDao;
@Inject
private FileStorageService fileStorageService;
@RequestMapping(value="/api/Products", method=RequestMethod.GET)
public ResponseEntity<Page<ProductDto>> getProducts(Pageable pageable) {
Page<ProductDto> result = productDao.findAll(pageable).map(new ProductToProductDto());
return new ResponseEntity<>(result, HttpStatus.OK);
}
@RequestMapping(value="/api/Product/{id}", method=RequestMethod.GET)
public ResponseEntity<ProductDto> getProduct(@PathVariable Long id) {
Optional<ProductDto> result = productDao.findById(id).map(new ProductToProductDto());
return new ResponseEntity<>(result.get(), HttpStatus.OK);
}
@RequestMapping(value="/api/Product", method=RequestMethod.POST)
public ResponseEntity<?> newProduct(@RequestBody Product product) {
product.setProductId(null);
product = productDao.save(product);
// Set the location header for the newly created resource
HttpHeaders responseHeaders = new HttpHeaders();
URI newUri = ServletUriComponentsBuilder
.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(product.getId())
.toUri();
responseHeaders.setLocation(newUri);
return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED);
}
@RequestMapping(value="/api/Product/{id}", method=RequestMethod.PUT)
public ResponseEntity<?> updateProduct(@RequestBody Product product, @PathVariable Long id) {
verifyProduct(id);
product.setProductId(id);
// Save the entity
product = productDao.save(product);
return new ResponseEntity<>(HttpStatus.OK);
}
@RequestMapping(value="/api/Product/{id}", method=RequestMethod.DELETE)
public ResponseEntity<?> deleteProduct(@PathVariable Long id) {
verifyProduct(id);
productDao.deleteById(id);
return new ResponseEntity<>(HttpStatus.OK);
}
private Product verifyProduct(Long id) throws ResourceNotFoundException {
Optional<Product> Product = productDao.findById(id);
if(!Product.isPresent()){
throw new ResourceNotFoundException("Product #" + id + " not found.");
}
return Product.get();
}
@RequestMapping(value="/api/Product/{id}/file", method= {RequestMethod.POST, RequestMethod.PUT})
public ResponseEntity<?> uploadFile(@PathVariable Long id, @RequestParam("file") MultipartFile file) throws Exception {
Product product = verifyProduct(id);
fileStorageService.storeFile(product, file);
return new ResponseEntity<>(HttpStatus.OK);
}
@RequestMapping(value="/api/Product/{id}/file", method= RequestMethod.GET)
public void getFile(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) throws Exception {
Product product = verifyProduct(id);
fileStorageService.streamFile(request, response, product, FileStorageService.ImageType.NORMAL);
}
@RequestMapping(value="/api/Product/{id}/thumbnail", method=RequestMethod.GET)
public void getThumbnail(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") Long id) throws Exception {
Product product = verifyProduct(id);
fileStorageService.streamFile(request, response, product, FileStorageService.ImageType.THUMBNAIL);
}
@RequestMapping(value="/api/Product/GetProductsByCategory", method=RequestMethod.GET)
public ResponseEntity<Page<ProductDto>> getProductsByCategory(Pageable pageable, @RequestParam("idcategory") Long idCategory) {
Page<ProductDto> result = productDao.SearchByCategoryId(pageable, idCategory).map(new ProductToProductDto());
return new ResponseEntity<>(result, HttpStatus.OK);
}
private class ProductToProductDto implements Function<Product, ProductDto> {
@Override
public ProductDto apply(Product t) {
return new ProductDto(t.getId(),
t.getProductTitle(),
t.getProductPrice(),
t.getProductSpecial(),
t.getProductDescriptions(),
t.getCategories(),
String.format("/api/Product/%d/thumbnail", t.getId()),
String.format("/api/Product/%d/file", t.getId()));
}
}
}
|
package presentacion.controlador.command.CommandEmpleado;
import negocio.empleado.SAEmpleado;
import negocio.empleado.TransferEmpleado;
import negocio.factorias.FactorySA;
import presentacion.contexto.Contexto;
import presentacion.controlador.command.Command;
import presentacion.eventos.EventosEmpleado;
public class TotalSalarioDepartamento implements Command {
@Override
public Contexto execute(Object objeto) {
final TransferEmpleado Empleado = (TransferEmpleado) objeto;
final SAEmpleado sa = FactorySA.getInstance().createSAEmpleado();
String mensaje;
Contexto contexto;
try {
contexto = new Contexto(EventosEmpleado.TOTAL_SALARIOS_DEP_OK, sa.totalSalariosDepartamento(Empleado.getDepartamento().getID()));
} catch (final Exception e) {
mensaje = e.getMessage();
contexto = new Contexto(EventosEmpleado.TOTAL_SALARIOS_DEP_KO, mensaje);
}
return contexto;
}
}
|
class Planet
{
public static final double G = 6.67E-11;
String workDir=System.getProperty("user.dir");
String uu=workDir+"/images/";
double aX;
double aY;
double xVel;
double yVel;
double xxPos;
double yyPos;
double xxVel;
double yyVel;
double mass;
String imgFileName;
public Planet(double xP, double yP, double xV, double yV, double m,String img)
{
xxPos=xP;
yyPos=yP;
xxVel=xV;
yyVel=yV;
mass=m;
imgFileName=uu+img;
}
public Planet(Planet p)
{
xxPos=p.xxPos;
yyPos=p.yyPos;
xxVel=p.xxVel;
yyVel=p.yyVel;
mass=p.mass;
imgFileName=p.imgFileName;
}
public double calcDistance(Planet a)
{
return (Math.sqrt(Math.pow((xxPos-a.xxPos),2) + (Math.pow((yyPos-a.yyPos),2))));
}
public double calcForceExertedBy(Planet a)
{
return (G * this.mass * a.mass) / Math.pow(calcDistance(a),2);
}
public double calcForceExertedByX(Planet a)
{
double dx=a.xxPos-this.xxPos;
return calcForceExertedBy(a) * dx / calcDistance(a);
}
public double calcForceExertedByY(Planet a)
{
double dy=a.yyPos - this.yyPos;
return calcForceExertedBy(a) * dy / calcDistance(a);
}
public double calcNetForceExertedByX (Planet[] a)
{
xVel=0;
//double xNetForce;
for (int i=0;i<a.length;i++)
{
if (this.equals(a[i]))
{continue;}
else{
xVel+=this.calcForceExertedByX(a[i]);
}
}
return xVel;
}
public double calcNetForceExertedByY(Planet[] a)
{
yVel=0;
for (int i=0;i<a.length;i++)
{
if (this.equals(a[i]))
{continue;}
else {
yVel+=this.calcForceExertedByY(a[i]);
}
}
return yVel;
}
public void update(double dt,double fX,double fY)
{
double aX=fX / this.mass;
double aY=fY / this.mass;
xxVel+=dt*aX ;
yyVel+=dt*aY ;
xxPos+=dt*xxVel;
yyPos+=dt*yyVel;
}
public void draw()
{
StdDraw.picture(xxPos,yyPos,imgFileName);
}
}
|
package com.jim.multipos.utils;
import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.jim.multipos.R;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by developer on 04.12.2017.
*/
public class OrderMenuDialog extends Dialog {
@BindView(R.id.tvHeldOrders)
TextView tvHeldOrders;
@BindView(R.id.tvTodayOrders)
TextView tvTodayOrders;
@BindView(R.id.tvClose)
TextView tvClose;
@BindView(R.id.llSettingsMenu)
LinearLayout llSettingsMenu;
@BindView(R.id.tvNewOrders)
TextView tvNewOrders;
public OrderMenuDialog(Context context, onOrderMenuItemClickListener listener) {
super(context);
View dialogView = getLayoutInflater().inflate(R.layout.order_dialog, null);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
Window window = this.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.y = CommonUtils.dpToPx(30);
wlp.x = CommonUtils.dpToPx(210);
wlp.width = CommonUtils.dpToPx(300);
wlp.height = CommonUtils.dpToPx(250);
wlp.gravity = Gravity.TOP | Gravity.LEFT;
window.setAttributes(wlp);
ButterKnife.bind(this, dialogView);
setContentView(dialogView);
llSettingsMenu.setOnClickListener(view -> dismiss());
tvTodayOrders.setOnClickListener(view -> {
listener.onTodayOrderClick();
dismiss();
});
tvHeldOrders.setOnClickListener(view -> {
listener.onHeldOrderClick();
dismiss();
});
tvNewOrders.setOnClickListener(view -> {
listener.onNewOrderClick();
dismiss();
});
tvClose.setOnClickListener(view -> {
dismiss();
});
}
public interface onOrderMenuItemClickListener {
void onTodayOrderClick();
void onHeldOrderClick();
void onNewOrderClick();
}
}
|
package com.github.hippo.netty;
import com.github.hippo.bean.HippoRequest;
import com.github.hippo.bean.HippoResponse;
import com.github.hippo.callback.CallTypeHandler;
import com.github.hippo.callback.RemoteCallHandler;
import com.github.hippo.enums.HippoRequestEnum;
import com.github.hippo.exception.HippoServiceException;
import com.github.hippo.threadpool.HippoClientProcessPool;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ConcurrentHashMap;
/**
* client process handler
*
* @author sl
*/
public class HippoRequestHandler extends SimpleChannelInboundHandler<HippoResponse> {
private static final Logger LOGGER = LoggerFactory.getLogger(HippoRequestHandler.class);
private ConcurrentHashMap<String, HippoResultCallBack> callBackMap = new ConcurrentHashMap<>();
private String serviceName;
private EventLoopGroup eventLoopGroup;
private Channel channel;
private String host;
private int port;
public HippoRequestHandler(String serviceName, EventLoopGroup eventLoopGroup, String host,
int port) {
this.serviceName = serviceName;
this.eventLoopGroup = eventLoopGroup;
this.host = host;
this.port = port;
}
@Override
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
super.channelRegistered(ctx);
this.channel = ctx.channel();
}
@Override
protected void channelRead0(ChannelHandlerContext arg0, HippoResponse response) throws Exception {
// ping不需要记录到返回结果MAP里
if (response != null && !("-99").equals(response.getRequestId())) {
HippoClientProcessPool.INSTANCE.getPool().execute(() -> {
HippoResultCallBack hippoResultCallBack = callBackMap.remove(response.getRequestId());
// oneway方式没有hippoResultCallBack
if (hippoResultCallBack == null) {
return;
}
RemoteCallHandler handler = CallTypeHandler.INSTANCE
.getHandler(hippoResultCallBack.getHippoRequest().getCallType());
if (handler != null) {
handler.back(hippoResultCallBack, response);
}
});
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
super.userEventTriggered(ctx, evt);
if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt;
if (e.state() == IdleState.WRITER_IDLE) {
HippoRequest hippoRequest = new HippoRequest();
hippoRequest.setServiceName(serviceName);
hippoRequest.setRequestId("-99");
hippoRequest.setRequestType(HippoRequestEnum.PING.getType());
ctx.writeAndFlush(hippoRequest);
}
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
super.channelInactive(ctx);
ctx.close();
shutdown();
this.callBackMap.values().forEach(c -> {
HippoResponse response = new HippoResponse();
response.setError(true);
response.setThrowable(
new HippoServiceException("hippo server error trigger client channelInactive"));
c.signal(response);
});
callBackMap.clear();
HippoClientBootstrapMap.remove(serviceName, host, port);
}
public void shutdown() {
try {
if (eventLoopGroup != null && !eventLoopGroup.isShutdown()
&& !eventLoopGroup.isShuttingDown()) {
eventLoopGroup.shutdownGracefully();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendAsync(HippoResultCallBack hippoResultCallBack) {
callBackMap.put(hippoResultCallBack.getHippoRequest().getRequestId(), hippoResultCallBack);
this.channel.writeAndFlush(hippoResultCallBack.getHippoRequest());
}
public HippoResponse sendOneWay(HippoRequest hippoRequest) {
this.channel.writeAndFlush(hippoRequest);
return buildEmptyHippoResponse(hippoRequest);
}
public HippoResponse sendWithCallBack(HippoResultCallBack hippoResultCallBack) {
sendAsync(hippoResultCallBack);
return buildEmptyHippoResponse(hippoResultCallBack.getHippoRequest());
}
private HippoResponse buildEmptyHippoResponse(HippoRequest hippoRequest) {
HippoResponse hippoResponse = new HippoResponse();
hippoResponse.setRequestId(hippoRequest.getRequestId());
hippoResponse.setChainId(hippoRequest.getChainId());
hippoResponse.setChainOrder(hippoRequest.getChainOrder());
return hippoResponse;
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
LOGGER.error("netty client error", cause.fillInStackTrace());
HippoClientBootstrapMap.remove(serviceName, host, port);
ctx.close();
shutdown();
}
}
|
/*
* Copyright 2014 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.shadowstore;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
/**
* {@link ShadowStore} implementation that stores shadows in Redis, via an injected {@link RedisTemplate}.
*
* @author Craig Walls
*/
public class RedisShadowStore extends AbstractShadowStore implements DisposableBean {
private final RedisOperations<String, Shadow<?>> redisTemplate;
private final List<String> keys = new ArrayList<>();
/**
* Constructs a Redis-based {@link ShadowStore}.
* @param remoteNodeId the unique id of the node that this shadow store is being created for.
* @param redisTemplate a {@link RedisOperations} that will be used to store shadow copies.
*/
public RedisShadowStore(String remoteNodeId, RedisOperations<String, Shadow<?>> redisTemplate) {
super(remoteNodeId);
this.redisTemplate = redisTemplate;
}
@Override
public void putShadow(String key, Shadow<?> shadow) {
String nodeKey = getNodeSpecificKey(key);
redisTemplate.opsForValue().set(nodeKey, shadow);
keys.add(nodeKey);
}
@Override
public Shadow<?> getShadow(String key) {
return redisTemplate.opsForValue().get(getNodeSpecificKey(key));
}
@Override
public void destroy() throws Exception {
redisTemplate.delete(keys);
}
}
|
/*
@author <<author name redacted >>
Purpose: To sort a table in ascending order and check if sorted
Programming Assignment 1
Course: CS5387 - Software Integration and V&V
Professor: Dr. Steve Roach
Last modification date: 1/25/2020
*/
package cs5387;
public class TablesSorter {
/** A Places contains, is an inner class because coordinates are commonly used in the algorithms*/
private class Place{
int row;
int col;
//Removes default constructor to forces row and col to be specified
private Place(){}
public Place(int row, int col){
this.row = row;
this.col = col;
}
}
/** Finds if table is sorted in ascending order
* @return true if every row and every column of the table t is sorted in ascending order*/
public boolean isSorted(Table t){
int tableSize = t.getSize();
/*We can tell that a table is sorted when every 2 by 2 square is sorted.
(max value on the bottom-right, and the min on the top-left)*/
//Iterates through every row except the last
for(int row = 0; row < tableSize-1; row++){
//Iterates through every column except the last
for(int col = 0; col < tableSize-1; col++){
//Coordinates of the square
Place[] squareCoordinates = getSquareIdx(row, col);
//Values of the square
int [] tableSquareValues = getSquareValues(t, squareCoordinates);
//Finds where the max and min value is
int idxMax = argMax(tableSquareValues);
int idxMin = argMin(tableSquareValues);
//return false if min isn't in the top-left corner and max isn't at the bottom-right corner
if(idxMin != 0 || idxMax != 3){
return false;
}
}
}
return true;
}
/** Does table sorting of the values (row,col), (row+1,col), (row,col+1), (row+1,col+1),
* so that index (row, col) value is min, and max value is at index (row+1, col+1)
* precondition: row+1 < table.getSize() && col+1 < table.getSize() or an index out of bounds exception will be thrown*/
private void sortSquare(Table t, int row, int col){
Place[] tableSquareIdx = getSquareIdx(row, col);
int [] tableSquareValues = getSquareValues(t, tableSquareIdx);
int idxMax = argMax(tableSquareValues);
int idxMin = argMin(tableSquareValues);
//Swaps to min is at index (row,col)
swapValues(t, tableSquareIdx[idxMin], tableSquareIdx[0]);
//Updates position of idxMax and idxMin (idxMax could have been moved if it was at index row,col)
if(idxMax == 0){
idxMax = idxMin;
idxMin = 0;
}
swapValues(t, tableSquareIdx[idxMax], tableSquareIdx[3]);
}
/** @return coordinates for a 2 by 2 square: (row, col), (row+1, col), (row, col+1), (row+1, col+1)
* Used for the table sorting algorithm and for the algorithm check if the table is sorted*/
private Place[] getSquareIdx(int row, int col){
return new Place[]{
new Place(row, col),
new Place(row + 1, col),
new Place(row, col + 1),
new Place(row + 1, col + 1)
};
}
/** @return integer array containing the values in the table the parameter places has the coordinates of*/
private int[] getSquareValues(Table t, Place[] places){
int[] tableSquareValues = new int[4];
for(int i = 0; i < places.length; i++){
Place p = places[i];
tableSquareValues[i] = t.getTableValue(p.row, p.col);
}
return tableSquareValues;
}
/** precondition: array can't be null and must have at least 1 element
* @return the index of where the biggest value is, if precondition isn't met, returns -1 */
private int argMax(int[] arr) {
return findArgMaxOrMin(arr, true);
}
/** precondition: array can't be null and must have at least 1 element
* @return the index of where the smallest value is, if precondition isn't met, returns -1 */
private int argMin(int[] arr){
return findArgMaxOrMin(arr, false);
}
/** Finds the index of where the min value or the max value is.
* precondition: array can't be null and must have at least 1 element, or else returns -1
* @param findMax if true finds the argument of max, if false finds the index where the min is
* @return the index of where the max or min value is*/
private int findArgMaxOrMin(int[] arr, boolean findMax){
if(arr == null || arr.length < 1){
return -1;
}
int maxOrMin = arr[0];
int maxOrMinIndex = 0;
for(int i = 1; i < arr.length; i++){
boolean isMaxOrMin = maxOrMin < arr[i];
//If we are not finding max
if(!findMax){
isMaxOrMin = !isMaxOrMin;
}
if(isMaxOrMin){
maxOrMin = arr[i];
maxOrMinIndex = i;
}
}
return maxOrMinIndex;
}
/** Swaps the values in coordinates p1 and p2 of table t */
private void swapValues(Table t, Place p1, Place p2){
int p1Value = t.getTableValue(p1.row, p1.col);
int p2Value = t.getTableValue(p2.row, p2.col);
t.setTableValue(p1.row, p1.col, p2Value);
t.setTableValue(p2.row, p2.col, p1Value);
}
/** Sorts a Table so that every row and every column of the table t is sorted in ascending order */
public static void sortable(Table t){
int tableSize = t.getSize();
TablesSorter ts = new TablesSorter();
/*Algorithm: Sorts every 2 by 2 square in the table, if you do this tableSize * 2 - 1 times, then eventually
* the table will be fully sorted since during every square sort a value will be moved at least one place*/
for(int i = 0; i < tableSize * 2 - 1 && !ts.isSorted(t); i++){
//TableSize - 1 because, index row,col already checks row+1 and col+1
for (int row = 0; row < tableSize-1; row++) {
for (int col = 0; col < tableSize-1; col++) {
ts.sortSquare(t, row, col);
}
}
}
}
}
|
package jp.co.logacy.exception;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;
public class SmyExceptionHandler extends ExceptionHandler {
final Logger log = Logger.getLogger(SmyExceptionHandler.class.getName());
@Override
public ActionForward execute(Exception ex, ExceptionConfig ae, ActionMapping mapping, ActionForm formInstance,
HttpServletRequest request, HttpServletResponse response) throws ServletException {
log.error(ex.getClass());
// メッセージ生成
ActionMessage msg = new ActionMessage("msg.key.handler");
String property = Globals.ERROR_KEY;
ActionForward forward = new ActionForward(ae.getPath());
String scope = "request";
// リクエストにエラーメッセージを保存
storeException(request, property, msg, forward, scope);
if (!response.isCommitted()) {
return forward;
}
return null;
}
}
|
package handwriting.learners.decisiontree;
import handwriting.core.Drawing;
public class DTInteriorNode implements DTNode {
int featureX = 0, featureY = 0;
DTNode left, right;
public DTInteriorNode(int x, int y){
this(x, y, null, null);
}
public DTInteriorNode(int x, int y, DTNode left, DTNode right){
this.featureX = x;
this.featureY = y;
this.left = left;
this.right = right;
}
public void setLeft(DTNode node){
this.left = node;
}
public void setRight(DTNode node){
this.right = node;
}
@Override
public String classify(Drawing d) {
if (hasFeature(d))
return this.right.classify(d);
else
return this.left.classify(d);
}
public boolean hasFeature(Drawing d){
return d.isSet(this.featureX, this.featureY);
}
}
|
package com.tt.miniapphost.liveplayer;
import com.tt.miniapp.liveplayer.ITTLivePlayer;
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapphost\liveplayer\BDPLivePlayer$WhenMappings.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
/*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.java.micronaut;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.AnnotationMatcher;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.JavaParser;
import org.openrewrite.java.JavaTemplate;
import org.openrewrite.java.marker.JavaSearchResult;
import org.openrewrite.java.search.UsesType;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JavaType;
import org.openrewrite.marker.Marker;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import static org.openrewrite.Tree.randomId;
public class TypeRequiresIntrospection extends Recipe {
private static final JavaType.FullyQualified INTROSPECTED_ANNOTATION = JavaType.Class.build("io.micronaut.core.annotation.Introspected");
@SuppressWarnings("ConstantConditions")
private static final Marker FOUND_CHANGE_TO_MAKE = new JavaSearchResult(randomId(), null, null);
private static final String CONTEXT_KEY = "classes-need-introspection";
@Override
public String getDisplayName() {
return "Add `@Introspected` to classes requiring a map representation";
}
@Override
public String getDescription() {
return "In Micronaut 2.x a reflection-based strategy was used to retrieve that information if the class was not annotated with `@Introspected`. As of Micronaut 3.x it is required to annotate classes with `@Introspected` that are used in this way.";
}
@Override
protected JavaIsoVisitor<ExecutionContext> getApplicableTest() {
return new UsesType<>("io.micronaut.*");
}
@Override
protected JavaIsoVisitor<ExecutionContext> getSingleSourceApplicableTest() {
return new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, ExecutionContext executionContext) {
Set<JavaType.Class> classesToUpdate = executionContext.getMessage(CONTEXT_KEY);
if (classesToUpdate != null && classesToUpdate.stream()
.anyMatch(jc -> cu.getClasses().stream().map(J.ClassDeclaration::getType).anyMatch(jc::isAssignableFrom))) {
return cu.withMarkers(cu.getMarkers().addIfAbsent(FOUND_CHANGE_TO_MAKE));
} else {
doAfterVisit(new UsesType<>("io.micronaut.http.annotation.Controller"));
doAfterVisit(new UsesType<>("io.micronaut.http.client.annotation.Client"));
}
return cu;
}
};
}
@Override
protected RequiresIntrospectionVisitor getVisitor() {
return new RequiresIntrospectionVisitor();
}
private static class RequiresIntrospectionVisitor extends JavaIsoVisitor<ExecutionContext> {
private static final List<Predicate<J.Annotation>> REQUIRES_INTROSPECTED_CLASSES_PREDICATES = Arrays.asList(
new AnnotationMatcher("@io.micronaut.http.annotation.Controller")::matches,
new AnnotationMatcher("@io.micronaut.http.client.annotation.Client")::matches);
private static boolean requiresIntrospectedTypes(J.ClassDeclaration cd) {
return cd.getLeadingAnnotations().stream().anyMatch(anno -> REQUIRES_INTROSPECTED_CLASSES_PREDICATES.stream().anyMatch(p -> p.test(anno)));
}
private static boolean needsIntrospectedAnnotation(@Nullable JavaType.Class jc) {
return jc != null && jc.getAnnotations().stream().noneMatch(fq -> fq.isAssignableFrom(INTROSPECTED_ANNOTATION));
}
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext executionContext) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, executionContext);
if (requiresIntrospectedTypes(cd)) {
new JavaIsoVisitor<ExecutionContext>() {
@Override
public J.MethodDeclaration visitMethodDeclaration(J.MethodDeclaration method, ExecutionContext executionContext) {
J.MethodDeclaration md = super.visitMethodDeclaration(method, executionContext);
if (!md.isConstructor()) {
// method parameters need introspection
md.getParameters().stream()
.filter(J.VariableDeclarations.class::isInstance)
.map(j -> ((J.VariableDeclarations) j).getVariables())
.flatMap(List::stream)
.map(J.VariableDeclarations.NamedVariable::getType)
.filter(JavaType.Class.class::isInstance)
.map(JavaType.Class.class::cast)
.filter(RequiresIntrospectionVisitor::needsIntrospectedAnnotation)
.forEach(jc -> executionContext.putMessageInSet(CONTEXT_KEY, jc));
// return type needs introspection
if (md.getReturnTypeExpression() instanceof J.Identifier) {
J.Identifier ident = (J.Identifier) md.getReturnTypeExpression();
JavaType.Class jc = ident.getType() != null && ident.getType() instanceof JavaType.Class ? (JavaType.Class) ident.getType() : null;
if (needsIntrospectedAnnotation(jc)) {
executionContext.putMessageInSet(CONTEXT_KEY, jc);
}
}
}
return md;
}
}.visit(cd, executionContext, getCursor());
}
if (executionContext.getMessage(CONTEXT_KEY) != null) {
doAfterVisit(new AddIntrospectionRecipe());
}
return cd;
}
}
private static class AddIntrospectionRecipe extends Recipe {
private static final AnnotationMatcher INTROSPECTION_ANNOTATION_MATCHER = new AnnotationMatcher("@io.micronaut.core.annotation.Introspected");
private static final ThreadLocal<JavaParser> JAVA_PARSER = ThreadLocal.withInitial(() ->
JavaParser.fromJavaVersion().dependsOn(
"package io.micronaut.core.annotation; public @interface Introspected {}")
.build());
@Override
public String getDisplayName() {
return "Adding Introspection annotation";
}
@Override
protected JavaIsoVisitor<ExecutionContext> getVisitor() {
return new JavaIsoVisitor<ExecutionContext>() {
final JavaTemplate templ = JavaTemplate.builder(this::getCursor, "@Introspected")
.imports(INTROSPECTED_ANNOTATION.getFullyQualifiedName())
.javaParser(JAVA_PARSER::get).build();
@Override
public J.ClassDeclaration visitClassDeclaration(J.ClassDeclaration classDecl, ExecutionContext executionContext) {
J.ClassDeclaration cd = super.visitClassDeclaration(classDecl, executionContext);
if (cd.getLeadingAnnotations().stream().noneMatch(INTROSPECTION_ANNOTATION_MATCHER::matches)) {
Set<JavaType.Class> needsAnnotation = executionContext.getMessage(CONTEXT_KEY);
if (needsAnnotation != null && needsAnnotation.stream().anyMatch(jc -> jc.isAssignableFrom(classDecl.getType()))) {
cd = cd.withTemplate(templ, cd.getCoordinates().addAnnotation(Comparator.comparing(J.Annotation::getSimpleName)));
maybeAddImport(INTROSPECTED_ANNOTATION.getFullyQualifiedName());
}
}
return cd;
}
};
}
}
}
|
package EnterRectangleWidthAndHeight;
import java.awt.Rectangle;
import java.util.Locale;
import java.util.Scanner;
public class dadosFuncionario {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
Scanner sc = new Scanner(System.in);
a rect = new a();
System.out.println("Enter rectangle width and height:");
rect.width = sc.nextDouble();
rect.height = sc.nextDouble();
System.out.printf("AREA = %.2f%n", rect.area());
System.out.printf("PERIMETER = %.2f%n", rect.perimeter());
System.out.printf("DIAGONAL = %.2f%n", rect.diagonal());
sc.close();
}
}
|
package com.tencent.mm.plugin.emoji.ui.v2;
import android.text.Editable;
import android.text.TextWatcher;
import com.tencent.mm.R;
class EmojiStoreV2RewardUI$4 implements TextWatcher {
final /* synthetic */ EmojiStoreV2RewardUI iqC;
EmojiStoreV2RewardUI$4(EmojiStoreV2RewardUI emojiStoreV2RewardUI) {
this.iqC = emojiStoreV2RewardUI;
}
public final void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public final void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
}
public final void afterTextChanged(Editable editable) {
if (EmojiStoreV2RewardUI.h(this.iqC) != null) {
if (editable != null && editable.length() > 0) {
String obj = editable.toString();
int indexOf = obj.indexOf(".");
if (indexOf > 0 && (obj.length() - indexOf) - 1 > 2) {
editable.delete(indexOf + 3, indexOf + 4);
}
float f = 0.0f;
try {
f = Float.valueOf(editable.toString()).floatValue();
} catch (NumberFormatException e) {
}
if (f > 200.0f || f < 1.0f) {
EmojiStoreV2RewardUI.e(this.iqC).getContentEditText().setTextColor(this.iqC.mController.tml.getResources().getColor(R.e.red));
} else {
EmojiStoreV2RewardUI.e(this.iqC).getContentEditText().setTextColor(this.iqC.mController.tml.getResources().getColor(R.e.normal_text_color));
EmojiStoreV2RewardUI.h(this.iqC).setEnabled(true);
return;
}
}
EmojiStoreV2RewardUI.h(this.iqC).setEnabled(false);
}
}
}
|
package com.rudecrab.demo.entity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
* @author RC
* @description 用户实体类
*/
@Data
@ApiModel("用户")
public class User {
@ApiModelProperty("用户id")
@NotNull(message = "用户id不能为空")
private Long id;
@ApiModelProperty("用户账号")
@NotNull(message = "用户账号不能为空")
@Size(min = 6, max = 11, message = "账号长度必须是6-11个字符")
private String account;
@ApiModelProperty("用户密码")
@NotNull(message = "用户密码不能为空")
@Size(min = 6, max = 11, message = "密码长度必须是6-16个字符")
private String password;
@ApiModelProperty("用户邮箱")
@NotNull(message = "用户邮箱不能为空")
@Email(message = "邮箱格式不正确")
private String email;
}
|
/*
* 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.webbeans.test.component;
import java.util.List;
import jakarta.enterprise.context.RequestScoped;
import jakarta.enterprise.inject.Default;
import jakarta.inject.Inject;
@RequestScoped
public class InjectedTypeLiteralComponent
{
private @Inject @Default ITypeLiteralComponent<List<String>> component;
public InjectedTypeLiteralComponent()
{
super();
}
/**
* @return the component
*/
public ITypeLiteralComponent<List<String>> getComponent()
{
return component;
}
/**
* @param component the component to set
*/
public void setComponent(ITypeLiteralComponent<List<String>> component)
{
this.component = component;
}
}
|
import java.io.*;
import java.util.*;
public class character_position {
private int position;
private int a;
private int b;
private int c;
public void character_postion(){
}
}
|
package com.gtfs.action;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.gtfs.bean.LicRequirementDtls;
import com.gtfs.service.interfaces.LicRequirementDtlsService;
@Component
@Scope("session")
public class LicReqActPointAction implements Serializable{
private Logger log = Logger.getLogger(LicReqActPointAction.class);
@Autowired
private LicRequirementDtlsService licRequirementDtlsService;
@Autowired
private LoginAction loginAction;
private String applicationNo;
private Boolean renderedList;
private List<LicRequirementDtls> licRequirementDtlses= new ArrayList<LicRequirementDtls>();
public void refresh(){
applicationNo = null;
renderedList = false;
}
public void save(){
try{
Date now = new Date();
for(LicRequirementDtls obj:licRequirementDtlses){
obj.setActionBy(loginAction.getUserList().get(0).getUserid());
obj.setActionDate(now);
if(obj.getActionType().equals("SFCL") || obj.getActionType().equals("IR")){
obj.setDispatchReadyFlag("Y");
}else{
obj.setDispatchReadyFlag("N");
}
}
Boolean status=licRequirementDtlsService.saveForActionPoint(licRequirementDtlses);
if(status){
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,
"Save Successful : ", "Actions are taken"));
refresh();
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"Save Unsuccessful : ", "Error Occurred"));
}
}catch(Exception e){
log.info("LicReqActPointAction save Error : ", e);
}
}
public void search(){
try{
licRequirementDtlses = licRequirementDtlsService.findReqForActionTakenByApplNo(applicationNo,loginAction.findHubForProcess("POS"));
if(!(licRequirementDtlses == null || licRequirementDtlses.size() == 0)){
renderedList=true;
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,
"No Record(s) found : ", "Please Enter Requirement"));
}
}catch(Exception e){
log.info("LicReqActPointAction save Error : ", e);
}
}
public String onLoad(){
refresh();
return "/licHubActivity/licReqActPoint.xhtml";
}
/* GETTER SETTER */
public String getApplicationNo() {
return applicationNo;
}
public void setApplicationNo(String applicationNo) {
this.applicationNo = applicationNo;
}
public Boolean getRenderedList() {
return renderedList;
}
public void setRenderedList(Boolean renderedList) {
this.renderedList = renderedList;
}
public List<LicRequirementDtls> getLicRequirementDtlses() {
return licRequirementDtlses;
}
public void setLicRequirementDtlses(
List<LicRequirementDtls> licRequirementDtlses) {
this.licRequirementDtlses = licRequirementDtlses;
}
}
|
package de.jmda.app.uml.diagram.type;
import de.jmda.core.cdi.event.ActionOnEvent.AbstractEvent;
import javafx.scene.layout.Pane;
public interface TypeDiagramService
{
Pane getDiagramPane();
// void addShapesFor(Set<TypeElement> typeElements);
/**
* Used in CDI events to indicate that {@link TypeDiagramService} instance is available.
*
* @see TypeDiagramController#initialize()
*/
public class ViewServiceAvailable extends AbstractEvent<TypeDiagramService>
{
public ViewServiceAvailable(TypeDiagramService service) { super(service); }
public TypeDiagramService getViewService() { return getData().get(); }
}
}
|
package com.stackInstance.HighChartDatabase.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import com.stackInstance.HighChartDatabase.model.Employee;
import com.stackInstance.HighChartDatabase.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
private EmployeeService service;
@PostMapping("/addEmployee")
public String addEmployee(@RequestBody Employee employee) {
return service.saveEmployee(employee);
}
}
|
package LambdaDemo;
/**
* The functional interface is an interface with one method. Lambda expressions
* didn't work individually, they implement (define behavior) of 'abstract'
* method with the return type, which defined in the functional interface. So,
* lambda expression and return type of the functional interface should be
* similar.Another way of using functional interfaces is to use the default
* library 'java.util.function.Function'.
*
* Lambda expression cannot be generic, but a functional interface can be
* generic.
*
* @author Bohdan Skrypnyk
*/
// Generic functional interface
interface SomeFunc<T> {
T func(T t);
}
public class GenericLambdaDemo {
public static void main(String args[]) {
// this block expression return reversed word.
SomeFunc<String> reverse = (str) -> {
String result = "";
// get word length and start counting from the end.
for (int i = str.length() - 1; i >= 0; i--) {
result += str.charAt(i); // display characters by index
}
return result;
};
// display the method 'reverse.func("")'.
System.out.println("Reversed word 'Java' : " + reverse.func("Java"));
System.out.println("Reversed word 'Experience' : " + reverse.func("Experience"));
// the lambda block expression, which count factorial of the 'n'.
SomeFunc<Integer> factorial = (num) -> {
int result = 1;
for (int i = 1; i <= num; i++) {
result = result * i; // n! = 1×2×3×4×...×n
}
return result; // block lamda expression must have the return method.
};
// display factorial of the number 2.
System.out.println("Factorial : 2! = " + factorial.func(2));
// display factorial of the number 8.
System.out.println("Factorial : 8! = " + factorial.func(8));
}
}
|
package com.eres.waiter.waiter.model.singelton;
import android.content.Context;
import android.util.Log;
import com.eres.waiter.waiter.model.ArmoredTables;
import com.eres.waiter.waiter.model.DataMenu;
import com.eres.waiter.waiter.model.EmptyTable;
import com.eres.waiter.waiter.model.IAmTables;
import com.eres.waiter.waiter.model.OrderItemsItem;
import com.eres.waiter.waiter.model.ProductsItem;
import com.eres.waiter.waiter.model.TablesItem;
import com.eres.waiter.waiter.model.test.DataAddList;
import com.eres.waiter.waiter.model.test.NotificationEventAlarm;
import com.eres.waiter.waiter.retrofit.ApiClient;
import com.eres.waiter.waiter.retrofit.ApiInterface;
import com.eres.waiter.waiter.viewpager.helper.ObservableCollection;
import com.eres.waiter.waiter.viewpager.model.Hall;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class DataSingelton {
public static DataSingelton singelton;
public static ArrayList<EmptyTable> emptyTables;
private static ArrayList<ArmoredTables> armoredTables;
public static ArrayList<IAmTables> iAmTables;
private ObservableCollection<Hall> halls;
private static Context mC;
private static ArrayList<DataMenu> dataMenus;
private static ArrayList<DataAddList> productsItems;
private static boolean load = false;
private static boolean loadITable = false;
private static boolean loadArmoredTable = false;
public static HashSet<ProductsItem> testSet;
private static final String TAG = "DataSingelton";
ApiInterface apiInterface;
public static ObservableCollection<ProductsItem> searchItems;
public static HashMap<String, Integer> eventNotifAlarm;
public static ArrayList<String> strings;
public ObservableCollection<Hall> getHalls() {
return halls;
}
public void setHalls(ObservableCollection<Hall> halls) {
this.halls = halls;
}
public static ArrayList<OrderItemsItem> getMyOrders() {
return myOrders;
}
public static void setMyOrders(ArrayList<OrderItemsItem> myOrders) {
DataSingelton.myOrders = myOrders;
}
private static ArrayList<OrderItemsItem> myOrders;
public static ArrayList<DataAddList> getProducts() {
return productsItems;
}
public static void setProducts(ArrayList<DataAddList> productsItems) {
DataSingelton.productsItems = productsItems;
}
public static boolean isLoadITable() {
return loadITable;
}
public static boolean isLoadArmoredTable() {
return loadArmoredTable;
}
public static ArrayList<ArmoredTables> getArmoredTables() {
return isLoadArmoredTable() ? armoredTables : null;
}
public static ArrayList<IAmTables> getiAmTables() {
return iAmTables;
}
public static ArrayList<EmptyTable> getEmptyTables() {
return emptyTables;
}
public static ArrayList<DataMenu> getDataMenus() {
return isLoad() ? dataMenus : null;
}
public static boolean isLoad() {
return load;
}
private DataSingelton() {
apiInterface = ApiClient.getRetrofit(mC).create(ApiInterface.class);
emptyTables = new ArrayList<>();
halls = new ObservableCollection<>();
dataMenus = new ArrayList<>();
productsItems = new ArrayList<>();
testSet = new HashSet<>();
myOrders = new ArrayList<>();
searchItems = new ObservableCollection<>();
armoredTables = new ArrayList<>();
iAmTables = new ArrayList<>();
strings = new ArrayList<>();
eventNotifAlarm = new HashMap<>();
}
public IAmTables parseTable(TablesItem item) {
return new IAmTables(item.getHallId(), item.getDescription(), item.getId(), item.isExtOrder(), item.getDefaultWaiterId(), item.getCurrentWaiterId(), item.getName(), item.getTableState());
}
public void addImTableData(int id) {
for (int i = 0; i < getEmptyTables().size(); i++) {
for (int i1 = 0; i1 < getEmptyTables().get(i).getTables().size(); i1++) {
if (getEmptyTables().get(i).getTables().get(i1).getId() == id) {
getiAmTables().add(parseTable(getEmptyTables().get(i).getTables().get(i1)));
getEmptyTables().get(i).getTables().remove(i1);
Log.d(TAG, "addImTableData: " + i1 + "==" + id);
break;
}
}
}
}
public static DataSingelton getInstance(Context context) {
if (singelton == null) {
mC = context;
singelton = new DataSingelton();
}
return singelton;
}
public void loadArmoredTable() {
Call<ArrayList<ArmoredTables>> call = apiInterface.getArmoredTables();
call.enqueue(new Callback<ArrayList<ArmoredTables>>() {
@Override
public void onResponse(Call<ArrayList<ArmoredTables>> call, Response<ArrayList<ArmoredTables>> response) {
if (response.body() != null) {
armoredTables.clear();
armoredTables.addAll(response.body());
loadArmoredTable = true;
}
}
@Override
public void onFailure(Call<ArrayList<ArmoredTables>> call, Throwable t) {
Log.d(TAG, "onFailure: Armored ");
loadArmoredTable = false;
}
});
}
public void loadITable() {
Call<ArrayList<IAmTables>> call = apiInterface.getIamTables();
call.enqueue(new Callback<ArrayList<IAmTables>>() {
@Override
public void onResponse(Call<ArrayList<IAmTables>> call, Response<ArrayList<IAmTables>> response) {
if (response.body() != null) {
iAmTables.clear();
iAmTables.addAll(response.body());
Log.d("MY_LOG", "onResponse: " + iAmTables.size() + "==" + response.body().size());
}
}
@Override
public void onFailure(Call<ArrayList<IAmTables>> call, Throwable t) {
}
});
}
public void loadEmptyTable() {
emptyTables = new ArrayList<>();
Call<ArrayList<EmptyTable>> call = apiInterface.getEmptyTable();
call.enqueue(new Callback<ArrayList<EmptyTable>>() {
@Override
public void onResponse(Call<ArrayList<EmptyTable>> call, Response<ArrayList<EmptyTable>> response) {
if (response.body() != null) {
emptyTables.clear();
emptyTables.addAll(response.body());
Log.d(TAG, "onResponse: " + response.body().size() + "asd" + emptyTables.size());
}
}
@Override
public void onFailure(Call<ArrayList<EmptyTable>> call, Throwable t) {
Log.d(TAG, "onFailure: Error load table !!!! ");
}
});
}
public void loadData() {
Call<ArrayList<DataMenu>> call = apiInterface.getMenuAll();
call.enqueue(new Callback<ArrayList<DataMenu>>() {
@Override
public void onResponse(Call<ArrayList<DataMenu>> call, Response<ArrayList<DataMenu>> response) {
if (response.body() != null) {
dataMenus.clear();
dataMenus.addAll(response.body());
load = true;
Log.d(TAG, TAG + dataMenus.size());
}
}
@Override
public void onFailure(Call<ArrayList<DataMenu>> call, Throwable t) {
Log.d(TAG, "onFailure: DataMenu");
t.printStackTrace();
}
});
}
}
|
package com.example.myi;
import android.support.v4.content.AsyncTaskLoader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class ImageLoader extends AsyncTaskLoader<String> {
String myurl;
public ImageLoader(ImageActivity imageActivity, String key) {
super(imageActivity);
myurl=key;
}
@Override
public String loadInBackground() {
try {
URL u=new URL(myurl);
HttpsURLConnection connection= (HttpsURLConnection) u.openConnection();
InputStream is = connection.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String line="";
StringBuilder stringBuilder=new StringBuilder();
while ((line=br.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
return stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onStartLoading() {
super.onStartLoading();
forceLoad();
}
}
|
package com.example.flappobird;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
public class Ground {
private Context mContext;
private int mFrameWidth = GameView.sViewWidth;
private int mFrameHeight = GameView.sViewHeight;
private Bitmap mImage;
private Rect mImageRect1; // rect1 that fills the image
private Rect mImageRect2; // rect2 ..
static float sTop = (float) (83.3/100.0 * GameView.sViewHeight); // top coordinate of mImage
static float sVelocity = (float) ((0.43055/100.0 * GameView.sViewWidth)*0.06); // pixels per millisecond - expressed as percentage of frameWidth
private long mDeltaTime;
public Ground(Context context) {
mContext = context;
//mImage = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ground);
mImage = GameView.decodeScaledBitmapFromResource(mContext.getResources(), R.drawable.ground, mFrameWidth, 0);
mImageRect1 = new Rect(0, (int) sTop, mFrameWidth, mFrameHeight);
mImageRect2 = new Rect(mImageRect1.right, (int) sTop, mFrameWidth*2, mFrameHeight);
System.out.println("*** Ground.java ***");
System.out.println("sTop = "+sTop);
System.out.println("sVelocity = "+sVelocity);
}
public void draw(Canvas canvas) {
canvas.drawBitmap(mImage, null, mImageRect1, null);
canvas.drawBitmap(mImage, null, mImageRect2, null);
}
public void update() {
// Ground should update only if game not over yet
if(!GameView.sGameOver) {
// get delta time
mDeltaTime = GameView.getDeltaTime();
// update left/right coordinates of both Rects
mImageRect1.left = Math.round(mImageRect1.left - sVelocity*mDeltaTime);
mImageRect1.right = Math.round(mImageRect1.right - sVelocity*mDeltaTime);
mImageRect2.left = Math.round(mImageRect2.left - sVelocity*mDeltaTime);
mImageRect2.right = Math.round(mImageRect2.right - sVelocity*mDeltaTime);
// reset Rects if going out of screen
if (mImageRect1.right <= 0) {
mImageRect1.left = 0;
mImageRect1.right = mFrameWidth;
mImageRect2.left = mImageRect1.right;
mImageRect2.right = mFrameWidth * 2;
}
}
}
public boolean isColliding(Bird bird) {
// return true if bird is below ground i.e bird's Y-pos less than sTop
if(bird.getYpos()+(bird.getImage().getHeight()/2 )> sTop) {
bird.jump();
return true;
}
return false;
}
}
|
package javaBasics;
public class ConstructorConcept {
public ConstructorConcept(){ //when there are no parameters it is called default constructor
System.out.println("default constructor"); // we don't need to create this default constructor - it is created automatically and is hidden
}
public ConstructorConcept(int i){
System.out.println("single param constructor");
System.out.println("the value of i" + i);
}
public ConstructorConcept(int i, int j){
System.out.println("two params constructor");
System.out.println("the value of i" + i);
System.out.println("the value of j" + j);
}
public static void main(String[] args) {
ConstructorConcept obj = new ConstructorConcept();
ConstructorConcept obj1 = new ConstructorConcept(10);
ConstructorConcept obj2 = new ConstructorConcept(10,20);
}
}
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class MoneyChangeDynamic {
private static class ChangeData {
// money -> amount of coins for change
private Map<Integer, Integer> map = new HashMap<>(Collections.singletonMap(0, 0));
private int getMinNumCoins(int money) {
return map.getOrDefault(money, -1);
}
private void addOrReplaceNumCoins(int money, int numCoins) {
map.put(money, numCoins);
}
}
private static int DPChange(int money, int[] coins) {
if (money == 0) {
return 0;
}
ChangeData changeData = new ChangeData();
for (int m = 1; m <= money; m++) {
for (int coin : coins) {
if (m >= coin) {
int numCoinsPossible = changeData.getMinNumCoins(m - coin) + 1;
int numCoinsActual = changeData.getMinNumCoins(m);
if (numCoinsActual == -1 || numCoinsActual > numCoinsPossible) {
changeData.addOrReplaceNumCoins(m, numCoinsPossible);
}
}
}
}
return changeData.getMinNumCoins(money);
}
public static void main(String[] args) {
FastScanner scanner = new FastScanner(System.in);
int money = scanner.nextInt();
int[] coins = {1, 3, 4};
System.out.println(DPChange(money, coins));
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
|
package com.example.network;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
/**
* Created by ouyangshen on 2017/11/11.
*/
@SuppressLint("DefaultLocale")
public class JsonParseActivity extends AppCompatActivity implements OnClickListener {
private TextView tv_json;
private String mJsonStr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json_parse);
tv_json = findViewById(R.id.tv_json);
findViewById(R.id.btn_construct_json).setOnClickListener(this);
findViewById(R.id.btn_parser_json).setOnClickListener(this);
findViewById(R.id.btn_traverse_json).setOnClickListener(this);
mJsonStr = getJsonStr();
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_construct_json) {
// 显示完整的json串
tv_json.setText(mJsonStr);
} else if (v.getId() == R.id.btn_parser_json) {
// 显示json串解析后的各个参数值
tv_json.setText(parserJson(mJsonStr));
} else if (v.getId() == R.id.btn_traverse_json) {
// 显示json串的遍历结果串
tv_json.setText(traverseJson(mJsonStr));
}
}
// 获取一个手动构造的json串
private String getJsonStr() {
String str = "";
// 创建一个JSON对象
JSONObject obj = new JSONObject();
try {
// 添加一个名叫name的字符串参数
obj.put("name", "address");
// 创建一个JSON数组对象
JSONArray array = new JSONArray();
for (int i = 0; i < 3; i++) {
JSONObject item = new JSONObject();
// 添加一个名叫item的字符串参数
item.put("item", "第" + (i + 1) + "个元素");
// 把item这个JSON对象加入到JSON数组
array.put(item);
}
// 添加一个名叫list的数组参数
obj.put("list", array);
// 添加一个名叫count的整型参数
obj.put("count", array.length());
// 添加一个名叫desc的字符串参数
obj.put("desc", "这是测试串");
// 把JSON对象转换为json字符串
str = obj.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return str;
}
// 解析json串内部的各个参数
private String parserJson(String jsonStr) {
String result = "";
try {
// 根据json串构建一个JSON对象
JSONObject obj = new JSONObject(jsonStr);
// 获得名叫name的字符串参数
String name = obj.getString("name");
// 获得名叫desc的字符串参数
String desc = obj.getString("desc");
// 获得名叫count的整型参数
int count = obj.getInt("count");
result = String.format("%sname=%s\n", result, name);
result = String.format("%sdesc=%s\n", result, desc);
result = String.format("%scount=%d\n", result, count);
// 获得名叫list的数组参数
JSONArray listArray = obj.getJSONArray("list");
for (int i = 0; i < listArray.length(); i++) {
// 获得数组中指定下标的JSON对象
JSONObject list_item = listArray.getJSONObject(i);
// 获得名叫item的字符串参数
String item = list_item.getString("item");
result = String.format("%s\titem=%s\n", result, item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
// 遍历json串保存的键值对信息
private String traverseJson(String jsonStr) {
String result = "";
try {
// 根据json串构建一个JSON对象
JSONObject obj = new JSONObject(jsonStr);
// 获得JSON对象内部的键名称迭代器
Iterator<String> it = obj.keys();
while (it.hasNext()) { // 遍历JSONObject
String key = it.next(); // 获得下一个键的名称
String value = obj.getString(key); // 获得与该键对应的值信息
result = String.format("%skey=%s, value=%s\n", result, key, value);
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
|
package my;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* @author liming.gong
*/
@Component("personLogger")
@Aspect
public class PersonLogger {
/**
* 定义切面,拦截方法
* execution(
* public : 方法的修饰词(*代表所有)
* String : 方法的返回值(*代表所有)
* my..* : 包com.anting和其下面所有子包的所有类(..表示包含子包下的所有类)
* .run* : 方法名,此处可指定类名以run开头(*run*表示方法名只需要run即可,类似*run)
* (..) : 接受的参数类型,(..表示所有参数)[(int,*)表示接受参数为2个,其中第一个为int类型,第二个任一]
* )
*/
@Pointcut("execution (public * my..*.run*(..))")
public void pointCutMethod() {
System.out.println("pointCutMethod 切面拦截方法");
}
@Around("pointCutMethod()")
public void around(ProceedingJoinPoint joinpoint) throws Throwable {
//可以先做一些判断
if (true) {
System.out.println("方法条件满足,开始执行方法!");
joinpoint.proceed();
System.out.println("执行方法完毕!");
}
}
}
|
package mx.com.azaelmorales.yurtaapp;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.IntegerRes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import mx.com.azaelmorales.yurtaapp.utilerias.Servidor;
public class ObraAgregarMaterialActivity extends AppCompatActivity implements View.OnClickListener {
private ListView listViewMaterial;
private SearchView searchView;
private TextView textViewNombre,textViewExistencias,textViewMarca;
private Button buttonAdd,buttonSub;
private ArrayList<Material> listaMaterial;
private AdapterMaterial adaptador;
private TextView textViewID,textViewLugar;
private String tipoObra;
private ArrayList<Pedido> arrayListPedidos;
private EditText editTextCantidad;
static ArrayList<Material> arrayListMateriales;
private int cantidad=0;
ArrayList<Material> listaMaterialesPedido;
Material material;
private boolean buscar;
private Button buttonAgregarMaterial;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_obra_agregar_material);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar_materiales);
setSupportActionBar(toolbar);
toolbar.setTitle("Materiales");
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity(new Intent(getApplicationContext(),HomeActivity.class));
finish();
}
});
arrayListPedidos = new ArrayList<Pedido>();
listaMaterialesPedido = new ArrayList<Material>();
listViewMaterial =(ListView)findViewById(R.id.listViewMaterialAdd);
searchView =(SearchView)findViewById(R.id.search_material);
textViewNombre = (TextView)findViewById(R.id.textViewNombreMat);
textViewMarca = (TextView)findViewById(R.id.textViewMarcaMat);
textViewExistencias =(TextView)findViewById(R.id.textViewExisMat);
buttonAdd =(Button)findViewById(R.id.buttonAdd);
buttonSub = (Button)findViewById(R.id.buttonSub);
buttonAgregarMaterial = (Button)findViewById(R.id.buttonAgregarMaterial);
editTextCantidad =(EditText)findViewById(R.id.editTextCantidadMat);
buttonAdd.setOnClickListener(this);
buttonSub.setOnClickListener(this);
buttonAgregarMaterial.setOnClickListener(this);
cargarDatos();
Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b!=null){
}
listViewMaterial.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(buscar){
textViewNombre.setText("Nombre: " + AdapterMaterial.listaFiltrada.get(i).getNombre());
textViewMarca.setText("Marca: "+ AdapterMaterial.listaFiltrada.get(i).getMarca());
textViewExistencias.setText("Existencias: " + AdapterMaterial.listaFiltrada.get(i).getExistecias());
buscar = false;
}else{
textViewNombre.setText("Nombre: " + listaMaterial.get(i).getNombre());
textViewMarca.setText("Marca: "+ listaMaterial.get(i).getMarca());
textViewExistencias.setText("Existencias: " + listaMaterial.get(i).getExistecias());
}
Material materialAux = buscarMaterial(listaMaterial.get(i).getCodigo());
if(materialAux!=null){
cantidad = Integer.parseInt(materialAux.getCantidadSolicitada());
material = materialAux;
}else{
cantidad =0;
material = listaMaterial.get(i);
}
editTextCantidad.setText(""+cantidad);
}
});
}
private void cargarDatos(){
String url = "http://dissymmetrical-diox.xyz/mostrarMaterial.php";
RequestQueue requestQueue = Volley.newRequestQueue(ObraAgregarMaterialActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
response = response.replace("][",",");
try {
JSONArray jsonArray = new JSONArray(response);
cargarListView(jsonArray);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String query) {
buscar =true;
adaptador.getFilter().filter(query);
return false;
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(ObraAgregarMaterialActivity.this,"Error al cargar los datos" ,Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
}
private void cargarListView(JSONArray jsonArray) throws JSONException {
//pasa el json devuelto por el query a una matriz de String
int longitud = jsonArray.length();
int columnas = 6;
listaMaterial = new ArrayList<Material>();
Material material;
for (int i=0; i<longitud; i+=columnas) {
material = new Material(jsonArray.getString(i),jsonArray.getString(i+1),
jsonArray.getString(i+2),jsonArray.getString(i+3),
jsonArray.getString(i+4),jsonArray.getString(i+5),"0");
listaMaterial.add(material);
}
adaptador = new AdapterMaterial(ObraAgregarMaterialActivity.this,listaMaterial);
listViewMaterial.setAdapter(adaptador);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_agregar_material, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.nav_aceptar:
ObraAgregarFragment.arrayListMateriales = listaMaterialesPedido;
AdapterMaterialSolicitado adaptador;
adaptador = new AdapterMaterialSolicitado(ObrasActivity.getAppContext(), listaMaterialesPedido);
ObraAgregarFragment.listViewMaterialesPedidos.setAdapter(adaptador);
finish();
return true;
case R.id.nav_cancelar:
finish();
return true;
case R.id.nav_ver_lista:
for(int i=0; i<listaMaterialesPedido.size(); i++)
Toast.makeText(this,"Material Pedido: " + listaMaterialesPedido.get(i).getNombre()
+ "Cantidad solicitada: " +listaMaterialesPedido.get(i).getCantidadSolicitada()
,Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onClick(View view) {
if(view==buttonSub){
cantidad--;
if(cantidad<=0)
cantidad =0;
editTextCantidad.setText(""+cantidad);
}else if(view==buttonAdd){
cantidad++;
if(cantidad>Integer.parseInt(material.getExistecias())){
cantidad = Integer.parseInt(material.getExistecias());
}
editTextCantidad.setText(""+cantidad);
}else if(view ==buttonAgregarMaterial){
if(!actualizarMaterialP(material.getCodigo(),cantidad+"")){
material.setCantidadSolicitada(""+cantidad);
listaMaterialesPedido.add(material);
}
}
}
public Material buscarMaterial(String codigo){
for(int i=0; i<listaMaterialesPedido.size(); i++)
if(listaMaterialesPedido.get(i).getCodigo().equals(codigo))
return listaMaterialesPedido.get(i);
return null;
}
public boolean actualizarMaterialP(String codigo,String cantidad){
for(int i=0; i<listaMaterialesPedido.size(); i++){
if(listaMaterialesPedido.get(i).getCodigo().equals(codigo)){
listaMaterialesPedido.get(i).setCantidadSolicitada(cantidad);
return true;
}
}
return false;
}
}
|
package com.user188245.util.rsort;
class ByteBitExtractor implements BitExtractor<Byte>{
@Override
public int bitSize() {
return 8;
}
@Override
public boolean getSignificantBit(Byte elem, int exp) {
return (((elem + -128) >>> exp) & 1) == 1;
}
}
|
package com.ljx.javaFx.utils;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.MultimediaInfo;
import java.io.File;
/**
* @author lijx
* @date 2019/4/15 - 18:07
*/
public class VideoUtil {
private static Encoder encoder = new Encoder();
public static String getVideoTimeString(File source) {
Encoder encoder = new Encoder();
String length = "";
try {
MultimediaInfo m = encoder.getInfo(source);
long ls = m.getDuration() / 1000;
int hour = (int) (ls / 3600);
int minute = (int) (ls % 3600) / 60;
int second = (int) (ls - hour * 3600 - minute * 60);
length = hour + ":" + minute + ":" + second + ":'";
} catch (Exception e) {
e.printStackTrace();
}
return length;
}
public static long getVideoTimeSeconds(File source) {
long result = 0;
try {
MultimediaInfo m = encoder.getInfo(source);
result = m.getDuration() / 1000;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
|
package com.github.emailtohl.integration.core;
import java.io.Serializable;
import java.security.SecureRandom;
import java.util.List;
import java.util.Set;
import javax.transaction.Transactional;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCrypt;
import com.github.emailtohl.lib.exception.NotAcceptableException;
import com.github.emailtohl.lib.jpa.Paging;
/**
* 抽象的服务,主要就是增删改查功能。
*
* 标准化参数名、参数类型以及返回后,不仅利于维护,更利于在切面层进行扩展。
*
* 默认ID是Long类型
*
* @author HeLei
*/
@Transactional
public abstract class StandardService<E extends Serializable> {
/**
* Service尽量做到无状态,但是有些Service需要获取到当前用户信息
* 这里使用线程本地存储域,在Service外部统一设置当前用户id或唯一识别用户名
* Service内部就能根据id查询到当前用户信息
*/
public static final ThreadLocal<Long> CURRENT_USER_ID = new ThreadLocal<Long>();
public static final ThreadLocal<String> CURRENT_USERNAME = new ThreadLocal<String>();
protected static final Logger LOG = LogManager.getLogger();
/**
* 由于接口+抽象类的加入使得@Valid注解不能使用,所以可进行手动校验
*/
protected static final ValidatorFactory FACTORY = Validation.buildDefaultValidatorFactory();
protected Validator validator = FACTORY.getValidator();
protected static final transient int HASHING_ROUNDS = 10;
/**
* 创建一个实体
* @param entity
* @return
*/
public abstract E create(E entity);
/**
* 根据实体自身唯一性的属性查找是否已存在
* @param matcherValue
* @return
*/
public abstract boolean exist(Object matcherValue);
/**
* 根据ID获取实体
* @param id
* @return
*/
public abstract E get(Long id);
/**
* 分页查询
* @param params
* @param pageable
* @return Paging封装的分页信息,一般JPA底层返回的是Page对象,但该对象不利于JSON等序列化。
* 所以在将持久化状态的实体转瞬态时,同时改变分页对象
*/
public abstract Paging<E> query(E params, Pageable pageable);
/**
* 查询列表
* @param params
* @return
*/
public abstract List<E> query(E params);
/**
* 修改实体内容,并指明哪些属性忽略
* @param id
* @param newEntity
* @return 返回null表示没找到该实体
*/
public abstract E update(Long id, E newEntity);
/**
* 根据ID删除实体
* @param id
*/
public abstract void delete(Long id);
/**
* 屏蔽实体中的敏感信息,如密码;将持久化状态的实体转存到瞬时态的实体对象上以便于调用者序列化
* 本方法提取简略信息,不做关联查询,主要用于列表中
* @param entity 持久化状态的实体对象
* @return 瞬时态的实体对象
*/
protected abstract E toTransient(E entity);
/**
* 屏蔽实体中的敏感信息,如密码;将持久化状态的实体转存到瞬时态的实体对象上以便于调用者序列化
* 本方法提取详细信息,做关联查询
* @param entity 持久化状态的实体对象
* @return 瞬时态的实体对象
*/
protected abstract E transientDetail(@Valid E entity);
/**
* 手动校验对象是否符合约束条件
* @param entity 被校验的实体对象
* @throws 若不符合则抛出自定义NotAcceptableException异常
*/
public void validate(E entity) {
Set<ConstraintViolation<E>> violations = validator.validate(entity);
if (violations.size() > 0) {
violations.forEach(v -> LOG.debug(v));
throw new NotAcceptableException(new ConstraintViolationException(violations));
}
}
/**
* 手动校验对象是否符合约束条件
* @param obj 被校验的对象
* @param clz 被校验的对象的类型
* @throws 若不符合则抛出自定义NotAcceptableException异常
*/
public <T> void validate(T obj, Class<T> clz) {
Set<ConstraintViolation<T>> violations = validator.validate(obj);
if (violations.size() > 0) {
violations.forEach(v -> LOG.debug(v));
throw new NotAcceptableException(new ConstraintViolationException(violations));
}
}
/**
* Hash加密密码
* @param password 明文密码
* @return 被Hash加密过的密文密码
*/
public String hashpw(String password) {
String salt = BCrypt.gensalt(HASHING_ROUNDS, new SecureRandom());
return BCrypt.hashpw(password, salt);
}
/**
* 检查明文密码是否与被加密过的密码是否一致
* @param plaintext 明文密码
* @param hashed 被加密后的密文密码
* @return 校验结果
*/
public boolean checkpw(String plaintext, String hashed) {
return BCrypt.checkpw(plaintext, hashed);
}
/**
* 判断字符串是否存在
* @param text 字符串
* @return 是否为空的结果
*/
public boolean hasText(String text) {
return text != null && !text.isEmpty();
}
}
|
package com.tencent.mm.g.a;
public final class qp$a {
public String id;
public int type;
}
|
package com.shagaba.kickstarter.rest.domain.security.account;
public class ChallengeQuestion {
protected String question;
protected String answer;
/**
* @return the question
*/
public String getQuestion() {
return question;
}
/**
* @param question the question to set
*/
public void setQuestion(String question) {
this.question = question;
}
/**
* @return the answer
*/
public String getAnswer() {
return answer;
}
/**
* @param answer the answer to set
*/
public void setAnswer(String answer) {
this.answer = answer;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return String.format("ChallengeQuestion {question=%s, answer=%s}", question, answer);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((answer == null) ? 0 : answer.hashCode());
result = prime * result + ((question == null) ? 0 : question.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ChallengeQuestion other = (ChallengeQuestion) obj;
if (answer == null) {
if (other.answer != null)
return false;
} else if (!answer.equals(other.answer))
return false;
if (question == null) {
if (other.question != null)
return false;
} else if (!question.equals(other.question))
return false;
return true;
}
}
|
package cn.yami.wechat.demo.exception;
import cn.yami.wechat.demo.entity.Result;
import cn.yami.wechat.demo.enums.CodeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
public Result<String> exceptionHandler(HttpServletRequest request,Exception e){
e.printStackTrace();
if (e instanceof GlobalException){
GlobalException exception = (GlobalException) e;
return Result.error(exception.getCodeMessage());
}
else if (e instanceof BindException){
BindException exception = (BindException) e;
List<ObjectError> errorList = exception.getAllErrors();
return Result.error(CodeMessage.BIND_ERROR.fillArgs(errorList.get(0).getDefaultMessage()));
}else {
return Result.error(CodeMessage.SERVER_ERROR);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.