text
stringlengths 10
2.72M
|
|---|
package com.apprisingsoftware.util;
public final class Perlin2 {
private static final double INT_MAX_VALUE = Integer.MAX_VALUE + 1.0;
private final int seed;
private final int octaves;
private final double persistence;
private final double yStretch;
public Perlin2(int seed, int octaves, double persistence, double yStretch) {
this.seed = seed;
this.octaves = octaves;
this.persistence = persistence;
this.yStretch = yStretch;
}
public double perlinNoise(double x, double y) {
double total = 0;
for (int i=0; i<octaves; i++) {
double frequency = Math.pow(2, i);
double amplitude = Math.pow(persistence, i);
total += interpolatedNoise(x * frequency, y * frequency / yStretch) * amplitude;
}
return total;
}
public double getMinimumValue() {
return 0;
}
public double getMaximumValue() {
return (1 - Math.pow(persistence, octaves)) / (1 - persistence);
}
public double getExpectedValue() {
return getMaximumValue() / 2;
}
/**
* Range: [0, 1]
* Expected: 0.5
*/
private double interpolatedNoise(double x, double y) {
int iPartX = (int) Math.floor(x);
double fPartX = x - iPartX;
int iPartY = (int) Math.floor(y);
double fPartY = y - iPartY;
double leftFloor = smoothedNoise(iPartX, iPartY);
double rightFloor = smoothedNoise(iPartX + 1, iPartY);
double leftCeil = smoothedNoise(iPartX, iPartY + 1);
double rightCeil = smoothedNoise(iPartX + 1, iPartY + 1);
double midFloor = interpolateCosine(leftFloor, rightFloor, fPartX);
double midCeil = interpolateCosine(leftCeil, rightCeil, fPartX);
return interpolateCosine(midFloor, midCeil, fPartY);
}
/**
* Range: [left, right]
* Expected: N/A
*/
private double interpolateCosine(double left, double right, double xFrac) {
double yFrac = (1 - Math.cos(xFrac * Math.PI)) / 2;
return left + (right - left) * yFrac;
}
/**
* Range: [0, 1)
* Expected: 0.5
*/
private double smoothedNoise(int x, int y) {
return
(noise(x-1, y-1) + noise(x-1, y+1) + noise(x+1, y-1) + noise(x+1, y+1)) / 16 +
(noise(x, y-1) + noise(x, y+1) + noise(x-1, y) + noise(x+1, y)) / 8 +
(noise(x, y)) / 4;
}
/**
* Range: [0, 1)
* Expected: 0.5
*/
private double noise(int x, int y) {
x = x + y * 57 + seed * 37;
x = (x << 13) ^ x;
return ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7FFFFFFF) / INT_MAX_VALUE;
}
}
|
package dailyPractice.jianzhi;
public class Q17 {
public int[] printNumbers(int n) {
StringBuffer string = new StringBuffer();
for (int i = 1; i <= n; i++) {
string.append(9);
}
int max = Integer.parseInt(string.toString());
int[] res = new int[max];
for (int i = 0; i < max; i++) {
res[i] = i + 1;
}
return res;
}
}
|
package Game;
import java.util.Scanner;
public class Lifecycle {
private final MainForm mainForm;
private final Scanner inMessage;
public Lifecycle(MainForm mainForm, Scanner inMessage) {
this.mainForm = mainForm;
this.inMessage = inMessage;
}
public void start() {
while (true) {
if (inMessage.hasNext()) {
String inMsg = inMessage.nextLine();
switch (inMsg) {
case "Player 1":
mainForm.setPlayerFirst(true);
break;
case "Player 2":
mainForm.setPlayerFirst(false);
break;
case "Start game":
mainForm.startGame();
break;
default:
String[] data = inMsg.split("/");
int x = Integer.parseInt(data[0]);
int y = Integer.parseInt(data[1]);
int playerNum = Integer.parseInt(data[2]);
mainForm.move(x, y, playerNum);
break;
}
}
}
}
}
|
package io.swagger.client.api;
import io.swagger.client.ApiException;
import io.swagger.client.ApiClient;
import io.swagger.client.Configuration;
import io.swagger.client.model.*;
import java.util.*;
import io.swagger.client.model.WebhookListResponse;
import io.swagger.client.model.CreateWebhook;
import io.swagger.client.model.WebhookSubscription;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.util.Map;
import java.util.HashMap;
import java.net.URL;
import java.net.MalformedURLException;
public class WebhooksubscriptionsApi {
private ApiClient apiClient;
private String[] authNames = new String[] { "oauth2" };
public WebhooksubscriptionsApi() {
this(Configuration.getDefaultApiClient());
}
public WebhooksubscriptionsApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Get the list of webhooks.
*
* @return WebhookListResponse
*/
public WebhookListResponse list () throws ApiException {
Object postBody = null;
// create path and map variables
String path = "/webhook-subscriptions".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (WebhookListResponse) apiClient.deserialize(response, "", WebhookListResponse.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Create a new webhook subscription.
*
* @param body Webhook subscription to create.
* @return WebhookSubscription
*/
public WebhookSubscription create (CreateWebhook body) throws ApiException {
Object postBody = body;
// create path and map variables
String path = "/webhook-subscriptions".replaceAll("\\{format\\}","json");
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/vnd.dwolla.v1.hal+json"
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (WebhookSubscription) apiClient.deserialize(response, "", WebhookSubscription.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Get a webhook subscription by id.
*
* @param id ID of webhook subscription to get.
* @return WebhookSubscription
*/
public WebhookSubscription id (String id) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling id");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/webhook-subscriptions/{id}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (WebhookSubscription) apiClient.deserialize(response, "", WebhookSubscription.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
/**
* Delete a webhook subscription by id.
*
* @param id ID of webhook subscription to delete.
* @return WebhookSubscription
*/
public WebhookSubscription deleteById (String id) throws ApiException {
Object postBody = null;
// verify the required parameter 'id' is set
if (id == null) {
throw new ApiException(400, "Missing the required parameter 'id' when calling deleteById");
}
// if a URL is provided, extract the ID
URL u;
try {
u = new URL(id);
id = id.substring(id.lastIndexOf('/') + 1);
}
catch (MalformedURLException mue) {
u = null;
}
// create path and map variables
String path = "/webhook-subscriptions/{id}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "id" + "\\}", apiClient.escapeString(id.toString()));
// query params
Map<String, String> queryParams = new HashMap<String, String>();
Map<String, String> headerParams = new HashMap<String, String>();
Map<String, String> formParams = new HashMap<String, String>();
final String[] accepts = {
"application/vnd.dwolla.v1.hal+json"
};
final String accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
};
final String contentType = apiClient.selectHeaderContentType(contentTypes);
if(contentType.startsWith("multipart/form-data")) {
boolean hasFields = false;
FormDataMultiPart mp = new FormDataMultiPart();
if(hasFields)
postBody = mp;
}
else {
}
try {
String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, this.authNames);
if(response != null){
return (WebhookSubscription) apiClient.deserialize(response, "", WebhookSubscription.class);
}
else {
return null;
}
} catch (ApiException ex) {
throw ex;
}
}
}
|
package com.tencent.mm.plugin.fts.b;
import android.database.Cursor;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.fts.a.a.a;
import com.tencent.mm.plugin.fts.a.a.h;
import com.tencent.mm.plugin.fts.a.a.i;
import com.tencent.mm.plugin.fts.a.a.j;
import com.tencent.mm.plugin.fts.a.m;
import com.tencent.mm.plugin.fts.a.n;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
public final class d extends com.tencent.mm.plugin.fts.a.b {
private m dhW;
com.tencent.mm.plugin.fts.c.d juL;
public class b extends a {
public final boolean execute() {
d.this.juL.jpT.execSQL(String.format("DELETE FROM %s ;", new Object[]{"FTS5MetaSOSHistory"}));
return true;
}
public final String getName() {
return "DeleteSOSHistoryTask";
}
}
public class d extends h {
public d(i iVar) {
super(iVar);
}
protected final void a(j jVar) {
Cursor rawQuery;
super.a(jVar);
jVar.jsx = new ArrayList();
com.tencent.mm.plugin.fts.c.d dVar = d.this.juL;
String str = this.jsj.bWm;
int i = this.jsj.jss;
if (str.trim().length() > 0) {
str = com.tencent.mm.plugin.fts.a.d.u(new String[]{str});
rawQuery = dVar.jpT.rawQuery(String.format("SELECT history FROM %s NOT INDEXED JOIN %s ON (%s.docid = %s.rowid) WHERE %s MATCH '%s' ORDER BY timestamp desc LIMIT " + i, new Object[]{"FTS5MetaSOSHistory", "FTS5IndexSOSHistory", "FTS5MetaSOSHistory", "FTS5IndexSOSHistory", "FTS5IndexSOSHistory", str}), null);
} else {
rawQuery = dVar.jpT.rawQuery(String.format("SELECT history FROM %s ORDER BY timestamp desc LIMIT " + i, new Object[]{"FTS5MetaSOSHistory"}), null);
}
while (rawQuery.moveToNext()) {
str = rawQuery.getString(0);
com.tencent.mm.plugin.fts.a.a.m mVar = new com.tencent.mm.plugin.fts.a.a.m();
mVar.content = str;
jVar.jsx.add(mVar);
}
rawQuery.close();
}
public final String getName() {
return "SearchSOSHistoryTask";
}
}
public final String getName() {
return "FTS5SearchSOSHistoryLogic";
}
protected final boolean onCreate() {
if (((n) g.n(n.class)).isFTSContextReady()) {
x.i("MicroMsg.FTS.FTS5SearchSOSHistoryLogic", "Create Success!");
this.juL = (com.tencent.mm.plugin.fts.c.d) ((n) g.n(n.class)).getFTSIndexStorage(1024);
this.dhW = ((n) g.n(n.class)).getFTSTaskDaemon();
return true;
}
x.i("MicroMsg.FTS.FTS5SearchSOSHistoryLogic", "Create Fail!");
return false;
}
public final void addSOSHistory(String str) {
a aVar = new a(this);
aVar.juM = str;
this.dhW.a(132072, aVar);
}
public final void deleteSOSHistory() {
this.dhW.a(132072, new b());
}
public final void deleteSOSHistory(String str) {
c cVar = new c(this);
cVar.juM = str;
this.dhW.a(132072, cVar);
}
public final a a(i iVar) {
d dVar = new d(iVar);
this.dhW.a(-65536, dVar);
return dVar;
}
protected final boolean BT() {
this.juL = null;
this.dhW = null;
return true;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.o;
import com.tencent.mm.plugin.appbrand.jsapi.h;
public class c$b extends h {
private static final int CTRL_INDEX = -2;
private static final String NAME = "onTouchCancel";
}
|
package com.example;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
@Named
@ViewScoped
public class ParametersBean implements Serializable {
private static final long serialVersionUID = 1L;
private List<Parameter> parameters;
private Parameter selectedParameter;
@Inject
private FunctionsBean functions;
/*
public void onRowSelect(SelectEvent event) {
log("ParametersBean.onRowSelect(), Selected : " + ((Parameter) event.getObject()).getName());
}
*/
@PostConstruct
public void afterCreate() {
log("ParametersBean.afterCreate() ... ... ...");
}
public void reload() {
if (functions != null && functions.getSelectedFunction() != null) {
Function function = functions.getSelectedFunction();
log("ParametersBean, load ... ... ... function id = " + function.getId());
parameters = DataLoader.getDataLoader().loadParameters(function);
}
else {
log("ParametersBean, load/reset ... ... ...");
parameters = new ArrayList<>();
}
}
public void reset() {
log("ParametersBean, reset ... ... ...");
parameters = new ArrayList<>();
}
public List<Parameter> getParameters() {
return parameters;
}
public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}
public Parameter getSelectedParameter() {
return selectedParameter;
}
public void setSelectedParameter(Parameter selectedParameter) {
this.selectedParameter = selectedParameter;
}
private static void log(String message) {
System.err.println(message);
}
}
|
package io.makeabilitylab.facetrackerble;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.Tracker;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.google.android.gms.vision.face.LargestFaceFocusingProcessor;
import java.io.IOException;
import io.makeabilitylab.facetrackerble.ble.BLEDevice;
import io.makeabilitylab.facetrackerble.ble.BLEListener;
import io.makeabilitylab.facetrackerble.ble.BLEUtil;
import io.makeabilitylab.facetrackerble.camera.CameraSourcePreview;
import io.makeabilitylab.facetrackerble.camera.GraphicOverlay;
/**
* Demonstrates how to use the Google Android Vision API--specifically the FaceDetector--along
* with the RedBear Duo. The app detects faces in real-time and transmits left eye and right eye
* state information (open probability) along with basic emotion inference (sad/happiness probability).
*
* It is based on:
* - The Google Code Lab tutorial: https://codelabs.developers.google.com/codelabs/face-detection/index.html#1
* - The Google Mobile Vision Face Tracker tutorial: https://developers.google.com/vision/android/face-tracker-tutorial
* - The FaceTracker demo: https://github.com/googlesamples/android-vision/tree/master/visionSamples/FaceTracker
* - The Googly Eyes demo: https://github.com/googlesamples/android-vision/tree/master/visionSamples/googly-eyes
* - The CSE590 BLE demo: https://github.com/jonfroehlich/CSE590Sp2018/tree/master/A03-BLEAdvanced
*
* Jon TODO:
* 1. (Low priority) We shouldn't disconnect from BLE just because our orientation changed (e.g., from Portrait to Landscape). How to deal?
*/
public class MainActivity extends AppCompatActivity implements BLEListener{
private static final String TAG = "FaceTrackerBLE";
private static final int RC_HANDLE_GMS = 9001;
private static final int CAMERA_PREVIEW_WIDTH = 640;
private static final int CAMERA_PREVIEW_HEIGHT = 480;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private CameraSource mCameraSource = null;
private CameraSourcePreview mPreview;
private GraphicOverlay mGraphicOverlay;
private boolean mIsFrontFacing = true;
// Bluetooth stuff
private BLEDevice mBLEDevice;
// TODO: Define your device name and the length of the name. For your assignment, do not use the
// default name or you will not be able to discriminate your board from everyone else's board.
// Note the device name and the length should be consistent with the ones defined in the Duo sketch
private final String TARGET_BLE_DEVICE_NAME = "MakeLab";
//==============================================================================================
// Activity Methods
//==============================================================================================
/**
* Initializes the UI and initiates the creation of a face detector.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPreview = (CameraSourcePreview) findViewById(R.id.cameraSourcePreview);
mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
final Button button = (Button) findViewById(R.id.buttonFlip);
button.setOnClickListener(mFlipButtonListener);
if (savedInstanceState != null) {
mIsFrontFacing = savedInstanceState.getBoolean("IsFrontFacing");
}
// Check for the camera permission before accessing the camera. If the
// permission is not granted yet, request permission.
int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (rc == PackageManager.PERMISSION_GRANTED) {
createCameraSource();
} else {
requestCameraPermission();
}
// Make sure that Bluetooth is supported.
if (!BLEUtil.isSupported(this)) {
Toast.makeText(this, "BLE not supported", Toast.LENGTH_SHORT)
.show();
finish();
return;
}
// Make sure that we have required permissions.
if (!BLEUtil.hasPermission(this)) {
BLEUtil.requestPermission(this);
}
// Make sure that Bluetooth is enabled.
if (!BLEUtil.isBluetoothEnabled(this)) {
BLEUtil.requestEnableBluetooth(this);
}
mBLEDevice = new BLEDevice(this, TARGET_BLE_DEVICE_NAME);
mBLEDevice.addListener(this);
attemptBleConnection();
}
/**
* Handles the requesting of the camera permission. This includes
* showing a "Snackbar" message of why the permission is needed then
* sending the request.
*/
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
// Snackbars are like Toasts
// See: https://stackoverflow.com/q/34432339
Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == BLEUtil.REQUEST_ENABLE_BLUETOOTH
&& !BLEUtil.isBluetoothEnabled(this)) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Creates and starts the camera. Note that this uses a higher resolution in comparison
* to other detection examples to enable the barcode detector to detect small barcodes
* at long distances.
*/
private void createCameraSource() {
int cameraFacing = mIsFrontFacing ? CameraSource.CAMERA_FACING_FRONT : CameraSource.CAMERA_FACING_BACK;
Context context = getApplicationContext();
// Setup the Google Vision FaceDetector:
// - https://developers.google.com/android/reference/com/google/android/gms/vision/face/FaceDetector
// We use the detector in a pipeline structure in conjunction with a source (Camera)
// and a processor (in this case, MultiProcessor.Builder<>(new FaceTrackerFactory()))
FaceDetector detector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.build();
// This processor distributes the items of detection results among individual trackers
// so that you can detect multiple faces.
// See: https://developers.google.com/android/reference/com/google/android/gms/vision/MultiProcessor
// MultiProcessor faceProcessor = new MultiProcessor.Builder<>(new FaceTrackerFactory()).build();
// This processor only finds the largest face in the frame.
LargestFaceFocusingProcessor faceProcessor = new LargestFaceFocusingProcessor(detector, new FaceTracker(mGraphicOverlay));
// set the detector's processor
detector.setProcessor(faceProcessor);
if (!detector.isOperational()) {
// Note: The first time that an app using face API is installed on a device, GMS will
// download a native library to the device in order to do detection. Usually this
// completes before the app is run for the first time. But if that download has not yet
// completed, then the above call will not detect any faces.
//
// isOperational() can be used to check if the required native library is currently
// available. The detector will automatically become operational once the library
// download completes on device.
Log.w(TAG, "Face detector dependencies are not yet available.");
}
// The face detector can run with a fairly low resolution image (e.g., 320x240)
// Running in lower images is significantly faster than higher resolution
// We've currently set this to 640x480
mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(CAMERA_PREVIEW_WIDTH, CAMERA_PREVIEW_HEIGHT)
.setFacing(cameraFacing)
.setRequestedFps(30.0f)
.build();
}
/**
* Restarts the camera.
*/
@Override
protected void onResume() {
super.onResume();
startCameraSource();
if (!BLEUtil.isBluetoothEnabled(this)) {
BLEUtil.requestEnableBluetooth(this);
}
}
/**
* Stops the camera.
*/
@Override
protected void onPause() {
super.onPause();
mPreview.stop();
}
@Override
protected void onStop() {
super.onStop();
if (mBLEDevice != null) {
mBLEDevice.disconnect();
}
}
/**
* Releases the resources associated with the camera source, the associated detector, and the
* rest of the processing pipeline.
*/
@Override
protected void onDestroy() {
super.onDestroy();
if (mCameraSource != null) {
mCameraSource.release();
}
}
/**
* Callback for the result from requesting permissions. This method
* is invoked for every call on {@link #requestPermissions(String[], int)}.
* <p>
* <strong>Note:</strong> It is possible that the permissions request interaction
* with the user is interrupted. In this case you will receive empty permissions
* and results arrays which should be treated as a cancellation.
* </p>
*
* @param requestCode The request code passed in {@link #requestPermissions(String[], int)}.
* @param permissions The requested permissions. Never null.
* @param grantResults The grant results for the corresponding permissions
* which is either {@link PackageManager#PERMISSION_GRANTED}
* or {@link PackageManager#PERMISSION_DENIED}. Never null.
* @see #requestPermissions(String[], int)
*/
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// Check user response to requesting bluetooth permissions
if (requestCode == BLEUtil.REQUEST_BLUETOOTH_PERMISSIONS) {
if(BLEUtil.hasPermission(this)){
attemptBleConnection();
}else{
finish();
return;
}
}
// Check user response to requesting camera permissions
if (requestCode == RC_HANDLE_CAMERA_PERM) {
if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "Camera permission granted - initialize the camera source");
// we have permission, so create the camerasource
createCameraSource();
return;
}
Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Face Tracker BLE Demo")
.setMessage(R.string.no_camera_permission)
.setPositiveButton(R.string.ok, listener)
.show();
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
//==============================================================================================
// UI
//==============================================================================================
/**
* Saves the camera facing mode, so that it can be restored after the device is rotated.
*/
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("IsFrontFacing", mIsFrontFacing);
}
/**
* Toggles between front-facing and rear-facing modes.
*/
private View.OnClickListener mFlipButtonListener = new View.OnClickListener() {
public void onClick(View v) {
mIsFrontFacing = !mIsFrontFacing;
if (mCameraSource != null) {
mCameraSource.release();
mCameraSource = null;
}
createCameraSource();
startCameraSource();
}
};
//==============================================================================================
// Camera Source Preview
//==============================================================================================
/**
* Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet
* (e.g., because onResume was called before the camera source was created), this will be called
* again when the camera source is created.
*/
private void startCameraSource() {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
//==============================================================================================
// Graphic Face Tracker
//==============================================================================================
/**
* Factory for creating a face tracker to be associated with a new face. The multiprocessor
* uses this factory to create face trackers as needed -- one for each individual.
*/
private class FaceTrackerFactory implements MultiProcessor.Factory<Face> {
@Override
public Tracker<Face> create(Face face) {
return new FaceTracker(mGraphicOverlay);
}
}
/**
* Face tracker for each detected individual. This maintains a face graphic within the app's
* associated face overlay.
*/
private class FaceTracker extends Tracker<Face> {
private GraphicOverlay mOverlay;
private FaceGraphic mFaceGraphic;
FaceTracker(GraphicOverlay overlay) {
mOverlay = overlay;
mFaceGraphic = new FaceGraphic(overlay);
}
/**
* Start tracking the detected face instance within the face overlay.
*/
@Override
public void onNewItem(int faceId, Face item) {
mFaceGraphic.setId(faceId);
}
/**
* Update the position/characteristics of the face within the overlay.
*/
@Override
public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
mOverlay.add(mFaceGraphic);
mFaceGraphic.updateFace(face);
// CSE590 Student TODO:
// Once a face is detected, you get lots of information about the face for free, including
// a smiling probability score, eye shut probability, and the location of the face in the
// camera image (note that we are using a small camera size to speedup processing:
// The dimensions are: CAMERA_PREVIEW_WIDTH x CAMERA_PREVIEW_HEIGHT
//
// You need to translate the location of the face into data that will be useful for your servo.
// For example, this code would translate the X location of the face into a range from 0-255:
// (centerOfFace.x / CAMERA_PREVIEW_WIDTH) * 255
// Since the servo motor can move in only one dimension, you only need to track one dimension of movement
//
// To properly calculate the location of the face, you may need to handle front facing vs. rear facing camera
// and portrait vs. landscape phone modes properly.
//
// You can also turn on Landmark detection to get more information about the face like cheek, ear, mouth, etc.
// See: https://developers.google.com/android/reference/com/google/android/gms/vision/face/Landmark
boolean isPortrait = (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
String debugFaceInfo = String.format("Portrait: %b Front-Facing Camera: %b FaceId: %d Loc (x,y): (%.1f, %.1f) Size (w, h): (%.1f, %.1f) Left Eye: %.1f Right Eye: %.1f Smile: %.1f",
isPortrait,
mIsFrontFacing,
face.getId(),
face.getPosition().x, face.getPosition().y,
face.getHeight(), face.getWidth(),
face.getIsLeftEyeOpenProbability(), face.getIsRightEyeOpenProbability(),
face.getIsSmilingProbability());
Log.i(TAG, debugFaceInfo);
// Come up with your own communication protocol to Arduino. Make sure that you change the
// RECEIVE_MAX_LEN in your Arduino code to match the # of bytes you are sending.
// For example, one protocol might be:
// 0 : Control byte
// 1 : left eye open probability (0-255 where 0 is eye closed and 1 is eye open)
// 2 : right eye open probability (0-255 where 0 is eye closed and 1 is eye open)
// 3 : happiness probability (0-255 where 0 sad, 128 is neutral, and 255 is happy)
// 4 : x-location of face (0-255 where 0 is left side of camera and 255 is right side of camera)
byte[] buf = new byte[] { (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00}; // 5-byte initialization
// CSE590 Student TODO:
// Write code that puts in your data into the buffer
// Send the data!
mBLEDevice.sendData(buf);
}
/**
* Hide the graphic when the corresponding face was not detected. This can happen for
* intermediate frames temporarily (e.g., if the face was momentarily blocked from
* view).
*/
@Override
public void onMissing(FaceDetector.Detections<Face> detectionResults) {
mOverlay.remove(mFaceGraphic);
}
/**
* Called when the face is assumed to be gone for good. Remove the graphic annotation from
* the overlay.
*/
@Override
public void onDone() {
mOverlay.remove(mFaceGraphic);
}
}
//==============================================================================================
// Bluetooth stuff
//==============================================================================================
private void attemptBleConnection(){
if(BLEUtil.hasPermission(this) &&
BLEUtil.isBluetoothEnabled(this) &&
mBLEDevice.getState() == BLEDevice.State.DISCONNECTED){
String msg = "Attempting to connect to '" + TARGET_BLE_DEVICE_NAME + "'";
Toast toast = Toast.makeText(
MainActivity.this,
msg,
Toast.LENGTH_LONG);
toast.show();
TextView textViewBleStatus = (TextView)findViewById(R.id.textViewBleStatus);
textViewBleStatus.setText(msg);
mBLEDevice.connect();
}
}
@Override
public void onBleConnected() {
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
TextView textViewBleStatus = (TextView)findViewById(R.id.textViewBleStatus);
textViewBleStatus.setText("Connected to '" + TARGET_BLE_DEVICE_NAME + "'");
}
@Override
public void onBleConnectFailed() {
Toast toast = Toast
.makeText(
MainActivity.this,
"Couldn't find the BLE device with name '" + TARGET_BLE_DEVICE_NAME + "'!",
Toast.LENGTH_SHORT);
toast.setGravity(0, 0, Gravity.CENTER);
toast.show();
TextView textViewBleStatus = (TextView)findViewById(R.id.textViewBleStatus);
textViewBleStatus.setText("BLE connection to '" + TARGET_BLE_DEVICE_NAME + "' failed");
// Jon TODO: We should really pause here before trying to reconnect...
// Have some sort of backoff
attemptBleConnection();
}
@Override
public void onBleDisconnected() {
Toast.makeText(getApplicationContext(), "Disconnected", Toast.LENGTH_SHORT).show();
TextView textViewBleStatus = (TextView)findViewById(R.id.textViewBleStatus);
textViewBleStatus.setText("Disconnected from '" + TARGET_BLE_DEVICE_NAME + "'");
// Jon TODO: We should really pause here before trying to reconnect...
// Have some sort of backoff
attemptBleConnection();
}
@Override
public void onBleDataReceived(byte[] data) {
// CSE590 Student TODO
// Write code here that receives the ultrasonic measurements from Arduino
// and outputs them in your app. (You could also consider receiving the angle
// of the servo motor but this would be more for debugging and is not necessary)
}
@Override
public void onBleRssiChanged(int rssi) {
// Not needed for this app
}
}
|
package com.b12.offer.controller;
import java.util.List;
import org.codehaus.jettison.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.b12.offer.constant.AllConstant;
import com.b12.offer.dto.OfferResponse;
import com.b12.offer.entity.Offer;
import com.b12.offer.service.OfferService;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
@RestController
@RequestMapping("/offers")
@Api(value="offer api", description="To uptain & add the offer details")
public class OfferController {
@Autowired
private OfferService offerService;
@ApiOperation(value = "get a offer details for a product", response = OfferResponse.class, tags = "GetOfferDetails")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully sending Offer details"),
@ApiResponse(code = 400, message = "Invalid Request"),
@ApiResponse(code = 500, message = "Internal Server Error"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
})
@GetMapping(value ="/{offerId}",produces = "application/json")
public ResponseEntity<OfferResponse> getOffer(@PathVariable Long offerId){
OfferResponse offerResponse = new OfferResponse();
ResponseEntity<OfferResponse> response = null;
if( offerId != null && offerId>0)
{
Offer offer = offerService.getOffer(offerId);
offerResponse.setResult(true);
offerResponse.setOfferCategory(offer.getOfferCategory());
offerResponse.setOfferId(offer.getOfferId());
offerResponse.setOfferPercentage(offer.getOfferPercentage());
offerResponse.setValidFrom(offer.getValidFrom());
offerResponse.setValidUpto(offer.getValidUpto());
response = new ResponseEntity<OfferResponse>(offerResponse, HttpStatus.OK);
}else {
offerResponse.setMessage(AllConstant.INVALID_OFFER_ID);
offerResponse.setResult(false);
response = new ResponseEntity<OfferResponse>(offerResponse, HttpStatus.BAD_REQUEST);
}
return response;
}
@ApiOperation(value = "save a offer details for a product", response = OfferResponse.class, tags = "AddOfferDetails")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully added the Offer details"),
@ApiResponse(code = 400, message = "Invalid Request"),
@ApiResponse(code = 500, message = "Internal Server Error"),
})
@PostMapping(value = "/",produces = "application/json")
public ResponseEntity<OfferResponse> addOffer(@RequestBody Offer offer){
Offer offerReturned = offerService.addOffer(offer);
OfferResponse response =new OfferResponse();
response.setMessage(AllConstant.ADDED_SUCCESSFULLY);
response.setOfferCategory(offerReturned.getOfferCategory());
response.setOfferId(offerReturned.getOfferId());
response.setOfferPercentage(offerReturned.getOfferPercentage());
response.setValidFrom(offer.getValidFrom());
response.setValidUpto(offer.getValidUpto());
response.setResult(true);
return new ResponseEntity<OfferResponse>(response, HttpStatus.OK);
}
@ApiOperation(value = "Get all offer details for a product", response = JSONArray.class, tags = "GetAllOfferDetails")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully Sending all offer details"),
@ApiResponse(code = 500, message = "Internal Server Error"),
})
@GetMapping(value = "/",produces = "application/json")
public ResponseEntity<String> getAllOffer(){
List<Offer> allOffer = offerService.getAllOffer();
Gson gson = new Gson();
String jsonOffers = gson.toJson(allOffer);
return new ResponseEntity<String>("{\"offers\":"+jsonOffers+"}",HttpStatus.OK);
}
@ApiOperation(value = "modify a offer details for a product", response = OfferResponse.class, tags = "UpdateOfferDetails")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully modified Offer details"),
@ApiResponse(code = 400, message = "Invalid Request"),
@ApiResponse(code = 500, message = "Internal Server Error"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
})
@PutMapping(value ="/",produces = "application/json",consumes = "application/json")
public ResponseEntity<OfferResponse> updateOfferDetails(@RequestBody Offer offer){
OfferResponse offerResponse = new OfferResponse();
ResponseEntity<OfferResponse> response = null;
if( offer != null && offer.getOfferId() > 0)
{
Offer offerReturned = offerService.getOffer(offer.getOfferId());
offerReturned.setOfferCategory( offer.getOfferCategory() != null ? offer.getOfferCategory() : offerReturned.getOfferCategory());
offerReturned.setValidFrom( offer.getValidFrom() != null ? offer.getValidFrom() : offerReturned.getValidFrom());
offerReturned.setValidUpto( offer.getValidUpto() != null ? offer.getValidUpto() : offerReturned.getValidUpto());
offerReturned.setOfferPercentage( offer.getOfferPercentage() != null ? offer.getOfferPercentage() : offerReturned.getOfferPercentage());
offerService.updateOffer(offerReturned);
offerResponse.setResult(true);
offerResponse.setOfferCategory(offerReturned.getOfferCategory());
offerResponse.setOfferId(offerReturned.getOfferId());
offerResponse.setOfferPercentage(offerReturned.getOfferPercentage());
offerResponse.setValidFrom(offerReturned.getValidFrom());
offerResponse.setValidUpto(offerReturned.getValidUpto());
offerResponse.setMessage(AllConstant.UPDATED_SUCCESSFULLY);
response = new ResponseEntity<OfferResponse>(offerResponse, HttpStatus.OK);
}else {
offerResponse.setMessage(AllConstant.INVALID_OFFER_ID);
offerResponse.setResult(false);
response = new ResponseEntity<OfferResponse>(offerResponse, HttpStatus.BAD_REQUEST);
}
return response;
}
<<<<<<< HEAD
@ApiOperation(value = "delete a offer details for a product", response = OfferResponse.class, tags = "DeleteOfferDetails")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully deleted Offer details"),
@ApiResponse(code = 400, message = "Invalid Request"),
@ApiResponse(code = 500, message = "Internal Server Error"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
})
@GetMapping(value ="/{offerId}",produces = "application/json")
public ResponseEntity<OfferResponse> deleteOffer(@PathVariable Long offerId){
OfferResponse offerResponse = new OfferResponse();
ResponseEntity<OfferResponse> response = null;
if( offerId != null && offerId>0)
{
offerService.deleteOffer(offerId);
offerResponse.setMessage(AllConstant.DELETED_SUCCESSFULLY);
offerResponse.setResult(false);
//response = new ResponseEntity<OfferResponse>(offerResponse, HttpStatus.DELETED_SUCCESSFULLY);
}
return response;
}
=======
>>>>>>> 93f671b5c5470e5eeb1a89c00a02fcfd9fd72fb9
}
|
package com.box.androidsdk.content.listeners;
import com.box.androidsdk.content.models.BoxDownload;
/**
* Listener that provides information on a download once the download starts.
*/
public interface DownloadStartListener {
/**
* Callback when download has started
* @param downloadInfo
*/
public void onStart(BoxDownload downloadInfo);
}
|
package com.ns.greg.library.base_architecture.module;
import android.content.SharedPreferences;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* @author Gregory
* @since 2017/8/4
*/
@Singleton public class SharedPreferenceManager {
private SharedPreferences sharedPreferences;
@Inject SharedPreferenceManager(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
}
/**
* Gets the String from {@link SharedPreferences}
* with specific key
*
* @param key specific key
* @param defaultValue default value
*/
public String getString(String key, String defaultValue) {
return sharedPreferences.getString(key, defaultValue);
}
/**
* Sets the String into {@link SharedPreferences}
*
* @param key specific key
* @param value stored value
*/
public void setString(String key, String value) {
sharedPreferences.edit().putString(key, value).apply();
}
/**
* Gets the boolean form {@link SharedPreferences}
* with specific key
*
* @param key specific key
* @param defaultValue default value
*/
public boolean getBoolean(String key, boolean defaultValue) {
return sharedPreferences.getBoolean(key, defaultValue);
}
/**
* Sets the boolean into {@link SharedPreferences}
*
* @param key specific key
* @param value stored value
*/
public void setBoolean(String key, boolean value) {
sharedPreferences.edit().putBoolean(key, value).apply();
}
/**
* Gets the Integer form {@link SharedPreferences}
* with specific key
*
* @param key specific key
* @param defaultValue default value
*/
public int getInt(String key, int defaultValue) {
return sharedPreferences.getInt(key, defaultValue);
}
/**
* Sets the Integer into {@link SharedPreferences}
*
* @param key specific key
* @param value stored value
*/
public void setInt(String key, int value) {
sharedPreferences.edit().putInt(key, value).apply();
}
/**
* Gets the Float from {@link SharedPreferences}
* with specific key
*
* @param key specific key
* @param defaultValue default value
*/
public float getFloat(String key, float defaultValue) {
return sharedPreferences.getFloat(key, defaultValue);
}
/**
* Sets the Float into {@link SharedPreferences}
*
* @param key specific key
* @param value stored value
*/
public void setFloat(String key, float value) {
sharedPreferences.edit().putFloat(key, value).apply();
}
/**
* Gets the Long from {@link SharedPreferences}
* with specific key
*
* @param key specific key
* @param defaultValue default value
*/
public long getLong(String key, long defaultValue) {
return sharedPreferences.getLong(key, defaultValue);
}
/**
* Sets the Long into {@link SharedPreferences}
*
* @param key specific key
* @param value stored value
*/
public void setLong(String key, long value) {
sharedPreferences.edit().putLong(key, value).apply();
}
/**
* Checks if {@link SharedPreferences} contains the specific key
*
* @param key specific key
*/
public boolean hasKey(String key) {
return sharedPreferences.contains(key);
}
/**
* Clears {@link SharedPreferences}
*/
public void clearPreferences() {
sharedPreferences.edit().clear().apply();
}
}
|
package com.gsonkeno.elasticsearch5_3;
/**
* Created by gaosong on 2017-04-30.
*/
public enum ClauseType {
MUST,
SHOULD,
MUST_NOT,
FILTER
}
|
package java_code;
import java_code.server.Server;
import javafx.application.Application;
import java_code.view.SeatDApplication;
import java.util.ArrayList;
import java.util.Arrays;
/**
* Application starts this way so that we can easily launch the server application with the same main, just add an if
* statement to check if the args has a arbitrary "server" tag.
*/
public class Main{
public static void main(String[] args){
if(new ArrayList<>(Arrays.asList(args)).contains("server")){
Server server = new Server();
server.start();
}else
Application.launch(SeatDApplication.class, args);
}
}
|
package com.revature.abstraction;
public class Cat extends Animals{
// thanks to abstraction, all # of legs and color properties are abstracted
private String breed;
private boolean hasFur;
@Override
public void makeSound() {
System.out.println("Meow");
}
public Cat() {
super();
this.hasFur = true;
}
// getters & setters
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
public boolean isHasFur() {
return hasFur;
}
public void setHasFur(boolean hasFur) {
this.hasFur = hasFur;
}
@Override
public String toString() {
return "Cat [breed=" + breed + ", hasFur=" + hasFur + "]";
}
}
|
package com.tencent.mm.ui.chatting;
import com.tencent.mm.R;
import com.tencent.mm.sdk.platformtools.al.a;
import com.tencent.mm.sdk.platformtools.as;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class p$9 implements a {
final /* synthetic */ p tJl;
p$9(p pVar) {
this.tJl = pVar;
}
public final boolean vD() {
long wu = p.a(this.tJl).wu();
x.d("MicroMsg.ChattingFooterEventImpl", "ms " + wu);
if (wu >= 50000 && wu <= 60000) {
if (!p.k(this.tJl)) {
bi.fO(p.e(this.tJl).tTq.getContext());
p.a(this.tJl, true);
}
int i = (int) ((60000 - wu) / 1000);
p.d(this.tJl).setRecordNormalWording(p.e(this.tJl).tTq.getMMResources().getQuantityString(R.j.chatting_rcd_time_limit, i, new Object[]{Integer.valueOf(i)}));
}
if (wu < 60000) {
return true;
}
x.v("MicroMsg.ChattingFooterEventImpl", "record stop on countdown");
p.l(this.tJl);
p.d(this.tJl).aMo();
as.I(p.e(this.tJl).tTq.getContext(), R.l.time_limit);
return false;
}
}
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package frc.robot.helpers;
/**
* Add your docs here.
*/
public class Helper {
public static double deadband(double value, double range){
return Math.abs(value) < range ? 0 : value;
}
}
|
package org.kernelab.basis.io;
import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* Filter files that has the same prefix.
*
* <pre>
* Example:
* "File.txt"
* "File.dat"
* "file.conf"
*
* filter by "File"
* returns
*
* "File.txt"
* "File.dat"
* </pre>
*
* @author Dilly King
*
*/
public class FilePrefixNamesFilter implements FilenameFilter
{
public static final String getFilenameBeforeSuffix(File file)
{
return getFilenameBeforeSuffix(file.getName());
}
public static final String getFilenameBeforeSuffix(String filename)
{
int index = filename.lastIndexOf('.');
if (index == -1) {
index = filename.length();
}
return filename.substring(0, index);
}
public static final Set<File> getFilesOfSamePrefixAround(File file)
{
Set<File> files = new LinkedHashSet<File>();
FilePrefixNamesFilter filter = new FilePrefixNamesFilter(
getFilenameBeforeSuffix(file));
File dir = file.getParentFile();
for (File f : dir.listFiles(filter)) {
files.add(f);
}
return files;
}
private Set<String> filePrefixNames;
public FilePrefixNamesFilter(String... names)
{
filePrefixNames = new HashSet<String>();
for (String name : names) {
filePrefixNames.add(name);
}
}
public boolean accept(File dir, String name)
{
return filePrefixNames.contains(getFilenameBeforeSuffix(name));
}
public Set<String> getFilePrefixNames()
{
return filePrefixNames;
}
}
|
package sendmessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import com.telstra.ApiClient;
import com.telstra.ApiException;
import com.telstra.Configuration;
import com.telstra.auth.*;
import com.telstra.messaging.*;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent;
import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent;
import org.json.*;
/**
* Handler for requests to Lambda function.
*/
public class App implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> {
public APIGatewayProxyResponseEvent handleRequest(final APIGatewayProxyRequestEvent input, final Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Body: " + input.getBody());
JSONObject obj = new JSONObject(input.getBody());
String phNumber = obj.getString("phNumber");
String message = obj.getString("message");
logger.log("Ph: " + phNumber);
logger.log("Message: " + message);
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://tapi.telstra.com/v2");
// Configure OAuth2 access token for authorization
OAuth auth = (OAuth) defaultClient.getAuthentication("auth");
AuthenticationApi authenticationApi = new AuthenticationApi(defaultClient);
String clientId = "";
String clientSecret = "";
String grantType = "client_credentials";
String scope = "NSMS";
try {
OAuthResponse oAuthResponse = authenticationApi.authToken(clientId, clientSecret, grantType, scope);
auth.setAccessToken(oAuthResponse.getAccessToken());
} catch (ApiException e) {
System.err.println("Exception when calling AuthenticationApi#authToken");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
// Send SMS
MessagingApi msgingApiInstance = new MessagingApi(defaultClient);
try {
SendSMSRequest sendSmsRequest = new SendSMSRequest();
sendSmsRequest.to(phNumber);
sendSmsRequest.body(message);
MessageSentResponseSms result = msgingApiInstance.sendSMS(sendSmsRequest);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling MessagingApi#sendSMS");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent()
.withHeaders(headers);
String output = "{ \"message\": \"" + message + " was sent\" }";
return response
.withStatusCode(200)
.withBody(output);
}
}
|
package com.cloudogu.smeagol.wiki.infrastructure;
import com.cloudogu.smeagol.wiki.domain.ContentFragment;
import com.cloudogu.smeagol.wiki.domain.Path;
import com.cloudogu.smeagol.wiki.domain.Score;
import com.cloudogu.smeagol.wiki.domain.SearchResult;
import net.bytebuddy.utility.RandomString;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import static com.cloudogu.smeagol.wiki.DomainTestData.WIKI_ID_42;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class LuceneSearchResultRepositoryTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Mock
private LuceneContext context;
@InjectMocks
private LuceneSearchResultRepository resultRepository;
private FSDirectory directory;
@Before
public void setUp() throws IOException {
File indexDirectory = temporaryFolder.newFolder();
directory = FSDirectory.open(indexDirectory.toPath());
Document doc = createSampleDocument();
addDocumentToIndex(doc);
when(context.createAnalyzer()).thenReturn(new StandardAnalyzer());
when(context.createReader(WIKI_ID_42)).then((Answer<IndexReader>) invocationOnMock -> DirectoryReader.open(directory));
}
private void addDocumentToIndex(Document document) throws IOException {
IndexWriterConfig config = new IndexWriterConfig(new StandardAnalyzer());
config.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
try (IndexWriter writer = new IndexWriter(directory, config)) {
writer.addDocument(document);
}
}
private Document createSampleDocument() {
String longGeneratedString = RandomString.make(60000);
longGeneratedString += "Hitchers guide to the Galaxy";
return createDocument("docs/Home", longGeneratedString, "don't panic");
}
private Document createDocument(String path, String content, String message) {
Document doc = new Document();
doc.add(new StringField(LuceneFields.PATH, path, Field.Store.YES));
doc.add(new TextField(LuceneFields.CONTENT, content, Field.Store.YES));
doc.add(new TextField(LuceneFields.MESSAGE, message, Field.Store.YES));
return doc;
}
@Test
public void testSearch() {
Iterable<SearchResult> results = resultRepository.search(WIKI_ID_42, "content:guide");
Iterator<SearchResult> iterator = results.iterator();
assertThat(iterator.hasNext()).isTrue();
SearchResult result = iterator.next();
assertThat(result.getPath()).isEqualTo(Path.valueOf("docs/Home"));
assertThat(result.getScore().getValue()).isGreaterThan(0f);
assertThat(result.getContentFragment().getValue()).containsIgnoringCase("guide");
assertThat(iterator.hasNext()).isFalse();
}
@Test
public void testSearchMultipleResults() throws IOException {
Document doc = createDocument("docs/Galaxy", "A Guide to the galaxy", "keep calm");
addDocumentToIndex(doc);
SearchResult resultHome = new SearchResult(WIKI_ID_42, Path.valueOf("docs/Home"), Score.valueOf(42), ContentFragment.valueOf("as"));
SearchResult resultGalaxy = new SearchResult(WIKI_ID_42, Path.valueOf("docs/Galaxy"), Score.valueOf(42), ContentFragment.valueOf("as"));
Iterable<SearchResult> results = resultRepository.search(WIKI_ID_42, "content:guide");
assertThat(results).containsExactlyInAnyOrder(resultHome, resultGalaxy);
}
@Test
public void testSearchNotFound() {
Iterable<SearchResult> results = resultRepository.search(WIKI_ID_42, "content:sorbot");
assertThat(results).isEmpty();
}
}
|
package com.noteshare.wechat.services.impl;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import com.noteshare.common.utils.constant.WechatConstants;
import com.noteshare.wechat.model.AccessToken;
import com.noteshare.wechat.services.WebchatApiService;
import com.noteshare.wechat.utils.MyX509TrustManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class WebchatApiServiceImpl implements WebchatApiService{
@Override
public AccessToken getAccessToken() {
AccessToken accessToken = null;
String url = WechatConstants.ACCESS_TOKEN_URL.replace("APPID", WechatConstants.APPID).replace("APPSECRET", WechatConstants.APPSECRET);
JSONObject json = httpRequest(url,"GET",null);
if(null != json){
accessToken = new AccessToken();
accessToken.setAccessToken(json.getString("access_token"));
accessToken.setExpiresIn(json.getInt("expires_in"));
}
//替换静态变量ACCESS_TOKEN的值
WechatConstants.ACCESS_TOKEN = accessToken.getAccessToken();
return accessToken;
}
@Override
public ArrayList<String> getWechatIpList() {
ArrayList<String> list = new ArrayList<String>();
String url = WechatConstants.WECHAT_SERVER_IP_LIST_URL.replace("ACCESS_TOKEN", WechatConstants.ACCESS_TOKEN);
JSONObject json = httpRequest(url,"GET",null);
if(null != json){
if(json.has("errcode")){
String errcode = json.getString("errcode");
if(null != errcode && WechatConstants.ACCESSTOKEN_OUTTIME.equals(errcode)){
//重新获取access_token的值
getAccessToken();
if(WechatConstants.GET_ACCESS_TOKEN_NUMBER < WechatConstants.MAX_GET_ACCESS_TOKEN_NUMBER){
//自加一
WechatConstants.GET_ACCESS_TOKEN_NUMBER++;
return getWechatIpList();
}else{
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return null;
}
}else{
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return null;
}
}
JSONArray jsonArr = json.getJSONArray("ip_list");
//初始化获取access_token的次数为0
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
//判断access_token是否超时"errcode":42001
@SuppressWarnings("unchecked")
Iterator<String> iter = jsonArr.iterator();
while(iter.hasNext()){
String value = iter.next();
list.add(value);
}
}
if(list.size() > 0){
return list;
}else{
return null;
}
}
@Override
public int createMenu(JSONObject json) {
String url = WechatConstants.MENU_URL.replace("ACCESS_TOKEN", WechatConstants.ACCESS_TOKEN);
JSONObject jsonObject = httpRequest(url, "POST", json.toString());
if(null != jsonObject){
if(jsonObject.has("errcode")){
String errcode = jsonObject.getString("errcode");
if(null != errcode && WechatConstants.ACCESSTOKEN_OUTTIME.equals(errcode)){
//重新获取access_token的值
getAccessToken();
if(WechatConstants.GET_ACCESS_TOKEN_NUMBER < WechatConstants.MAX_GET_ACCESS_TOKEN_NUMBER){
//自加一
WechatConstants.GET_ACCESS_TOKEN_NUMBER++;
return createMenu(json);
}else{
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return -1;
}
}else if(0 != jsonObject.getInt("errcode")){
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return jsonObject.getInt("errcode");
}else if(0 == jsonObject.getInt("errcode")){
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return 0;
}else{
return -1;
}
}else{
return -1;
}
}else{
return -1;
}
}
@Override
public JSONObject getMenus() {
String url = WechatConstants.GET_MENU_URL.replace("ACCESS_TOKEN", WechatConstants.ACCESS_TOKEN);
JSONObject jsonObject = httpRequest(url, "GET", null);
if(null != jsonObject){
if(jsonObject.has("errcode")){
String errcode = jsonObject.getString("errcode");
if(null != errcode && WechatConstants.ACCESSTOKEN_OUTTIME.equals(errcode)){
//重新获取access_token的值
getAccessToken();
if(WechatConstants.GET_ACCESS_TOKEN_NUMBER < WechatConstants.MAX_GET_ACCESS_TOKEN_NUMBER){
//自加一
WechatConstants.GET_ACCESS_TOKEN_NUMBER++;
return getMenus();
}else{
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return null;
}
}else if(0 != jsonObject.getInt("errcode")){
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return null;
}else if(0 == jsonObject.getInt("errcode")){
WechatConstants.GET_ACCESS_TOKEN_NUMBER = 0;
return jsonObject;
}else{
return null;
}
}else{
return null;
}
}else{
return null;
}
}
/**
* @Title : httpRequest
* @Description : 发起https请求并获取结果
* @param requestUrl : 请求地址
* @param requestMethod : 请求方式(GET、POST)
* @param data : 提交的数据
* @return : JSONObject 返回json对象
* @author : xingchen
* @date : 2016年6月20日 下午9:55:02
* @throws
*/
private JSONObject httpRequest(String requestUrl, String requestMethod, String data) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != data) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(data.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
}catch (Exception e) {
//TODO:日志信息
e.printStackTrace();
}
return jsonObject;
}
}
|
package org.zacharylavallee.algorithm.sorting;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.zacharylavallee.bool.BooleanUtils.greaterThan;
import static org.zacharylavallee.bool.BooleanUtils.lessThan;
class QuickSort implements Sortable {
private static <T> void swap(int index1, int index2, List<T> list) {
T temp = list.get(index1);
list.set(index1, list.get(index2));
list.set(index2, temp);
}
@Override
public <T extends Comparable<? super T>> List<T> sort(Collection<T> elements) {
if (elements.size() <= 1) {
return new ArrayList<>(elements);
}
List<T> elementList = new ArrayList<>(elements);
return sort(elementList, 0, elementList.size() - 1);
}
private <T extends Comparable<? super T>> List<T> sort(List<T> elements, int low, int high) {
T pivot = elements.get(low + (high - low) / 2);
int i = low, j = high;
while (i <= j) {
while (lessThan(elements.get(i), pivot)) {
i++;
}
while (greaterThan(elements.get(j), pivot)) {
j--;
}
if (i <= j) {
swap(i, j, elements);
i++;
j--;
}
}
if (low < j) {
elements = sort(elements, low, j);
}
if (i < high) {
elements = sort(elements, i, high);
}
return elements;
}
}
|
package edu.pdx.cs410J.hueb;
import edu.pdx.cs410J.ParserException;
import java.io.*;
import java.util.Collection;
public class Project2 {
public static final String USAGE_MESSAGE = "\nusage: java -jar target/apptbook-2021.0.0.jar [options] <args>\n\n" +
"args are (in this order):\n" + "owner \t\t The person who owns the appt book\n" +
"description \t A description of the appointment\n" + "begin \t\t When the appt begins (24-hour time)\n" +
"end \t\t When the appt ends (24-hour time)\n" + "\noptions are (options may appear in any order):\n" +
"-textFile file \t Where to read/write the appointment book\n" +
"-print \t\t Prints a description of the new appointment\n" + "-README \t Prints a README for this project and exits\n"+
"\n* Date and time should be in the format: mm/dd/yyyy hh:mm\n" +
"* Owner and Description should be wrapped in quotes\n" + "* File should be filename with valid extension\n ";
public static void main(String[] args) {
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//no command line args to pass first, premade test
if (args.length == 0) {
printErrorMessageAndExitWithUsage("\nMissing Command Line Arguments\n");
}
//check for readme option
for (String arg : args) {
if (arg.equalsIgnoreCase("-README")) {
readMeCheck(arg);
}
}
//if no -README option and args.length is appropriate for possibilities
if (args.length >= 6 && args.length <= 9) {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// ARGS LEN 6 ///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///only valid option is the 6min args
//if 6 args validate format of end and begin time, then add
if (args.length == 6) {
if (!args[0].equalsIgnoreCase("-print")) {
boolean validDateTime6 = (validDate(args[2]) && validTime(args[3]) &&
validDate(args[4]) && validTime(args[5]));
String beginTime = args[2] + " " + args[3];
String endTime = args[4] + " " + args[5];
if (validDateTime6) {
Appointment apt = new Appointment(args[1], beginTime, endTime);
AppointmentBook aptBook = new AppointmentBook(args[0]);
aptBook.addAppointment(apt);
System.exit(0);
} else {
//if (validDateTime6)
printErrorMessageAndExitWithUsage("6\nInvalid Arguments - Please Check the Formatting of Your Dates and Times\n");
}
} else {
printErrorMessageAndExitWithUsage("6\nInvalid Arguments - Possibly May Have Wrong Number/Combination of Arguments and Options\n");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// ARGS LEN 7 ///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///only valid option is -print + 6min args
else if (args.length == 7) {
//if 7 args see if first one is -print.caseinsensitive
//if so set a flag to print description
//then validate last and if all good
//add apt and print
if (args[0].equalsIgnoreCase("-print")) {
boolean validDateTime7 = (validDate(args[3]) && validTime(args[4]) &&
validDate(args[5]) && validTime(args[6]));
String beginTime = args[3] + " " + args[4];
String endTime = args[5] + " " + args[6];
if (validDateTime7) {
Appointment apt = new Appointment(args[2], beginTime, endTime);
AppointmentBook aptBook = new AppointmentBook(args[1]);
aptBook.addAppointment(apt);
System.out.println("\n"+apt.toString()+"\n");
System.exit(0);
} else {
//if (validDateTime7)
printErrorMessageAndExitWithUsage("7\nInvalid Arguments - Please Check the Formatting of Your Dates and Times\n");
}
} else {
printErrorMessageAndExitWithUsage("7\nInvalid Arguments - Possibly May Have Wrong Number/Combination of Arguments and Options\n");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// ARGS LEN 8 ///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///only valid option is -textfile file + 6min args
else if (args.length == 8) {
if (args[0].equalsIgnoreCase("-textfile")) {
boolean validDateTime8 = (validDate(args[4]) && validTime(args[5]) &&
validDate(args[6]) && validTime(args[7]));
String beginTime = args[4] + " " + args[5];
String endTime = args[6] + " " + args[7];
if (validDateTime8) {
Appointment apt = new Appointment(args[3], beginTime, endTime);
AppointmentBook aptBook = new AppointmentBook(args[2]);
aptBook.addAppointment(apt);
String file = args[1];
TextParser tp = new TextParser(file);
//check if file exists
File f = new File(file);
//if file exists make sure owner matches
if (f.exists() && !f.isDirectory()) {
// System.out.println("\nFile " + file + " WAS FOUND\n");
try {
//System.out.println("calling parse");
AppointmentBook ab = tp.parse();
//make sure owner names match
if (ab.getOwnerName().equalsIgnoreCase(aptBook.getOwnerName())) {
//dump aptBook to file
try {
TextDumper td = new TextDumper(file);
td.dump(aptBook);
} catch (IOException e) {
printErrorMessageAndExitWithOutUsage("8\nDUMP Failed\n");
}
//if owners do NOT match exit with error message
} else {
System.err.println("\nCannot Add New Appointment to File. \nOwner Names Do NOT Match\n"+
"Current Appointment Book Owner: " + ab.getOwnerName() + "\nOwner Entered: " + aptBook.getOwnerName() + "\n");
}
Collection<Appointment> appointments = ab.getAppointments();
} catch (ParserException e) {
printErrorMessageAndExitWithOutUsage("8\nParse Failed\n");
}
//if file does not exist, create file and dump to it
}
//if file doesnt exist or is directory
else {
System.out.println("\nFILE " + file + " Not Found\nAttempting to create file: " + file +"\n");
try {
//dump aptBook to file
TextDumper td = new TextDumper(file);
td.dump(aptBook);
System.exit(0);
} catch (IOException e) {
printErrorMessageAndExitWithOutUsage("8\nDUMP Failed\n");
}
}
System.exit(0);
} else {
//if (validDateTime8)
printErrorMessageAndExitWithUsage("8\nInvalid Arguments - Please Check the Formatting of Your Dates and Times\n");
}
} else {
printErrorMessageAndExitWithUsage("8\nInvalid Arguments - Possibly May Have Wrong Combination of Arguments and Options\n");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// ARGS LEN 9 ///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////only valid option is: -textfile file -print + 6min args || -print -textfile file + 6min args
else if (args.length == 9) {
if ((args[0].equalsIgnoreCase("-textfile") || args[1].equalsIgnoreCase("-textfile"))
&& (args[0].equalsIgnoreCase("-print") || args[2].equalsIgnoreCase("-print"))) {
boolean validDateTime9 = (validDate(args[5]) && validTime(args[6]) &&
validDate(args[7]) && validTime(args[8]));
String beginTime = args[5] + " " + args[6];
String endTime = args[7] + " " + args[8];
if (validDateTime9) {
Appointment apt = new Appointment(args[4], beginTime, endTime);
AppointmentBook aptBook = new AppointmentBook(args[3]);
aptBook.addAppointment(apt);
//find which arg index -textfile string is at
//in order to find position of "file" name string'
int fileFlag = 0;
if (args[0].equalsIgnoreCase("-textfile")) {
fileFlag = 1;
} else {
fileFlag = 2;
}
String file = args[fileFlag];
TextParser tp = new TextParser(file);
//check if file exists
File f = new File(file);
//if file exists make sure owner matches
if (f.exists() && !f.isDirectory()) {
try {
//System.out.println("calling parse");
AppointmentBook ab = tp.parse();
//make sure owner names match
if (ab.getOwnerName().equalsIgnoreCase(aptBook.getOwnerName())) {
//dump aptBook to file
try {
TextDumper td = new TextDumper(file);
td.dump(aptBook);
System.out.println("\n"+apt.toString()+"\n");
System.exit(0);
} catch (IOException e) {
printErrorMessageAndExitWithOutUsage("\n9) DUMP Failed\n");
}
//if owners dont match exit with error message
} else {
System.err.println("\nCannot Add New Appointment to File. \nOwner Names Do NOT Match\n"+
"Current Appointment Book Owner: " + ab.getOwnerName() + "\nOwner Entered: " + aptBook.getOwnerName() + "\n");
}
Collection<Appointment> appointments = ab.getAppointments();
} catch (ParserException e) {
printErrorMessageAndExitWithOutUsage("\n9)PARSE Failed\n");
}
//if file does NOT exist, create file and dump to it
} else {
//CREATE FILE
System.out.println("\nFILE " + file + " Not Found\nAttempting to create file: " + file + "\n");
//dump aptBook to file
try {
TextDumper td = new TextDumper(file);
td.dump(aptBook);
System.out.println("\n"+apt.toString()+"\n");
System.exit(0);
} catch (IOException e) {
printErrorMessageAndExitWithOutUsage("\n9) DUMP Failed\n");
}
}
System.exit(0);
} else {
//if (validDateTime9)
printErrorMessageAndExitWithUsage("\n9) Invalid Arguments - Please Check the Formatting of Your Dates and Times\n");
}
} else {
printErrorMessageAndExitWithUsage("\n9) Invalid Arguments - Possibly Missing or Malformed Options: -print and/or -textFile file\n");
}
} else {
printErrorMessageAndExitWithUsage("\n9) Invalid Arguments - Possibly May Have Wrong Combination of Arguments and Options\n");
}
//if (args.length >= 6 && args.length <= 9)
} else {
//if (args.length >= 6 && args.length <= 9)
printErrorMessageAndExitWithUsage("\n9) Invalid Arguments - Possibly Too Many or Too Few Arguments/Options Entered\n");
}
System.exit(0);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////// HELPERS ///////////////////////////////////
private static void readMeCheck(String arg) {
try {
readMe();
} catch (IOException e) {
printErrorMessageAndExitWithOutUsage("Problem With README.txt File");
} catch (NullPointerException n) {
printErrorMessageAndExitWithOutUsage("README.txt File Not Found");
}
}
private static void readMe() throws IOException {
InputStream readme = edu.pdx.cs410J.hueb.Project2.class.getResourceAsStream("README.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(readme));
String line = reader.readLine();
while((line=reader.readLine()) != null){
System.out.println(line);
}
// System.out.println(line);
System.exit(0);
}
protected static void printErrorMessageAndExitWithUsage(String message) {
System.err.println(message);
System.err.println(USAGE_MESSAGE);
System.exit(1);
}
private static void printErrorMessageAndExitWithOutUsage(String message) {
System.err.println(message);
System.exit(1);
}
///////////////////// MOVE TO STUDENT CLASS FOR PROJ 2 //////////////////////
// mm/dd/yy
private static boolean validDate(String arg) {
boolean match = arg.matches("(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/(\\d{4})");
// System.out.println("DATE: " + arg + " " + match);
return match;
}
// hh:mm
private static boolean validTime(String arg) {
boolean match = arg.matches("(0?[0-9]|1[0-9]|2[0-3]):(0?[0-9]|[0-5][0-9])");
// System.out.println("TIME: " + arg + " " + match);
return match;
}
}
|
package com.wang.java8;
/*
* 首先,之前的接口是个双刃剑,好处是面向抽象而不是面向具体编程,缺陷是,当需要修改接口时候,
* 需要修改全部实现该接口的类,目前的java 8之前的集合框架没有foreach方法,通常能想到的
* 解决办法是在JDK里给相关的接口添加新的方法及实现。然而,对于已经发布的
* 版本,是没法在给接口添加新方法的同时不影响已有的实现。所以引进的默认方法。
* 他们的目的是为了解决接口的修改与现有的实现不兼容的问题。
*
* Java 8 的另一个特性是接口可以声明(并且可以提供实现)静态方法。
*/
public class DefaultFunction {
public static void main(String[] args){
InterA obj1 = new ClsC();
obj1.fun1();
}
}
interface InterA{
default void fun1(){
System.out.println("接口A的默认方法");
}
static void fun3(){
System.out.println("接口A的静态方法");
}
}
interface InterB{
default void fun2(){
System.out.println("接口B的默认方法");
}
}
class ClsC implements InterA,InterB{
public void fun1(){
System.out.println("类C的方法");
InterA.super.fun1();
InterB.super.fun2();
InterA.fun3();
}
}
|
package com.awsec2.web.action.shared;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.awsec2.domain.User;
import com.awsec2.service.IUserService;
import com.awsec2.util.CookieUtil;
import com.awsec2.web.action.BaseAction;
public class LoginAction extends BaseAction{
private static final long serialVersionUID = -1182291046531750706L;
@Autowired
private IUserService userService = null;
private User user = null;
//private String message;
private HttpSession session = null;
private HttpServletResponse res = null;
private HttpServletRequest req = null;
/**
* @return the user
*/
public User getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
/*private User loadUser(){
System.out.println("@@@@@######user.getEmail_id():"+user.getEmail_id());
User currUser = (User)userService.loadUserByEmailId(user.getEmail_id());
System.out.println("@@@@@######currUser:"+currUser);
if (currUser == null) {
message = "error.username.notexiste";
}
if ((currUser != null) && !currUser.getPassword().equals(user.getPassword())) {
message = "error.password.mismatch";
}
return currUser;
}*/
private boolean loginValid(){
if(user != null){
System.out.println("****@user.username*******:" + user.getUsername());
User currUser = (User)userService.getUserByUsername(user.getUsername());
if(currUser == null){
System.out.println("****@login message*******: username is not exist" );
return false;
}
if(currUser != null && !currUser.getPassword().equals(user.getPassword())){
System.out.println("****@login message*******: password is error");
return false;
}
System.out.println("In action isSuper : " + currUser.isSupers());
if(req == null){
req = ServletActionContext.getRequest();
session = req.getSession();
session.setAttribute("username", currUser.getUsername());
session.setAttribute("userId", currUser.getId());
session.setAttribute("isSuper", currUser.isSupers());
}
if(res == null){
res = ServletActionContext.getResponse();
new CookieUtil().addCookies(res, "username", currUser.getUsername(), 3600);
new CookieUtil().addCookies(res, "isSuper", currUser.isSupers() == true ? "true" : "false" , 3600);
}else{
new CookieUtil().addCookies(res, "username", currUser.getUsername(), 3600);
new CookieUtil().addCookies(res, "isSuper", currUser.isSupers() == true ? "true" : "false" , 3600);
}
return true;
}
return false;
}
public String login() throws Exception{
/*this.loadUser();
if(message == null || message.isEmpty()){
return "success";//return null;
}else{
return "failure";
}*/
if(loginValid()){
System.out.println("****@login message*******: login successful");
if(req == null){
req = ServletActionContext.getRequest();
session = req.getSession();
System.out.println("Session Username : " + session.getAttribute("username"));
System.out.println("Session UserId : " + session.getAttribute("userId"));
System.out.println("Session IsSuper : " + session.getAttribute("isSuper"));
}else{
session = req.getSession();
System.out.println("Session Username : " + session.getAttribute("username"));
System.out.println("Session UserId : " + session.getAttribute("userId"));
System.out.println("Session IsSuper : " + session.getAttribute("isSuper"));
}
return "success";
}else{
return "failure";
}
//return "success";
}
public String logout(){
if(res == null){
res = ServletActionContext.getResponse();
}
new CookieUtil().delCookies(res, "username");
new CookieUtil().delCookies(res, "isSuper");
return "success";
}
public String home(){
return "success";
}
public String index(){
return "success";
}
public String testing() throws Exception{
return "success";
}
}
|
package util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import mobileIntegration.FireBaseComunication;
import models.Registro;
public class FireBaseStart {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Map<String, Registro> registros = new HashMap<>();
Registro registro = new Registro();
registro.setRegistroId(87578);
registro.setEscala(955);
registro.setObs("Massa hehe EAE");
registros.put("rere", registro);
FireBaseComunication baseComunication = FireBaseComunication.getInstance();
baseComunication.save(registros);
}
}
|
package example.nz.org.take.compiler.userv.spec;
import nz.org.take.rt.*;
/**
* Interface generated by the take compiler.
* @version Sun Oct 21 23:25:20 NZDT 2007
*/
@SuppressWarnings("unchecked")
public interface UservRules {
/**
* Method generated for query /potentialTheftRating[in,out]
* @param car input parameter generated from slot 0
* @return an iterator for instances of PotentialTheftRating
*/
public ResultSet<PotentialTheftRating> getPotenialTheftRating(
final example.nz.org.take.compiler.userv.domainmodel.Car car);
/**
* Method generated for query /potentialOccupantInjuryRating[in,out]
* @param car input parameter generated from slot 0
* @return an iterator for instances of PotentialOccupantInjuryRating
*/
public ResultSet<PotentialOccupantInjuryRating> getPotentialOccupantInjuryRating(
final example.nz.org.take.compiler.userv.domainmodel.Car car);
/**
* Method generated for query /autoEligibility[in,out]
* @param car input parameter generated from slot 0
* @return an iterator for instances of AutoEligibility
*/
public ResultSet<AutoEligibility> getAutoEligibility(
final example.nz.org.take.compiler.userv.domainmodel.Car car);
/**
* Method generated for query /driverCategory[in,out]
* @param driver input parameter generated from slot 0
* @return an iterator for instances of DriverCategory
*/
public ResultSet<DriverCategory> getDriverCategory(
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /isEligible[in]
* @param driver input parameter generated from slot 0
* @return an iterator for instances of DriverEligibility
*/
public ResultSet<DriverEligibility> getDriverEligibility(
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /isHighRiskDriver[in]
* @param driver input parameter generated from slot 0
* @return an iterator for instances of HighRiskDriver
*/
public ResultSet<HighRiskDriver> isHighRiskDriver(
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /hasTrainingCertification[in]
* @param driver input parameter generated from slot 0
* @return an iterator for instances of TrainedDriver
*/
public ResultSet<TrainedDriver> hasTrainingCertification(
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /policyEligibilityScore[in,in,out]
* @param car input parameter generated from slot 0
* @param driver input parameter generated from slot 1
* @return an iterator for instances of PolicyEligibilityScore
*/
public ResultSet<PolicyEligibilityScore> getPolicyEligibilityScore(
final example.nz.org.take.compiler.userv.domainmodel.Car car,
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /insuranceEligibility[in,in,out]
* @param car input parameter generated from slot 0
* @param driver input parameter generated from slot 1
* @return an iterator for instances of InsuranceEligibility
*/
public ResultSet<InsuranceEligibility> getPolicyEligibility(
final example.nz.org.take.compiler.userv.domainmodel.Car car,
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /isLongTermClient[in]
* @param driver input parameter generated from slot 0
* @return an iterator for instances of LongTermClient
*/
public ResultSet<LongTermClient> isLongTermClient(
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /basePremium[in,out]
* @param car input parameter generated from slot 0
* @return an iterator for instances of BasePremium
*/
public ResultSet<BasePremium> getBasePremium(
final example.nz.org.take.compiler.userv.domainmodel.Car car);
/**
* Method generated for query /additionalPremium[in,in,out]
* @param policy input parameter generated from slot 0
* @param car input parameter generated from slot 1
* @return an iterator for instances of AdditionalPremium
*/
public ResultSet<AdditionalPremium> getAdditionalPremium(
final example.nz.org.take.compiler.userv.domainmodel.Policy policy,
final example.nz.org.take.compiler.userv.domainmodel.Car car);
/**
* Method generated for query /additionalDriverPremium[in,out]
* @param driver input parameter generated from slot 0
* @return an iterator for instances of AdditionalDriverPremium
*/
public ResultSet<AdditionalDriverPremium> getAdditionalDriverPremium(
final example.nz.org.take.compiler.userv.domainmodel.Driver driver);
/**
* Method generated for query /premiumDiscount[in,out]
* @param car input parameter generated from slot 0
* @return an iterator for instances of PremiumDiscount
*/
public ResultSet<PremiumDiscount> getPremiumDiscount(
final example.nz.org.take.compiler.userv.domainmodel.Car car);
/**
* Method that can be used to query annotations at runtime.
* @param id the id of the rule (or other knowledge element)
* @return a map of annotations (string-string mappings)
* code generated using velocity template LocalAnnotationMethod.vm
*/
public java.util.Map<String, String> getAnnotations(String id);
/**
* Method that can be used to query global annotations at runtime.
* Global annotations are attached to the knowledge base, not to
* a particular element (rule,..).
* @return a map of annotations (string-string mappings)
* code generated using velocity template GlobalAnnotationMethod.vm
*/
public java.util.Map<String, String> getAnnotations();
}
|
package com.toggleable.morgan.jeremyslist.models;
import java.util.ArrayList;
public class List {
private String name;
private ArrayList<Restaurant> list;
public String getListName() {
return name;
}
public void setListName(String name) {
this.name = name;
}
public ArrayList<Restaurant> getList() {
return list;
}
public void setList(ArrayList<Restaurant> list) {
this.list = list;
}
public void saveList() {
}
public void deleteList() {
}
}
|
/*
* Created on Sep 11, 2006
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.ibm.ive.tools.japt.removal;
import com.ibm.ive.tools.commandLine.Option;
import com.ibm.ive.tools.japt.ExtensionException;
import com.ibm.ive.tools.japt.FormattedString;
import com.ibm.ive.tools.japt.JaptMessage;
import com.ibm.ive.tools.japt.JaptRepository;
import com.ibm.ive.tools.japt.Logger;
import com.ibm.ive.tools.japt.MemberSelector;
import com.ibm.ive.tools.japt.Specifier;
import com.ibm.ive.tools.japt.JaptMessage.InfoMessage;
import com.ibm.ive.tools.japt.MemberActor.MemberCollectorActor;
import com.ibm.ive.tools.japt.commandLine.CommandLineExtension;
import com.ibm.ive.tools.japt.commandLine.options.SpecifierOption;
import com.ibm.jikesbt.BT_Class;
import com.ibm.jikesbt.BT_ClassVector;
import com.ibm.jikesbt.BT_Field;
import com.ibm.jikesbt.BT_FieldVector;
import com.ibm.jikesbt.BT_HashedFieldVector;
import com.ibm.jikesbt.BT_HashedMethodVector;
import com.ibm.jikesbt.BT_Method;
import com.ibm.jikesbt.BT_MethodVector;
public class RemovalExtension implements CommandLineExtension {
final public SpecifierOption clinits = new SpecifierOption("removeStaticInits", "remove static init(s) from specified class(es)");
final public SpecifierOption privates = new SpecifierOption("removePrivateMembers", "remove private method(s) and field(s) from specified class(es)");
final public SpecifierOption privatePackaged = new SpecifierOption("removePackageMembers", "remove private/package-access method(s) and field(s) from specified class(es)");
final public SpecifierOption privateClasses = new SpecifierOption("removePackageClasses", "remove specified package-access class(es)");
final public SpecifierOption anyClasses = new SpecifierOption("removeClasses", "remove specified class(es)");
//final public SpecifierOption innerClasses = new SpecifierOption("removeInnerClasses", "remove specified class(es)");
final public SpecifierOption methodBodies = new SpecifierOption("removeMethodBodies", "remove body(ies) from specified method(s)");
final public SpecifierOption classMethodBodies = new SpecifierOption("removeMethBodsInClass", "remove body(ies) from method(s) in specified class(es)");
final JaptMessage clinitMessage = new InfoMessage(this, new FormattedString("removed static initializer from class {0}"));
final JaptMessage removedBodyMessage = new InfoMessage(this, new FormattedString("removed body from method {0}"));
final JaptMessage removedMessage = new InfoMessage(this, new FormattedString("removed {0}"));
public RemovalExtension() {}
public Option[] getOptions() {
return new Option[] {clinits, methodBodies, classMethodBodies, privates, privatePackaged, privateClasses, anyClasses};
}
public void execute(JaptRepository repository, Logger logger)
throws ExtensionException {
Specifier specs[];
BT_ClassVector classes;
specs = anyClasses.getSpecifiers();
classes = repository.findClasses(specs, true);
for(int i=0; i<classes.size(); i++) {
BT_Class clazz = classes.elementAt(i);
removedMessage.log(logger, clazz.useName());
clazz.remove();
}
// specs = innerClasses.getSpecifiers();
// classes = repository.findClasses(specs, true);
// for(int i=0; i<classes.size(); i++) {
// BT_Class clazz = classes.elementAt(i);
// if(clazz.isInnerClass()) {
// removedMessage.log(logger, clazz.useName());
// clazz.remove();
// }
// }
specs = privateClasses.getSpecifiers();
classes = repository.findClasses(specs, true);
for(int i=0; i<classes.size(); i++) {
BT_Class clazz = classes.elementAt(i);
if(!clazz.isPublic()) {
removedMessage.log(logger, clazz.useName());
clazz.remove();
}
}
if(privates.appears() || privatePackaged.appears()) {
BT_MethodVector methods = new BT_HashedMethodVector();
BT_FieldVector fields = new BT_HashedFieldVector();
MemberCollectorActor actor = new MemberCollectorActor(methods, fields);
if(privatePackaged.appears()) {
specs = privatePackaged.getSpecifiers();
repository.findClasses(specs, actor, MemberSelector.privatePackageResolvableSelector, true);
}
if(privates.appears()) {
specs = privates.getSpecifiers();
repository.findClasses(specs, actor, MemberSelector.privateResolvableSelector, true);
}
for(int i=0; i<methods.size(); i++) {
BT_Method method = methods.elementAt(i);
removedMessage.log(logger, method.useName());
method.remove();
}
for(int i=0; i<fields.size(); i++) {
BT_Field field = fields.elementAt(i);
removedMessage.log(logger, field.useName());
field.remove();
}
}
specs = clinits.getSpecifiers();
classes = repository.findClasses(specs, true);
for(int i=0; i<classes.size(); i++) {
BT_Class clazz = classes.elementAt(i);
BT_MethodVector methods = clazz.methods;
for(int j=0; j<methods.size(); j++) {
BT_Method method = methods.elementAt(j);
if(method.isStaticInitializer()) {
clinitMessage.log(logger, clazz);
method.remove();
}
}
}
specs = classMethodBodies.getSpecifiers();
BT_MethodVector methods = new BT_HashedMethodVector();
MemberCollectorActor actor = new MemberCollectorActor(methods, null);
repository.findClasses(specs, actor, MemberSelector.allNonResolvableMethodSelector, true);
specs = methodBodies.getSpecifiers();
repository.findMethods(specs, actor);
for(int i=0; i<methods.size(); i++) {
BT_Method method = methods.elementAt(i);
if(!method.isAbstract()
&& !method.isNative()
&& !method.isStub()
&& method.getCode() != null
&& repository.isInternalClass(method.getDeclaringClass())) {
removedBodyMessage.log(logger, method.useName());
method.makeCodeSimplyReturn();
}
}
}
public String getName() {
return "removal";
}
}
|
package com.controller;
import java.util.List;
import java.util.Scanner;
import com.model.Account;
public class Main {
public static void main(String[] args) {
LoginController lic = new LoginController();
lic.showInitialView();
lic.chooseAccountToLoginTo();
LoginSessionController lsc = new LoginSessionController(lic.getLoggedIntoAccount(), lic.getAccounts());
while(lsc.getIsLoggedIn()){
lsc.displayOptions();
lsc.getMenuInput();
}
}
}
|
package hdfs.daemon;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import config.ClusterConfig;
import hdfs.ActivityI;
import hdfs.CommunicationStream;
import formats.FormatSelectorI;
public class DaemonHDFS extends Thread {
static HashMap<String, List<FragmentFile>> register;
static FormatSelectorI selector;
private int id;
private CommunicationStream emitterStream;
public static class FragmentFile implements Serializable {
private int number;
private String fileName;
public FragmentFile(int number, String fileName) {
this.number = number;
this.fileName = fileName;
}
public int getNumber() {
return this.number;
}
public String getFileName() {
return this.fileName;
}
}
public DaemonHDFS(Socket emitter, int id) {
super();
this.emitterStream = new CommunicationStream(emitter);
this.id = id;
}
public void run() {
try {
// Réception de la commande
int command = this.emitterStream.receiveDataInt();
// Réception du nom du file
String fileName = new String(this.emitterStream.receiveData()) + "_" + this.id;
ActivityI activity = ClusterConfig.getDaemonActivity(this.emitterStream, this.id);
activity.start(command, fileName);
// Déconnexion
this.emitterStream.close();
} catch (Exception e) {e.printStackTrace();}
}
public static void main(String[] args) {
try {
if (args.length == 1) {
int id = Integer.parseInt(args[0]);
// Création de la collection contenant les numéros des fragments par fichier
File file = new File("register_" + id + ".ser");
if (file.exists()) {
try {
ObjectInputStream objectIS = new ObjectInputStream(new FileInputStream(file));
register = (HashMap<String, List<FragmentFile>>)objectIS.readObject();
objectIS.close();
} catch(IOException e) {
e.printStackTrace();
return;
}
} else {
register = new HashMap<>();
}
// Objet permettant de récupérer le format adapté au fichier
selector = ClusterConfig.selector;
ServerSocket client = new ServerSocket(ClusterConfig.numPortHDFS[id]);
while (true) {
DaemonHDFS daemon = new DaemonHDFS(client.accept(), id);
daemon.start();
}
} else {
System.out.println("Usage : java hdfs.daemon.DaemonHDFS <id>");
}
} catch (Exception e) {e.printStackTrace();}
}
}
|
/**
*
*/
package com.gojek.parkinglotmgmtservices.tests;
import static org.junit.Assert.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.junit.Test;
import com.gojek.parkinglotmgmtservices.pojos.ParkingData;
import com.gojek.parkinglotmgmtservices.servicesimpl.ParkingDataProviderImpl;
/**
* @author ajitgadad
*
*/
public class ParkingDataProviderTest {
@Test
public void testShowSlotNosByColour() {
// key should not be dependent on lower or upper case
ParkingDataProviderImpl parkingDataProviderImpl = new ParkingDataProviderImpl();
ParkingData parkingData = ParkingData.getInstance();
Map<String, HashSet<Integer>> colour_reg_no_map = new HashMap<>();
HashSet<Integer> slotsSet = new HashSet<Integer>();
slotsSet.add(1);
colour_reg_no_map.put("White", slotsSet);
parkingData.setColour_slots_map(colour_reg_no_map);
String colour = "White";
parkingDataProviderImpl.showSlotNosByColour(colour);
assertNotNull(colour_reg_no_map.get(colour));
}
@Test
public void testShowSlotNosByRegNo() {
// key should not be dependent on lower or upper case
ParkingDataProviderImpl parkingDataProviderImpl = new ParkingDataProviderImpl();
ParkingData parkingData = ParkingData.getInstance();
Map<String, HashSet<Integer>> reg_no_slots_map = new HashMap<>();
HashSet<Integer> slotsSet1 = new HashSet<Integer>();
slotsSet1.add(1);
HashSet<Integer> slotsSet2= new HashSet<Integer>();
slotsSet2.add(3);
slotsSet2.add(4);
reg_no_slots_map.put("KA441P", slotsSet1);
reg_no_slots_map.put("KA1234L", slotsSet2);
parkingData.setReg_no_slots_map(reg_no_slots_map);
String reg_no = "KA1234L";
parkingDataProviderImpl.showSlotNosByRegNo(reg_no );
assertNotNull(reg_no_slots_map.get(reg_no));
assertEquals(slotsSet2, reg_no_slots_map.get(reg_no));
}
@Test
public void testShowRegNosByColour(){
ParkingDataProviderImpl parkingDataProviderImpl = new ParkingDataProviderImpl();
ParkingData parkingData = ParkingData.getInstance();
Map<String, HashSet<String>> colour_reg_no_map = new HashMap<>();
HashSet<String> registrationSet = new HashSet<>();
registrationSet.add("KA441P");
registrationSet.add("KA1234L");
colour_reg_no_map.put("Red", registrationSet);
parkingData.setColour_reg_no_map(colour_reg_no_map);
String colour ="Red";
parkingDataProviderImpl.showRegNosByColour(colour );
assertNotNull(colour_reg_no_map.get(colour));
assertEquals(registrationSet, colour_reg_no_map.get(colour));
}
}
|
package dosultimonumero;
import javax.swing.JOptionPane;
/**
*
* @author cromerofajar
*/
public class Operaciones {
int numero,contador,finalNumero;
public void comprobar(){
numero=Integer.parseInt(JOptionPane.showInputDialog(null,"Introduzca un numero"));
while(numero!=0){
finalNumero=numero%10;
if(finalNumero==2){
contador++;
}
numero=Integer.parseInt(JOptionPane.showInputDialog(null,"Introduzca un numero"));
}
JOptionPane.showMessageDialog(null,"As introducido un total de "+contador+" numeros rematados en 2");
}
}
|
package com.smxknife.springboot.v2.jpa;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author smxknife
* 2019-02-21
*/
@EnableTransactionManagement
@SpringBootApplication
public class AppBoot {
public static void main(String[] args) {
SpringApplication.run(AppBoot.class, args);
}
}
|
package selPack;
import java.awt.Window;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Action {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Standalone jar\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.flipkart.com");
driver.findElement(By.xpath("//button[@class='_2AkmmA _29YdH8']")).click();
WebElement Men = driver.findElement(By.xpath("//span[contains(text(),'Men')]"));
Actions cursor= new Actions (driver);
cursor.moveToElement(Men).build().perform();
Thread.sleep(2000);
WebElement TShirts = driver.findElement(By.xpath("//*[text()='T-Shirts']//ancestor::a[1]"));
//cursor.moveToElement(Men).moveToElement(TShirts).click().build().perform();
// driver.findElement(By.xpath("//*[text()='T-Shirts']//ancestor::a[1]")).click();
cursor.moveToElement(TShirts).click().build().perform();
System.out.println("Tshirt clicked after");
}
}
|
package com.gmail.ivanytskyy.vitaliy.repository;
import java.util.List;
import com.gmail.ivanytskyy.vitaliy.model.Student;
/*
* Repository interface for Student domain objects
* @author Vitaliy Ivanytskyy
*/
public interface StudentRepository {
Student create(Student student);
Student findById(long id);
List<Student> findByGroupId(long id);
List<Student> findByName(String name);
List<Student> findAll();
void deleteById(long id);
}
|
package behavioralPatterns.observerPattern;
/**
* @Author:Jack
* @Date: 2021/9/13 - 19:39
* @Description: ovserverPattern
* @Version: 1.0
*/
public class Lisi implements Observer{
@Override
public void update(String context) {
System.out.println("observing");
System.out.println(context);
}
}
|
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import java.io.IOException;
public class LoginPageController
{
@FXML
TextField username;
@FXML
Button loginButton;
@FXML
ComboBox userComboBox;
@FXML
public void loginButtonHandler(MouseEvent mouseEvent) throws IOException
{
if (userComboBox.getSelectionModel().getSelectedItem().toString().equals("Customer"))
{
for(Customer customer : Main.library.getCustomers())
{
if (customer.getUsername().equals(username.getText()))
{
Main.signedIn = customer;
Parent root = FXMLLoader.load(getClass().getResource("customerPage.fxml"));
Main.window.setTitle("Tawe Lib");
Main.window.setScene(new Scene(root, 600, 550));
Main.window.show();
}
}
}
else if (userComboBox.getSelectionModel().getSelectedItem().toString().equals("Librarian"))
{
for(Librarian librarian : Main.library.getLibrarians())
{
if(librarian.getUsername().equals(username.getText()))
{
Main.signedIn = librarian;
Parent root = FXMLLoader.load(getClass().getResource("librarianPage.fxml"));
Main.window.setTitle("Tawe Lib");
Main.window.setScene(new Scene(root, 600, 550));
Main.window.show();
}
}
}
}
}
|
package com.icesoft.gettumblr.models;
public class VideoTumblrResult extends TumblrResult {
private static final int TYPE = 1;
private VideoDetail[] details;
public VideoTumblrResult(String queryString, Exception exception,VideoDetail[] details) {
super(queryString, exception);
this.details = details;
}
public VideoDetail[] getVideoDetails()
{
return details;
}
}
|
package server.dao;
import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.logging.Logger;
import shared.model.IndexerData;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
public class RecordIndexerDB {
public static final String DB_NAME = "RecordIndexer";
private final static String ImportFile = "database.sql";
/**
* Initialize(Create new) Database
* @throws ClassNotFoundException
* @throws SQLException
* @throws FileNotFoundException
*/
public static void initialize() throws ClassNotFoundException
{
Class.forName("org.sqlite.JDBC");
}
public static void dropTablesAndBuildNew() throws ClassNotFoundException, SQLException, FileNotFoundException
{
Logger.getLogger("Initialize Database");
Connection connection = DriverManager.getConnection("jdbc:sqlite:database/" + DB_NAME + ".sqlite");
connection.setAutoCommit(false);
int errorCount = 0;
File file = new File(ImportFile);
Scanner scan = new Scanner(file);
String query = "";
while(scan.hasNextLine())
{
query+=scan.nextLine();
if(query.contains(";"))
{
try
{
Statement statement = connection.createStatement();
statement.execute(query);
statement.close();
query = "";
}
catch (SQLException e)
{
System.out.println("Failed to execute "+query);
errorCount++;
if(errorCount>=10)
{
System.out.println("Too many Errors on Initializing");
System.exit(1);
}
}
}
}
System.out.println(errorCount + " errors were occured while initializing database");
connection.commit();
connection.close();
}
/**
* Import Database from XML
* @param file_name
* @throws ClassNotFoundException
* @throws SQLException
*/
public static void ImportDatabase(String file_name) throws ClassNotFoundException, SQLException
{
System.out.println("Importing Database");
DAO dao = new DAO();
XStream xmlStream = new XStream(new DomDriver());
xmlStream.processAnnotations(IndexerData.class);
File file = new File(file_name);
IndexerData db = (IndexerData) xmlStream.fromXML(file);
dao.userParseAndInsertInDB(db.getUser_list());
if(db.getProject_list()!=null)
{
dao.projectParseAndInsertInToDB(db.getProject_list());
}
}
}
|
/**
* Sort a linked list in O(n log n) time using constant space complexity.
*
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public static void main(String[] args) {
ListNode list = new ListNode((int)(Math.random() * 100));
ListNode temp = list;
for (int i = 0; i < 7; i++) {
temp.next = new ListNode((int)(Math.random() * 100));
temp = temp.next;
}
System.out.println("Original:");
temp = list;
do {
System.out.print(" " + temp.val);
} while((temp = temp.next) != null);
System.out.println("\nResult:");
temp = sortList(list);
do {
System.out.print(" " + temp.val);
} while((temp = temp.next) != null);
}
public static ListNode sortList(ListNode head) {//recursion
if (head == null || head.next == null) {
return head;
}
ListNode p = head;
ListNode f = head;
while ( f.next !=null && f.next.next !=null ){//locate p at half of the ListNode
p = p.next;
f = f.next.next;
}
//for GC to collect the p.next point.
ListNode h2 = sortList(p.next);
p.next = null;
//return merge(sortList(head), sortList(p.next)) , it's wrong.
return merge(sortList(head), h2);
}
/**
* MergeSort
*/
private static ListNode merge(ListNode h1, ListNode h2){
/*
* maybe h2.val < h1.val
* then h2.val should be inserted before h1.
* so new a ListNode preh1 to be the virtual head.
* h2.val can be inserted between the preh and h1.
*/
ListNode preh1 = new ListNode(-1);
ListNode temp = preh1;
while(h1 != null && h2 != null){
if (h1.val <= h2.val) {
preh1.next = h1;
h1 = h1.next;
} else {
//insert operation.
preh1.next = h2;
h2 = h2.next;
}
preh1 = preh1.next;
}
if(h1 == null){
preh1.next = h2;
}else{
preh1.next = h1;
}
return temp.next;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
|
/*
* 文 件 名: HttpClientUtil.java
* 描 述: HttpClientUtil.java
* 时 间: 2013-7-8
*/
package com.babyshow.util;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
/**
*
* 调用apache httpclient 4.x 发送GET、POST请求
*
* @author ztc
* @version [BABYSHOW V1R1C1, 2013-7-8]
*/
public class HttpClientUtil
{
/**
* 日志
*/
private static Logger log = Logger.getLogger(HttpClientUtil.class);
/**
*
* 向指定URL post数据,数据可为String或File,用Map键值对对应
*
* 成功返回true,失败返回false
* @param url
* @param map
* @return
*/
public static boolean postData(String url, Map<String, Object> map)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
Object paramValue = null;
StringBody stringBody = null;
FileBody fileBody = null;
try
{
for (String paramName : map.keySet())
{
paramValue = map.get(paramName);
if (paramValue instanceof String)
{
stringBody = new StringBody((String)paramValue);
multipartEntity.addPart(paramName, stringBody);
}
else if (paramValue instanceof File)
{
fileBody = new FileBody((File)paramValue);
multipartEntity.addPart(paramName, fileBody);
}
}
}
catch (UnsupportedEncodingException e)
{
log.info("UnsupportedEncodingException", e);
}
httpost.setEntity(multipartEntity);
HttpResponse httpResponse = null;
try
{
httpResponse = httpclient.execute(httpost);
}
catch (ClientProtocolException e)
{
log.info("ClientProtocolException", e);
}
catch (IOException e)
{
log.info("IOException", e);
}
finally
{
httpclient.getConnectionManager().shutdown();
}
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return true;
}
else
{
log.info("httpResponse Code is " + httpResponse.getStatusLine().getStatusCode());
return false;
}
}
}
|
package pl.todoapplication.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import pl.todoapplication.entity.RoleEntity;
@Repository
public interface RoleRepository extends CrudRepository<RoleEntity, Long> {
RoleEntity findByName(String name);
}
|
package com.ahsel.simbirsoft.controllers;
import com.ahsel.simbirsoft.models.Words;
import com.ahsel.simbirsoft.repo.WordsRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class MainController {
@Autowired
private WordsRepository wordsRepository;
@GetMapping("/")
public String home() {
return "home";
}
}
|
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.testng.annotations.Test;
import entities.User;
public class BodyTestWithJackson extends BaseClass {
@Test
public void returnCorrectLogin() throws ClientProtocolException, IOException {
HttpGet get = new HttpGet(TARGET_URL+"/users/rdhananjay7");
response = client.execute(get);
User user = ResponseUtils.unmarshall(response, User.class);
assertEquals(user.getLogin(), "rdhananjay7");
}
}
|
package com.yfancy.app.log.listener;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.yfancy.common.base.entity.Notify;
import com.yfancy.service.notify.api.service.NotifyRpcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
@Slf4j
public class RocketMqConsumerListener implements MessageListenerConcurrently {
@Reference
private NotifyRpcService notifyRpcService;
/**
* It is not recommend to throw exception,rather than returning ConsumeConcurrentlyStatus.RECONSUME_LATER if
* consumption failure
*
* @param msgs msgs.size() >= 1<br> DefaultMQPushConsumer.consumeMessageBatchMaxSize=1,you can modify here
* @param context
* @return The consume status
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
System.out.printf("%s Receive New Messages: %s %n", Thread.currentThread().getName(), msgs);
for (MessageExt messageExt : msgs){
String s = new String(messageExt.getBody());
System.out.printf("sss" + s);
try {
Notify notify = JSONObject.parseObject(s, Notify.class);
notifyRpcService.saveNotify(notify);
}catch (Exception e){
log.error("this is not a notify object message, error");
}
}
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
}
}
|
/*
* Copyright © 2014 YAOCHEN Corporation, All Rights Reserved.
*/
package com.yaochen.address.data.domain.address;
public class AdEditTemplateDetail {
/** 模板ID */
private Integer templateId;
/** 层级 */
private Integer levelNum;
/** 层级定义类型 */
private String configType;
/** 层级展示明细 */
private String configJson;
public Integer getTemplateId() {
return templateId;
}
public void setTemplateId(Integer templateId) {
this.templateId = templateId;
}
public Integer getLevelNum() {
return levelNum;
}
public void setLevelNum(Integer levelNum) {
this.levelNum = levelNum;
}
public String getConfigType() {
return configType;
}
public void setConfigType(String configType) {
this.configType = configType == null ? null : configType.trim();
}
public String getConfigJson() {
return configJson;
}
public void setConfigJson(String configJson) {
this.configJson = configJson == null ? null : configJson.trim();
}
}
|
package panels.sort;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SortPanel extends JPanel {
private GridBagConstraints gbc;
private JPanel pFpLeft, pFpRight;
private JLabel lHead;
private JTextField tfFilter;
private JSplitPane spSplit;
private JButton bSort;
public SortPanel() {
setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weighty = 0;
gbc.weightx = 1;
gbc.gridwidth=2;
lHead = new JLabel();
lHead.setText("----- Sort -----");
lHead.setHorizontalAlignment(SwingConstants.CENTER);
add(lHead, gbc);
pFpLeft = new FilePanel();
pFpRight = new FilePanel();
spSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
spSplit.setLeftComponent(pFpLeft);
spSplit.setRightComponent(pFpRight);
spSplit.setDividerLocation(0.5); //no effect Todo: fix
spSplit.setOneTouchExpandable(true);
gbc.weighty = 1;
gbc.gridy=1;
add(spSplit, gbc);
gbc.gridwidth=1;
bSort = new JButton();
bSort.setText("start Sorting");
gbc.weighty=0;
gbc.weightx=0;
gbc.insets= new Insets(5, 0, 5, 0);
gbc.gridy=2;
add(bSort,gbc);
tfFilter = new JTextField();
tfFilter.setText("only use file with ending ...");
tfFilter.setForeground(Color.GRAY);
tfFilter.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
tfFilter.setText("");
tfFilter.setForeground(Color.black);
}
@Override
public void focusLost(FocusEvent e) {
if (tfFilter.getText().length()==0) {
tfFilter.setText("only use file with ending ...");
tfFilter.setForeground(Color.GRAY);
}
}
});
gbc.weightx=1;
gbc.insets= new Insets(5, 5, 5, 0);
add(tfFilter, gbc);
validate();
repaint();
}
}
|
/**
*
*/
package com.infogen.self_description.component;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* 方法入参描述
* @author larry/larrylv@outlook.com/创建时间 2015年8月3日 上午11:22:14
* @since 1.0
* @version 1.0
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
public class InParameter {
private String name;
@JsonIgnore
private Class<?> type;
private Boolean required = true;
private String default_value = "";
private String describe = "";
public InParameter() {
}
public InParameter(String name, Class<?> type, Boolean required, String default_value, String describe) {
super();
this.name = name;
this.type = type;
this.required = required;
this.default_value = default_value;
this.describe = describe;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescribe() {
return describe;
}
public void setDescribe(String describe) {
this.describe = describe;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getDefault_value() {
return default_value;
}
public void setDefault_value(String default_value) {
this.default_value = default_value;
}
}
|
package com.pangpang6.hadoop.flink.apps;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
public class MainCheckPoint {
public static void main(String[] args) {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// 每隔1000 ms进行启动一个检查点【设置checkpoint的周期】
env.enableCheckpointing(1000);
// 高级选项:
// 设置模式为exactly-once (这是默认值)
env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);
// 确保检查点之间有至少500 ms的间隔【checkpoint最小间隔】
env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
// 检查点必须在一分钟内完成,或者被丢弃【checkpoint的超时时间】
env.getCheckpointConfig().setCheckpointTimeout(60000);
// 同一时间只允许进行一个检查点
env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
// 表示一旦Flink处理程序被cancel后,会保留Checkpoint数据,以便根据实际需要恢复到指定的Checkpoint【详细解释见备注】
env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
}
}
|
package decorator.design.pattern.example2;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class TestDecorator {
public static void main(String[] args) {
int c;
InputStream in=null;
try{
try{
in=new UpperCaseInputStream(new FileInputStream("D:\\inventory.txt"));
}catch(FileNotFoundException fio){
System.out.println("ERROR : Please specify corrrect path to file inventory.txt");
}
while((c=in.read()) >= 0){
System.out.print((char)c);
}
in.close();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
|
package org.movilforum.net.media;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
public class VideoStreamManager extends StreamManager implements Runnable{
byte pDataVideo[]={(byte)0x80,(byte) 0xc9,(byte) 0x00,(byte) 0x01,(byte) 0x73,(byte) 0xaa,(byte) 0xdf,(byte) 0xe2,(byte)
0x81,(byte) 0xca,(byte) 0x00,(byte) 0x06,(byte) 0x52,(byte) 0xb1,(byte) 0x9e,(byte) 0xd0,(byte)
0x01,(byte) 0x0e,(byte) 0x46,(byte) 0x72,(byte) 0x61,(byte) 0x6e,(byte) 0x5f,(byte) 0x6d,(byte)
0x40,(byte) 0x46,(byte) 0x72,(byte) 0x61,(byte) 0x6e,(byte) 0x5f,(byte) 0x6d,(byte) 0x31,(byte)
0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x81,(byte) 0xcb,(byte) 0x00,(byte) 0x01,(byte)
0x73,(byte) 0xaa,(byte) 0xdf,(byte) 0xe2};
byte pDataVideoData[]={(byte)0x80,(byte) 0x22,(byte) 0x8e,(byte) 0x9c,(byte) 0xef,(byte) 0xdb,(byte) 0xaf,(byte) 0x08,(byte)
0x73,(byte) 0xaa,(byte) 0xdf,(byte) 0xe2,(byte) 0x00,(byte) 0x40,(byte) 0x00,(byte) 0x00,(byte)
0x00,(byte) 0x80,(byte) 0x02,(byte) 0x08,(byte) 0x08};
public VideoStreamManager(String basePath, String remotePort, DatagramSocket socket , DatagramSocket controlSocket) {
super(basePath, remotePort, socket, controlSocket);
}
@Override
public void startTransMission(String from) throws IOException {
super.startTransMission(from, "263");
new Thread(this).start();
}
public void run() {
//Sends the video control data
try{
this.sendData(pDataVideo, Integer.parseInt(this.remotePort) + 1);
new ControlManager(this.controlSocket, "Video");
//The video data itself
this.sendData(pDataVideoData, Integer.parseInt(this.remotePort));
while(!this.ended) {
byte [] data = this.receiveData(this.socket);
}
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Override
protected void terminate() throws IOException {
byte pDataVideo[]={(byte)0x80,(byte) 0xc9,(byte) 0x00,(byte) 0x01,(byte) 0x73,(byte) 0xaa,(byte) 0xdf,(byte) 0xe2,(byte)
0x81,(byte) 0xca,(byte) 0x00,(byte) 0x06,(byte) 0x52,(byte) 0xb1,(byte) 0x9e,(byte) 0xd0,(byte)
0x01,(byte) 0x0e,(byte) 0x53,(byte) 0x49,(byte) 0x50,(byte) 0x54,(byte) 0x53,(byte) 0x54,(byte)
0x40,(byte) 0x53,(byte) 0x49,(byte) 0x50,(byte) 0x54,(byte) 0x53,(byte) 0x54,(byte) 0x31,(byte)
0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x81,(byte) 0xcb,(byte) 0x00,(byte) 0x01,(byte)
0x73,(byte) 0xaa,(byte) 0xdf,(byte) 0xe2};
this.controlSocket.send(new DatagramPacket(pDataVideo, pDataVideo.length));
this.controlSocket.close();
this.socket.close();
}
@Override
protected byte[] transformDataToBeConverted(byte[] data, int length) {
byte[] result = Arrays.copyOf(data, length);
return result;
}
}
|
/**
* original(c) zhuoyan company
* projectName: java-design-pattern
* fileName: NumberCommand.java
* packageName: cn.zy.pattern.command.undo
* date: 2018-12-19 23:35
* history:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package cn.zy.pattern.command.undo;
/**
* @version: V1.0
* @author: ending
* @className: NumberCommand
* @packageName: cn.zy.pattern.command.undo
* @description:
* @data: 2018-12-19 23:35
**/
public class NumberCommand extends AbstractCommand {
private NumberOperation numberOperation = new NumberOperation();
private Integer value;
@Override
public Integer execute(int num) {
this.value = num;
return numberOperation.add(num);
}
@Override
public Integer undo() {
return numberOperation.add(- this.value);
}
}
|
package great_class31;
import java.util.Stack;
/**
* Create By LKUNZ on 2023/6/5
*/
public class Problem_0150_EvaluateReversePolishNotation {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String str : tokens) {
if ("+".equals(str) || "-".equals(str) || "*".equals(str) || "/".equals(str)){
compulate(stack, str);
} else {
stack.push(Integer.valueOf(str));
}
}
return stack.peek();
}
private void compulate(Stack<Integer> stack, String str) {
Integer num1 = stack.pop();
Integer num2 = stack.pop();
Integer result = 0;
switch (str) {
case "+" :
result = num2 + num1;
break;
case "-" :
result = num2 - num1;
break;
case "*":
result = num2 * num1;
break;
case "/":
result = num2 / num1;
break;
}
stack.push(result);
}
}
|
package com.example.bratwurst.model;
public class User {
private int id;
private String username;
private String password;
private String salt;
private String first_name;
private String last_name;
private String country;
private String city;
private int age;
private String email;
private boolean gender;
private String profile_picture;
public User(int id, String username, String password, String salt, String first_name, String last_name, String country, String city, int age, String email, boolean gender, String profile_picture) {
this.id = id;
this.username = username;
this.password = password;
this.salt = salt;
this.first_name = first_name;
this.last_name = last_name;
this.country = country;
this.city = city;
this.age = age;
this.email = email;
this.gender = gender;
this.profile_picture = profile_picture;
}
//Get Users at homepage
public User(String username, String first_name, String last_name, String country, String email) {
this.username = username;
this.first_name = first_name;
this.last_name = last_name;
this.country = country;
this.email = email;
}
public User() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isGender() {
return gender;
}
public void setGender(boolean gender) {
this.gender = gender;
}
public String getProfile_picture() {
return profile_picture;
}
public void setProfile_picture(String profile_picture) {
this.profile_picture = profile_picture;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
", country='" + country + '\'' +
", city='" + city + '\'' +
", age=" + age +
", gender=" + gender +
", profile_picture='" + profile_picture + '\'' +
'}';
}
}
|
package com.kunsoftware.bean;
import java.util.Date;
public class ProductResourceRequestBean {
private String name;
private String startCountry;
private String startCity;
private String arriveCountry;
private String arriveCity;
private String destination;
private Integer arriveDestination;
private String productType;
private Integer productId;
private Integer flightId;
private Integer groundId;
private Integer travelDays;
private Integer stayDays;
private Integer earlyDays;
private Integer orderValue;
private Integer standardPrice;
private String interactRecommend;
private String whetherShelf;
private Date flightCheduleStart;
private Date flightCheduleEnd;
private String week;
private String salePrice;
private String marryRecommend;
private String combo;
private Integer somePraise;
private String customMade;
private String tag;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStartCountry() {
return startCountry;
}
public void setStartCountry(String startCountry) {
this.startCountry = startCountry;
}
public String getStartCity() {
return startCity;
}
public void setStartCity(String startCity) {
this.startCity = startCity;
}
public String getArriveCountry() {
return arriveCountry;
}
public void setArriveCountry(String arriveCountry) {
this.arriveCountry = arriveCountry;
}
public String getArriveCity() {
return arriveCity;
}
public void setArriveCity(String arriveCity) {
this.arriveCity = arriveCity;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public Integer getArriveDestination() {
return arriveDestination;
}
public void setArriveDestination(Integer arriveDestination) {
this.arriveDestination = arriveDestination;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public Integer getFlightId() {
return flightId;
}
public void setFlightId(Integer flightId) {
this.flightId = flightId;
}
public Integer getGroundId() {
return groundId;
}
public void setGroundId(Integer groundId) {
this.groundId = groundId;
}
public Integer getTravelDays() {
return travelDays;
}
public void setTravelDays(Integer travelDays) {
this.travelDays = travelDays;
}
public Integer getStayDays() {
return stayDays;
}
public void setStayDays(Integer stayDays) {
this.stayDays = stayDays;
}
public Integer getEarlyDays() {
return earlyDays;
}
public void setEarlyDays(Integer earlyDays) {
this.earlyDays = earlyDays;
}
public Integer getOrderValue() {
return orderValue;
}
public void setOrderValue(Integer orderValue) {
this.orderValue = orderValue;
}
public Integer getStandardPrice() {
return standardPrice;
}
public void setStandardPrice(Integer standardPrice) {
this.standardPrice = standardPrice;
}
public String getInteractRecommend() {
return interactRecommend;
}
public void setInteractRecommend(String interactRecommend) {
this.interactRecommend = interactRecommend;
}
public String getWhetherShelf() {
return whetherShelf;
}
public void setWhetherShelf(String whetherShelf) {
this.whetherShelf = whetherShelf;
}
public Date getFlightCheduleStart() {
return flightCheduleStart;
}
public void setFlightCheduleStart(Date flightCheduleStart) {
this.flightCheduleStart = flightCheduleStart;
}
public Date getFlightCheduleEnd() {
return flightCheduleEnd;
}
public void setFlightCheduleEnd(Date flightCheduleEnd) {
this.flightCheduleEnd = flightCheduleEnd;
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getSalePrice() {
return salePrice;
}
public void setSalePrice(String salePrice) {
this.salePrice = salePrice;
}
public String getMarryRecommend() {
return marryRecommend;
}
public void setMarryRecommend(String marryRecommend) {
this.marryRecommend = marryRecommend;
}
public String getCombo() {
return combo;
}
public void setCombo(String combo) {
this.combo = combo;
}
public Integer getSomePraise() {
return somePraise;
}
public void setSomePraise(Integer somePraise) {
this.somePraise = somePraise;
}
public String getCustomMade() {
return customMade;
}
public void setCustomMade(String customMade) {
this.customMade = customMade;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
|
package app.com.blogapi.adaptadores;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Date;
import java.util.List;
import app.com.blogapi.entidades.Comments;
import app.com.blogapi.R;
public class AdaptadorComentario extends RecyclerView.Adapter<AdaptadorComentario.ViewHolder> {
public List<Comments> dataComments;
public AdaptadorComentario(List<Comments> dataComments) {
this.dataComments = dataComments;
}
@NonNull
@Override
public AdaptadorComentario.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_comment,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull AdaptadorComentario.ViewHolder holder, int position) {
Comments comments = dataComments.get(position);
Date date = new Date(comments.getCreatedAt());
holder.author.setText(comments.getUserName()+" ("+comments.getUserEmail()+")");
holder.date.setText(String.valueOf(date));
holder.comment.setText(comments.getBody());
}
@Override
public int getItemCount() {
return dataComments.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
private TextView author, date, comment;
public ViewHolder(@NonNull View itemView) {
super(itemView);
author = itemView.findViewById(R.id.commentAuthor);
date = itemView.findViewById(R.id.commentDate);
comment = itemView.findViewById(R.id.commentBody);
}
}
}
|
package com.mideas.rpg.v2.hud.auction;
import java.util.ArrayList;
import com.mideas.rpg.v2.FontManager;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.game.auction.AuctionHouseFilter;
import com.mideas.rpg.v2.game.auction.AuctionHouseSort;
import com.mideas.rpg.v2.render.Draw;
import com.mideas.rpg.v2.render.Sprites;
import com.mideas.rpg.v2.render.TTF;
import com.mideas.rpg.v2.utils.ButtonMenuSort;
import com.mideas.rpg.v2.utils.Color;
import com.mideas.rpg.v2.utils.Frame;
import com.mideas.rpg.v2.utils.InputBox;
import com.mideas.rpg.v2.utils.ScrollBar;
public class AuctionHouseBrowseFrame extends Frame
{
@SuppressWarnings("hiding")
private AuctionHouseFrame parentFrame;
private final ArrayList<AuctionHouseBrowseCategoryFilterButton> categoryList;
private AuctionHouseFilter categoryFilter = AuctionHouseFilter.NONE;
private boolean categoryFilterScrollbarEnabled;
private short filterScrollbarYOffset;
private short categoryFilterTotalLine;
AuctionHouseSort selectedSort = AuctionHouseSort.RARITY_ASCENDING;
private final InputBox searchInputBox = new InputBox(this, "AuctionHouseFrameSearchInputBox", SEARCH_INPUT_BOX_X, SEARCH_INPUT_BOX_Y, SEARCH_INPUT_BOX_WIDTH, (short)63, SEARCH_INPUT_BOX_TEXT_X_OFFSET, SEARCH_INPUT_BOX_TEXT_Y_OFFSET, SEARCH_INPUT_BOX_TEXT_MAX_WIDTH, INPUT_BOX_FONT, false, SEARCH_INPUT_BOX_CURSOR_WIDTH, SEARCH_INPUT_BOX_CURSOR_HEIGHT, "Search", true, INPUT_BOX_COLOR)
{
@Override
public boolean keyEvent(char c)
{
return (false);
}
};
private final InputBox minLevelInputBox = new InputBox(this, "AuctionHouseFrameMinLevelInputBox", MIN_LEVEL_INPUT_BOX_X, MIN_LEVEL_INPUT_BOX_Y, MIN_LEVEL_INPUT_BOX_WIDTH, (short)2, MIN_LEVEL_INPUT_BOX_TEXT_X_OFFSET, MIN_LEVEL_INPUT_BOX_TEXT_Y_OFFSET, MIN_LEVEL_INPUT_BOX_TEXT_MAX_WIDTH, INPUT_BOX_FONT, true, MIN_LEVEL_INPUT_BOX_CURSOR_WIDTH, MIN_LEVEL_INPUT_BOX_CURSOR_HEIGHT, "", false, INPUT_BOX_COLOR)
{
@Override
public boolean keyEvent(char c)
{
return (false);
}
};
private final InputBox maxLevelInputBox = new InputBox(this, "AuctionHouseFrameMaxLevelInputBox", MAX_LEVEL_INPUT_BOX_X, MAX_LEVEL_INPUT_BOX_Y, MAX_LEVEL_INPUT_BOX_WIDTH, (short)2, MAX_LEVEL_INPUT_BOX_TEXT_X_OFFSET, MAX_LEVEL_INPUT_BOX_TEXT_Y_OFFSET, MAX_LEVEL_INPUT_BOX_TEXT_MAX_WIDTH, INPUT_BOX_FONT, true, MAX_LEVEL_INPUT_BOX_CURSOR_WIDTH, MAX_LEVEL_INPUT_BOX_CURSOR_HEIGHT, "", false, INPUT_BOX_COLOR)
{
@Override
public boolean keyEvent(char c)
{
return (false);
}
};
private final ScrollBar filterScrollbar = new ScrollBar(this, FILTER_SCROLLBAR_X, FILTER_SCROLLBAR_Y, FILTER_SCROLLBAR_HEIGHT, FILTER_SCROLLBAR_WIDTH, FILTER_SCROLLBAR_HEIGHT, false, CATEGORY_FILTER_BUTTON_Y_SHIFT, false) {
@SuppressWarnings("synthetic-access")
@Override
public void onScroll() {
onCategoryFilterScrollbarScroll();
}
};
private final ButtonMenuSort sortByRarityButton = new ButtonMenuSort(this, SORT_RARITY_BUTTON_X, SORT_BUTTON_Y, SORT_RARITY_BUTTON_WIDTH, SORT_BUTTON_HEIGHT, "Rarity", BUTTON_SORT_FONT) {
@Override
public void eventButtonClick() {
if(AuctionHouseBrowseFrame.this.selectedSort == AuctionHouseSort.RARITY_ASCENDING)
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.RARITY_DESCENDING;
else
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.RARITY_ASCENDING;
sendSearchQuery();
}
};
private final ButtonMenuSort sortByLevelButton = new ButtonMenuSort(this, SORT_LEVEL_BUTTON_X, SORT_BUTTON_Y, SORT_LEVEL_BUTTON_WIDTH, SORT_BUTTON_HEIGHT, "Lvl", BUTTON_SORT_FONT) {
@Override
public void eventButtonClick() {
if(AuctionHouseBrowseFrame.this.selectedSort == AuctionHouseSort.LEVEL_ASCENDING)
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.LEVEL_DESCENDING;
else
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.LEVEL_ASCENDING;
sendSearchQuery();
}
};
private final ButtonMenuSort sortByTimeLeftButton = new ButtonMenuSort(this, SORT_TIME_LEFT_BUTTON_X, SORT_BUTTON_Y, SORT_TIME_LEFT_BUTTON_WIDTH, SORT_BUTTON_HEIGHT, "Time Left", BUTTON_SORT_FONT) {
@Override
public void eventButtonClick() {
if(AuctionHouseBrowseFrame.this.selectedSort == AuctionHouseSort.TIME_LEFT_ASCENDING)
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.TIME_LEFT_DESCENDING;
else
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.TIME_LEFT_ASCENDING;
sendSearchQuery();
}
};
private final ButtonMenuSort sortBySellerButton = new ButtonMenuSort(this, SORT_SELLER_BUTTON_X, SORT_BUTTON_Y, SORT_SELLER_BUTTON_WIDTH, SORT_BUTTON_HEIGHT, "Seller", BUTTON_SORT_FONT) {
@Override
public void eventButtonClick() {
if(AuctionHouseBrowseFrame.this.selectedSort == AuctionHouseSort.VENDOR_ASCENDING)
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.VENDOR_DESCENDING;
else
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.VENDOR_ASCENDING;
sendSearchQuery();
}
};
private final ButtonMenuSort sortByPricePerUnitButton = new ButtonMenuSort(this, SORT_PRICE_PER_UNIT_BUTTON_X, SORT_BUTTON_Y, SORT_PRICE_PER_UNIT_BUTTON_WIDTH_NO_SCROLLBAR, SORT_BUTTON_HEIGHT, "Price Per Unit", BUTTON_SORT_FONT) {
@Override
public void eventButtonClick() {
if(AuctionHouseBrowseFrame.this.selectedSort == AuctionHouseSort.PRICE_PER_UNIT_ASCENDING)
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.PRICE_PER_UNIT_DESCENDING;
else
AuctionHouseBrowseFrame.this.selectedSort = AuctionHouseSort.PRICE_PER_UNIT_ASCENDING;
sendSearchQuery();
}
};
private final static short FILTER_SCROLLBAR_X = 167;
private final static short FILTER_SCROLLBAR_WIDTH = 184;
private final static short FILTER_SCROLLBAR_HEIGHT = 290;
private final static short FILTER_SCROLLBAR_Y = 100;
private final static short CATEGORY_FILTER_MAX_LINE_DISPLAYED = 15;
private final static short CATEGORY_FILTER_BUTTON_X = 21;
private final static short CATEGORY_FILTER_BUTTON_Y = 103;
public final static short CATEGORY_FILTER_BUTTON_Y_SHIFT = 20;
private final static short CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR = 167;
private final static short CATEGORY_FILTER_BUTTON_WIDTH_SCROLLBAR = 147;
public final static short CATEGORY_FILTER_MAX_Y = 408;
public final static short CATEGORY_FILTER_MIN_Y = 100;
public final static short CATEGORY_FILTER_SCISSOR_Y = 380;
public final static short CATEGORY_FILTER_SCISSOR_HEIGHT = 300;
public final static short CATEGORY_FILTER_MAX_HEIGHT = 308;
private final static short MIN_LEVEL_INPUT_BOX_X = 240;
private final static short MIN_LEVEL_INPUT_BOX_Y = 49;
private final static short MIN_LEVEL_INPUT_BOX_WIDTH = 32;
private final static short MIN_LEVEL_INPUT_BOX_TEXT_X_OFFSET = 4;
private final static short MIN_LEVEL_INPUT_BOX_TEXT_Y_OFFSET = 0;
private final static short MIN_LEVEL_INPUT_BOX_TEXT_MAX_WIDTH = 20;
private final static short MIN_LEVEL_INPUT_BOX_CURSOR_WIDTH = 4;
private final static short MIN_LEVEL_INPUT_BOX_CURSOR_HEIGHT = 14;
private final static short MAX_LEVEL_INPUT_BOX_X = 279;
private final static short MAX_LEVEL_INPUT_BOX_Y = 49;
private final static short MAX_LEVEL_INPUT_BOX_WIDTH = 32;
private final static short MAX_LEVEL_INPUT_BOX_TEXT_X_OFFSET = 4;
private final static short MAX_LEVEL_INPUT_BOX_TEXT_Y_OFFSET = 0;
private final static short MAX_LEVEL_INPUT_BOX_TEXT_MAX_WIDTH = 20;
private final static short MAX_LEVEL_INPUT_BOX_CURSOR_WIDTH = 4;
private final static short MAX_LEVEL_INPUT_BOX_CURSOR_HEIGHT = 14;
private final static short SEARCH_INPUT_BOX_X = 81;
private final static short SEARCH_INPUT_BOX_Y = 49;
private final static short SEARCH_INPUT_BOX_WIDTH = 154;
private final static short SEARCH_INPUT_BOX_TEXT_X_OFFSET = 23;
private final static short SEARCH_INPUT_BOX_TEXT_Y_OFFSET = -1;
private final static short SEARCH_INPUT_BOX_TEXT_MAX_WIDTH = 105;
private final static short SEARCH_INPUT_BOX_CURSOR_WIDTH = 4;
private final static short SEARCH_INPUT_BOX_CURSOR_HEIGHT = 14;
private final static Color INPUT_BOX_COLOR = Color.WHITE;
private final static TTF INPUT_BOX_FONT = FontManager.get("FRIZQT", 13);
private final static short SORT_BUTTON_Y = 80;
private final static short SORT_BUTTON_HEIGHT = 21;
private final static short SORT_RARITY_BUTTON_WIDTH = 227;
private final static short SORT_RARITY_BUTTON_X = 195;
private final static short SORT_LEVEL_BUTTON_X = 420;
private final static short SORT_LEVEL_BUTTON_WIDTH = 61;
private final static short SORT_TIME_LEFT_BUTTON_X = 479;
private final static short SORT_TIME_LEFT_BUTTON_WIDTH = 96;
private final static short SORT_SELLER_BUTTON_X = 573;
private final static short SORT_SELLER_BUTTON_WIDTH = 81;
private final static short SORT_PRICE_PER_UNIT_BUTTON_X = 652;
private final static short SORT_PRICE_PER_UNIT_BUTTON_WIDTH_SCROLLBAR = 195;
private final static short SORT_PRICE_PER_UNIT_BUTTON_WIDTH_NO_SCROLLBAR = 219;
private final static TTF BUTTON_SORT_FONT = FontManager.get("FRIZQT", 11);
private short categoryFilterScissorY;
private short categoryFilterScissorHeight;
public AuctionHouseBrowseFrame(AuctionHouseFrame parentFrame)
{
super("AuctionHouseBrowseFrame");
this.parentFrame = parentFrame;
this.x = this.parentFrame.getX();
this.y = this.parentFrame.getY();
this.searchInputBox.initParentFrame(this);
this.minLevelInputBox.initParentFrame(this);
this.maxLevelInputBox.initParentFrame(this);
this.sortByLevelButton.initParentFrame(this);
this.sortByPricePerUnitButton.initParentFrame(this);
this.sortByRarityButton.initParentFrame(this);
this.sortBySellerButton.initParentFrame(this);
this.sortByTimeLeftButton.initParentFrame(this);
this.categoryList = new ArrayList<AuctionHouseBrowseCategoryFilterButton>();
this.categoryFilterScissorY = (short)(this.y + CATEGORY_FILTER_SCISSOR_Y * Mideas.getDisplayYFactor());
this.categoryFilterScissorHeight = (short)(CATEGORY_FILTER_SCISSOR_HEIGHT * Mideas.getDisplayYFactor());
this.filterScrollbar.initParentFrame(this);
buildBrowseFilterMenu();
int i = -1;
while (++i < this.categoryList.size())
this.categoryList.get(i).initParentFrame(this);
updateCategoryButton();
}
@Override
public void draw()
{
updateSize();
Draw.drawQuad(Sprites.auction_browse_frame, this.parentFrame.getX(), this.parentFrame.getY(), this.parentFrame.getWidth(), this.parentFrame.getHeight());
this.searchInputBox.draw();
this.minLevelInputBox.draw();
this.maxLevelInputBox.draw();
drawBrowseFilter();
drawButtonSort();
this.filterScrollbar.draw();
}
private void drawButtonSort()
{
Sprites.button_menu_sort.drawBegin();
this.sortByLevelButton.drawTexturePart();
this.sortByPricePerUnitButton.drawTexturePart();
this.sortByRarityButton.drawTexturePart();
this.sortBySellerButton.drawTexturePart();
this.sortByTimeLeftButton.drawTexturePart();
Sprites.button_menu_sort.drawEnd();
BUTTON_SORT_FONT.drawBegin();
this.sortByRarityButton.drawStringPart();
this.sortByLevelButton.drawStringPart();
this.sortByTimeLeftButton.drawStringPart();
this.sortBySellerButton.drawStringPart();
this.sortByPricePerUnitButton.drawStringPart();
BUTTON_SORT_FONT.drawEnd();
Sprites.button_menu_hover.drawBlendBegin();
this.sortByRarityButton.drawHoverPart();
this.sortByLevelButton.drawHoverPart();
this.sortByTimeLeftButton.drawHoverPart();
this.sortBySellerButton.drawHoverPart();
this.sortByPricePerUnitButton.drawHoverPart();
Sprites.button_menu_hover.drawBlendEnd();
}
private void drawBrowseFilter()
{
int i = -1;
Draw.glScissorBegin(0, this.categoryFilterScissorY, 500, this.categoryFilterScissorHeight);
Sprites.chat_channel_button.drawBegin();
while(++i < this.categoryList.size())
this.categoryList.get(i).drawTexturePart();
Sprites.chat_channel_button.drawEnd();
i = -1;
AuctionHouseBrowseCategoryFilterButton.font.drawBegin();
while(++i < this.categoryList.size())
this.categoryList.get(i).drawStringPart();
AuctionHouseBrowseCategoryFilterButton.font.drawEnd();
i = -1;
Sprites.button_menu_hover.drawBlendBegin();
while(++i < this.categoryList.size())
this.categoryList.get(i).drawHoverPart();
Sprites.button_menu_hover.drawBlendEnd();
Draw.glScissorEnd();
}
@Override
public boolean mouseEvent()
{
if (this.searchInputBox.mouseEvent())
return (true);
if (this.minLevelInputBox.mouseEvent())
return (true);
if (this.maxLevelInputBox.mouseEvent())
return (true);
if (this.filterScrollbar.event())
return (true);
if (this.sortByLevelButton.mouseEvent())
return (true);
if (this.sortByPricePerUnitButton.mouseEvent())
return (true);
if (this.sortByRarityButton.mouseEvent())
return (true);
if (this.sortBySellerButton.mouseEvent())
return (true);
if (this.sortByTimeLeftButton.mouseEvent())
return (true);
int i = -1;
while (++i < this.categoryList.size())
if (this.categoryList.get(i).mouseEvent())
return (true);
return (false);
}
@Override
public boolean keyboardEvent()
{
if (this.searchInputBox.keyboardEvent())
return (true);
if (this.minLevelInputBox.keyboardEvent())
return (true);
if (this.maxLevelInputBox.keyboardEvent())
return (true);
return (false);
}
void sendSearchQuery()
{
}
@Override
public void open()
{
}
@Override
public void close()
{
this.searchInputBox.setActive(false);
this.minLevelInputBox.setActive(false);
this.maxLevelInputBox.setActive(false);
}
@Override
public boolean isOpen()
{
return (false);
}
@Override
public void reset()
{
this.searchInputBox.resetText();
this.minLevelInputBox.resetText();
this.maxLevelInputBox.resetText();
}
public void updateSize()
{
if (!this.shouldUpdateSize)
return;
this.x = this.parentFrame.getX();
this.y = this.parentFrame.getY();
this.categoryFilterScissorY = (short)(this.y + CATEGORY_FILTER_SCISSOR_Y * Mideas.getDisplayYFactor());
this.categoryFilterScissorHeight = (short)(CATEGORY_FILTER_SCISSOR_HEIGHT * Mideas.getDisplayYFactor());
this.searchInputBox.updateSize();
this.minLevelInputBox.updateSize();
this.maxLevelInputBox.updateSize();
this.filterScrollbar.updateSize();
this.sortByLevelButton.updateSize();
this.sortByPricePerUnitButton.updateSize();
this.sortByRarityButton.updateSize();
this.sortBySellerButton.updateSize();
this.sortByTimeLeftButton.updateSize();
int i = -1;
while (++i < this.categoryList.size())
this.categoryList.get(i).updateSize();
this.shouldUpdateSize = false;
}
private void checkCategoryFilterScrollbar()
{
updateCategoryButton();
if (this.categoryFilterTotalLine > CATEGORY_FILTER_MAX_LINE_DISPLAYED)
enableCategoryFilterScrollbar();
else
disabledCategoryFilterScrollbar();
}
private void enableCategoryFilterScrollbar()
{
if (this.categoryFilterScrollbarEnabled)
return;
this.filterScrollbar.enable();
this.categoryFilterScrollbarEnabled = true;
int i = -1;
while (++i < this.categoryList.size())
this.categoryList.get(i).setWidth(CATEGORY_FILTER_BUTTON_WIDTH_SCROLLBAR);
}
private void disabledCategoryFilterScrollbar()
{
if (!this.categoryFilterScrollbarEnabled)
return;
this.filterScrollbar.disable();
this.categoryFilterScrollbarEnabled = false;
this.filterScrollbarYOffset = 0;
this.filterScrollbar.resetScroll();
int i = -1;
while (++i < this.categoryList.size())
this.categoryList.get(i).setWidth(CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR);
}
private void onCategoryFilterScrollbarScroll()
{
this.filterScrollbarYOffset = (short)((this.categoryFilterTotalLine - CATEGORY_FILTER_MAX_LINE_DISPLAYED) * this.filterScrollbar.getScrollPercentage());
updateCategoryButton();
}
private void updateCategoryButton()
{
int i = -1;
short currentLine = (short)-this.filterScrollbarYOffset;
short totalLine = 0;
while (++i < this.categoryList.size())
{
this.categoryList.get(i).setY(CATEGORY_FILTER_BUTTON_Y + currentLine * (CATEGORY_FILTER_BUTTON_Y_SHIFT));
currentLine += this.categoryList.get(i).getNumberLine();
totalLine += this.categoryList.get(i).getNumberLine();
}
this.categoryFilterTotalLine = totalLine;
}
public void setSelectedFilter(AuctionHouseFilter filter)
{
if (this.categoryFilter == filter)
return;
this.categoryFilter = filter;
checkCategoryFilterScrollbar();
onCategoryFilterScrollbarScroll();
}
public void unexpandAllCategoryFilter()
{
int i = -1;
while (++i < this.categoryList.size())
this.categoryList.get(i).unexpand();
}
public AuctionHouseFilter getSelectedFilter()
{
return (this.categoryFilter);
}
@Override
public void shouldUpdateSize()
{
this.shouldUpdateSize = true;
}
private void buildBrowseFilterMenu() {
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.WEAPON, 1, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_ONE_HANDED_AXE);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_TWO_HANDED_AXE);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_BOW);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_GUN);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_ONE_HANDED_MACE);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_TWO_HANDED_MACE);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_POLEARM);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_ONE_HANDED_SWORD);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_TWO_HANDED_SWORD);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_STAFF);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_FIST_WEAPON);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_MISCELLANEOUS);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_DAGGERS);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_THROW_WEAPON);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_CROSSBOW);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_WAND);
this.categoryList.get(0).addFilter(AuctionHouseFilter.WEAPON_FISHING_POLES);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.ARMOR, 2, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_MISCELLANEOUS);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_CLOTH);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_LEATHER);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_MAIL);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_PLATE);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_SHIELDS);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_LIBRAMS);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_IDOLS);
this.categoryList.get(1).addFilter(AuctionHouseFilter.ARMOR_TOTEMS);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.CONTAINER, 3, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 2 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_SOUL_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_HERB_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_ENCHANTING_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_ENGINEERING_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_GEM_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_MINING_BAG);
this.categoryList.get(2).addFilter(AuctionHouseFilter.CONTAINER_LEATHERWORKING_BAG);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.CONSUMABLES, 4, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 3 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_FOOD_AND_DRINK);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_POTION);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_ELIXIR);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_FLASK);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_BANDAGE);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_ITEMS_ENCHANCEMENTS);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_PARCHEMIN);
this.categoryList.get(3).addFilter(AuctionHouseFilter.CONSUMABLES_MISCELLANEOUS);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.TRADE_GOOD, 5, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 4 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_ELEMENTAL);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_CLOTH);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_LEATHER);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_METAL_AND_STONE);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_COOKING);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_HERB);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_ENCHANTING);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_JEWELCRAFTING);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_PARTS);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_MATERIALS);
this.categoryList.get(4).addFilter(AuctionHouseFilter.TRADE_GOOD_OTHER);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.PROJECTILE, 6, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 5 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(5).addFilter(AuctionHouseFilter.PROJECTILE_ARROW);
this.categoryList.get(5).addFilter(AuctionHouseFilter.PROJECTILE_BULLET);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.QUIVER, 7, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 6 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(6).addFilter(AuctionHouseFilter.QUIVER_QUIVER);
this.categoryList.get(6).addFilter(AuctionHouseFilter.QUIVER_GIBERNE);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.RECIPES, 8, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 7 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_BOOK);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_LEATHERWORKING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_TAILORING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_ENGINEERING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_BLACKSMITHING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_COOKING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_ALCHEMY);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_FIRST_AID);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_ENCHANTING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_FISHING);
this.categoryList.get(7).addFilter(AuctionHouseFilter.RECIPES_JEWELCRAFTING);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.GEM, 9, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 8 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_RED);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_BLUE);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_YELLOW);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_PURPLE);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_GREEN);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_ORANGE);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_META);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_SIMPLE);
this.categoryList.get(8).addFilter(AuctionHouseFilter.GEM_PRISMATIC);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.MISCELLANEOUS, 10, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 9 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
this.categoryList.get(9).addFilter(AuctionHouseFilter.MISCELLANEOUS_JUNK);
this.categoryList.get(9).addFilter(AuctionHouseFilter.MISCELLANEOUS_REAGENT);
this.categoryList.get(9).addFilter(AuctionHouseFilter.MISCELLANEOUS_COMPANION_PETS);
this.categoryList.get(9).addFilter(AuctionHouseFilter.MISCELLANEOUS_HOLIDAY);
this.categoryList.get(9).addFilter(AuctionHouseFilter.MISCELLANEOUS_OTHER);
this.categoryList.get(9).addFilter(AuctionHouseFilter.MISCELLANEOUS_MOUNT);
this.categoryList.add(new AuctionHouseBrowseCategoryFilterButton(this, AuctionHouseFilter.QUESTS, 11, CATEGORY_FILTER_BUTTON_X, CATEGORY_FILTER_BUTTON_Y + 10 * CATEGORY_FILTER_BUTTON_Y_SHIFT, CATEGORY_FILTER_BUTTON_WIDTH_NO_SCROLLBAR));
}
}
|
package com.tfq.manager.web.control;
import com.tfq.manager.web.model.request.LoginRequestVO;
import com.tfq.manager.web.model.response.LoginResponseVO;
import com.tfq.manager.web.model.response.UserInfoResponseVO;
import com.tfq.manager.web.support.TokenSupport;
import com.tfq.manager.web.support.UserSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
/**
* @author: TangFenQi
* @description:
* @date:2020/3/14 19:35
*/
@Api(value = "登录相关API", tags = {"登录相关API"})
@RestController
@RequestMapping("login")
@Slf4j
public class LoginController {
@Autowired
private TokenSupport tokenSupport;
@ApiOperation(value = "登录")
@RequestMapping(value = "login", method = RequestMethod.POST)
public LoginResponseVO toLogin(@RequestBody LoginRequestVO loginRequestVO) {
//验证用户信息
int userId=10;
//生成token保存
String token = tokenSupport.generateToken(userId);
//返回验证信息
LoginResponseVO loginResponseVO=new LoginResponseVO();
loginResponseVO.setToken(token);
return loginResponseVO;
}
@ApiOperation(value = "获取用户信息")
@RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
public UserInfoResponseVO getAuth() {
UserInfoResponseVO user=new UserInfoResponseVO();
user.setName("测试");
user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
user.setIntroduction("I am a super administrator");
List<String> roles=new ArrayList<>();
roles.add("admin");
user.setRoles(roles);
return user;
}
@ApiOperation(value = "异常信息测试")
@RequestMapping(value = "toException",method = RequestMethod.POST)
public String toException(){
throw new RuntimeException("测试系统异常");
}
@ApiOperation(value = "用户登出")
@RequestMapping(value = "logout", method = RequestMethod.POST)
public void toLogout(){
System.out.println(UserSupport.get()+":登出!");
}
}
|
package Concurrency;/**
* Created by pc on 2018/2/25.
*/
/**
* describe:
*
* @author xxx
* @date4 {YEAR}/02/25
*/
public class Car {
private boolean waxon = false;
public synchronized void waxed(){
waxon = true;
notifyAll();
}
public synchronized void buffered(){
waxon = false;
notifyAll();
}
public synchronized void waitForWxing() throws InterruptedException {
while (waxon==false){
wait();
}
}
public synchronized void waitForBuffering() throws InterruptedException {
while(waxon==true){
wait();
}
}
}
|
package dp;
public class PackageProblem {
//0-1背包问题,类似挖矿问题。
//有一堆物品,分别有他们的价值数组和体积数组,还有一个背包,体积有限,如何装价值最多的物品
public static int packageProblemI(int[] value, int[] volume, int totalVolume) {
//value:价值数组,volume:体积数组, totalVolume:背包总体积
int number = value.length;
//dp[i][j]表示前i个物品,在体积j下的最大价值
int[][] dp = new int[number+1][totalVolume+1];
for(int i=0;i<number;i++) {
dp[i][0] = 0; //很显然的,体积为0的时候,最大价值肯定也为0
}
for(int j=0;j<totalVolume;j++) {
dp[0][j] = 0; //很显然,第0件物品,给再大体积也不行,
}
for(int i=1;i<number+1;i++) {
for(int j=1;j<totalVolume+1;j++) {
if(j<volume[i-1]) //此时的体积放不下,也就是j不够,那么最大价值肯定是在dp[i-1][j]里出现
dp[i][j] = dp[i-1][j];
else {
//否则我们有2种选择,1:选择第i-1件物品放进去、2:不选择第i-1件物品
dp[i][j] = Math.max(dp[i-1][j-volume[i-1]]+value[i-1], dp[i-1][j]);
}
}
}
//输出dp看下
for(int[] A:dp) {
for(int a:A)
System.out.print(a+" ");
System.out.println();
}
return dp[number][totalVolume];
}
public static void main(String[] args) {
int[] value = {12, 10, 20, 15};
int[] volume = {2, 1, 3, 2};
int totalVolume = 5;
System.out.println(packageProblemI(value, volume, totalVolume));
}
}
|
package at.htl.mealcounter.control;
import at.htl.mealcounter.entity.Person;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.xssf.streaming.*;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.YearMonth;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
@ApplicationScoped
class ExcelPivotExample {
@Inject
PersonRepository personRepository;
@Inject
ConsumationRepository consumationRepository;
private void streamCellData(Sheet sheet, int rowsCount) {
Calendar calOne = Calendar.getInstance();
int year = calOne.get(Calendar.YEAR);
int rowsMonthCount = 0;
List<Person> personFromEntryYear = personRepository.findByEntryYear(2016);
int consumed;
/* for (int r = 1; r <= 12; r++) {
for (int i = 1; i <= YearMonth.of(year, r).lengthOfMonth(); i++) {
Row row = sheet.createRow(rowsCount+i+1);
Cell cell = row.createCell(0);
cell.setCellValue( Month.of(r).toString());
for (int j = 1; j < personFromEntryYear.size(); j++) {
Person person = personFromEntryYear.get(j-1);
if(consumationRepository.findByDateAndPerson(LocalDate.parse("2020-01-01"), person).isHasConsumed()){
consumed = 1;
}else {
consumed = 0;
}
cell = row.createCell(j);
cell.setCellValue(consumed);
}
rowsMonthCount += YearMonth.of(year, r).lengthOfMonth();
}
}*/
for (int i = 1; i <= 12 ; i++) {
for (int j = 1; j <= 31; j++) {
Row row = sheet.createRow(j);
Cell cell = row.createCell(0);
cell.setCellValue("monat");
}
}
}
public void writeExcel() throws IOException {
int rowsCount = 31;
//first create XSSFWorkbook
XSSFWorkbook wb = new XSSFWorkbook();
//create XSSFSheet with at least the headings
XSSFSheet sheet = wb.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Eintrittsjahr/Monat");
for (int i = 1; i < personRepository.findByEntryYear(2016).size(); i++) {
cell = row.createCell(i);
cell.setCellValue(personRepository.findById((long)i).getFirstName() + personRepository.findById((long)i).getLastName());
}
/* row = sheet.createRow(1);
for (int i = 1; i <= 12; i++) {
cell = row.createCell(0);
}*/
//create XSSFSheet for pivot table
XSSFSheet pivotSheet = wb.createSheet("Pivot sheet");
//create pivot table
XSSFPivotTable pivotTable = pivotSheet.createPivotTable(
new AreaReference(new CellReference("Sheet1!A1"),
new CellReference("Sheet1!R" + (rowsCount +1)), //make the reference big enough for later data
SpreadsheetVersion.EXCEL2007),
new CellReference("A5"));
//Configure the pivot table
//Use first column as row label
pivotTable.addRowLabel(0);
//Sum up the second column
for (int i = 1; i < personRepository.findByEntryYear(2016).size(); i++) {
pivotTable.addColumnLabel(DataConsolidateFunction.SUM, i);
}
//Avarage the third column
// pivotTable.addColumnLabel(DataConsolidateFunction.AVERAGE, 2);
//Add filter on forth column
// pivotTable.addReportFilter(3);
//now create SXSSFWorkbook from XSSFWorkbook
SXSSFWorkbook swb = new SXSSFWorkbook(wb);
SXSSFSheet ssheet = swb.getSheet("Sheet1");
//now stream the big amount of data to build the pivot table on into Sheet1
streamCellData(ssheet, rowsCount);
swb.write(new FileOutputStream("nfc-reader.xlsx"));
swb.close();
swb.dispose();
}
}
|
package com.rms.risproject.model.response;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class BuildingEnVo {
private static final long serialVersionUID = 1L;
private String keyID;
/**
* 楼层图片
*/
private String img;
/**
* 楼层图片
*/
private String imgEn;
private Boolean tf;
private List<Boolean> tfList;
private Map<String,BuildingEnVo> enVoMap;
private Set<BuildingEnVo> buildingEnVoSet;
private List<String> recordList;
private List<String> recordListEn;
public List<TestVo> getTestVos() {
return testVos;
}
public void setTestVos(List<TestVo> testVos) {
this.testVos = testVos;
}
private List<TestVo> testVos;
public List<String> getRecordList() {
return recordList;
}
public void setRecordList(List<String> recordList) {
this.recordList = recordList;
}
public List<String> getRecordListEn() {
return recordListEn;
}
public void setRecordListEn(List<String> recordListEn) {
this.recordListEn = recordListEn;
}
public Map<String, BuildingEnVo> getEnVoMap() {
return enVoMap;
}
public void setEnVoMap(Map<String, BuildingEnVo> enVoMap) {
this.enVoMap = enVoMap;
}
public Set<BuildingEnVo> getBuildingEnVoSet() {
return buildingEnVoSet;
}
public void setBuildingEnVoSet(Set<BuildingEnVo> buildingEnVoSet) {
this.buildingEnVoSet = buildingEnVoSet;
}
public List<Boolean> getTfList() {
return tfList;
}
public void setTfList(List<Boolean> tfList) {
this.tfList = tfList;
}
public Boolean getTf() {
return tf;
}
public void setTf(Boolean tf) {
this.tf = tf;
}
public String getKeyID() {
return keyID;
}
public void setKeyID(String keyID) {
this.keyID = keyID;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getImgEn() {
return imgEn;
}
public void setImgEn(String imgEn) {
this.imgEn = imgEn;
}
}
|
package zystudio.demo.ipc;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.View;
import zystudio.demo.R;
import zystudio.mylib.utils.LogUtil;
/**
* Created by zylab on 2017/12/12.
*/
public class ShowAIDLActivity extends Activity {
public static void showCase(Activity activity){
Intent intent=new Intent(activity,ShowAIDLActivity.class);
activity.startActivity(intent);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showbinder);
}
public void onBindBtnClick(View view){
Intent intent=new Intent(this,RemoteAIDLService.class);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
//Bind Service 相关的类
private ServiceConnection conn=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LogUtil.log("onServiceConnected occured");
RemoteAIDLService.MyBinder binder=(RemoteAIDLService.MyBinder) service;
binder.invokeServiceMethod();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
}
|
package fr.pederobien.uhc.interfaces;
import fr.pederobien.uhc.managers.EColor;
public interface IUnmodifiablePlayer {
EColor getColor();
}
|
package org.zmartonos.selenium;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import org.zmartonos.reactivex.Obeservable;
import rx.Observable;
import rx.functions.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Created by zmartonos on 22.09.16.
*/
public class FinanzenTest {
static{
System.setProperty("webdriver.gecko.driver", "/home/zmartonos/Downloads/geckodriver");
}
private static final Logger LOGGER = LogManager.getLogger();
private WebDriver driver;
private static final String URL_BASF = "http://www.finanzen.net/realtimekurs/BASF";
private static final String URL_DAX = "http://www.finanzen.net/";
private static final By XPATH = By.xpath(".//th[@class='realtime']//div[@source='lightstreamer']");
private static final By XPATH_DAX = By.xpath(".//div[@id='fragHomepageIndexTopFlop']/table[@class='jsReloadPushData']/tbody/tr[3]/td[2]/div[@source='lightstreamer']");
@Test
public void test() throws InterruptedException {
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver(capabilities);
driver.get(URL_DAX);
Observable<Float> priceObservable = Observable
.interval(0, 1, TimeUnit.SECONDS)
.map(index ->getStockPrice())
.distinctUntilChanged();
Observable<Float> changeObservable = Observable
.zip(priceObservable, priceObservable.skip(1), new Func2<Float, Float, Float>() {
@Override
public Float call(final Float price, final Float skippedPrice) {
//return String.format("price: %.2f skippedPrice: %.2f, change: %.2f", price, skippedPrice, skippedPrice - price);
return skippedPrice - price;
}
});
Observable<Float> sequenceObservable = changeObservable.scan(0f, new Func2<Float, Float, Float>() {
@Override
public Float call(Float aFloat, Float bFloat) {
return aFloat+bFloat;
}
})
.asObservable();
Observable.zip(priceObservable, changeObservable, sequenceObservable, new Func3<Float, Float, Float, String>() {
@Override
public String call(Float price, Float change, Float sequence) {
return String.format("price: %.2f change: %.2f, sequence: %.2f", price, change, sequence);
}
}).subscribe(LOGGER::info);
while(true){
}
//LOGGER.info("finished");
}
private Float getStockPrice(){
return Float.parseFloat(driver.findElement(XPATH_DAX).getText().replaceAll("\\.", "").replaceAll(",","."));
}
@AfterClass
public void tearDown(){
driver.quit();
}
}
|
/*
* Sonar Web Plugin
* Copyright (C) 2010 Matthijs Galesloot
* dev@sonar.codehaus.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sonar.plugins.web.language;
import org.sonar.api.resources.AbstractLanguage;
import org.sonar.plugins.web.api.WebConstants;
/**
* This class defines the Web language.
*
* @author Matthijs Galesloot
* @since 1.0
*/
public class Web extends AbstractLanguage {
/** All the valid web files suffixes. */
private static final String[] DEFAULT_SUFFIXES = { "xhtml", "jspf", "jsp" };
/** A web instance. */
public static final Web INSTANCE = new Web();
/** The web language name */
private static final String WEB_LANGUAGE_NAME = "Web";
/**
* Default constructor.
*/
public Web() {
super(WebConstants.LANGUAGE_KEY, WEB_LANGUAGE_NAME);
}
/**
* Gets the file suffixes.
*
* @return the file suffixes
* @see org.sonar.api.resources.Language#getFileSuffixes()
*/
public String[] getFileSuffixes() {
return DEFAULT_SUFFIXES; //NOSONAR
}
}
|
package com.commercetools.main;
import com.commercetools.Main;
import com.commercetools.pspadapter.payone.config.PropertyProvider;
import com.commercetools.pspadapter.payone.domain.ctp.CustomTypeBuilder;
import com.commercetools.pspadapter.payone.mapping.CustomFieldKeys;
import com.neovisionaries.i18n.CountryCode;
import io.sphere.sdk.carts.CartDraft;
import io.sphere.sdk.carts.CartDraftBuilder;
import io.sphere.sdk.carts.commands.CartCreateCommand;
import io.sphere.sdk.carts.commands.CartUpdateCommand;
import io.sphere.sdk.carts.commands.updateactions.AddPayment;
import io.sphere.sdk.carts.commands.updateactions.SetBillingAddress;
import io.sphere.sdk.carts.commands.updateactions.SetShippingAddress;
import io.sphere.sdk.models.Address;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.PaymentDraft;
import io.sphere.sdk.payments.PaymentDraftBuilder;
import io.sphere.sdk.payments.PaymentMethodInfoBuilder;
import io.sphere.sdk.payments.TransactionDraftBuilder;
import io.sphere.sdk.payments.TransactionState;
import io.sphere.sdk.payments.TransactionType;
import io.sphere.sdk.payments.commands.PaymentCreateCommand;
import io.sphere.sdk.payments.commands.PaymentUpdateCommand;
import io.sphere.sdk.payments.commands.updateactions.AddTransaction;
import io.sphere.sdk.payments.queries.PaymentQuery;
import io.sphere.sdk.queries.PagedQueryResult;
import io.sphere.sdk.queries.QueryPredicate;
import io.sphere.sdk.types.CustomFieldsDraft;
import io.sphere.sdk.utils.MoneyImpl;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.junit.BeforeClass;
import org.junit.Test;
import javax.annotation.Nonnull;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.function.Function;
import static com.commercetools.pspadapter.payone.domain.payone.PayonePostServiceImpl.executeGetRequest;
import static com.commercetools.pspadapter.payone.domain.payone.model.common.ResponseStatus.APPROVED;
import static com.commercetools.pspadapter.payone.domain.payone.model.common.ResponseStatus.REDIRECT;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
import static util.PaymentRequestHelperUtil.CTP_CLIENT;
import static util.PaymentRequestHelperUtil.URL_HANDLE_PAYMENT;
import static util.PaymentRequestHelperUtil.URL_START_SESSION;
import static util.PaymentRequestHelperUtil.createKlarnaPayment;
import static util.PaymentRequestHelperUtil.createPayment;
import static util.PropertiesHelperUtil.getClientId;
import static util.PropertiesHelperUtil.getClientSecret;
import static util.PropertiesHelperUtil.getPayoneKey;
import static util.PropertiesHelperUtil.getPayoneMerchantId;
import static util.PropertiesHelperUtil.getPayonePortalId;
import static util.PropertiesHelperUtil.getPayoneSubAccId;
import static util.PropertiesHelperUtil.getProjectKey;
import static util.PropertiesHelperUtil.getTenant;
public class BasicPaymentRequestWorkflowIT {
public static final int DEFAULT_PORT = 8080;
private static final Map<String, String> testInternalProperties = new HashMap<>();
@BeforeClass
public static void setUp() {
testInternalProperties.put("TENANTS", getTenant());
testInternalProperties.put("TEST_DATA_CT_PROJECT_KEY", getProjectKey());
testInternalProperties.put("TEST_DATA_CT_CLIENT_ID", getClientId());
testInternalProperties.put("TEST_DATA_CT_CLIENT_SECRET", getClientSecret());
testInternalProperties.put("TEST_DATA_PAYONE_KEY", getPayoneKey());
testInternalProperties.put("TEST_DATA_PAYONE_MERCHANT_ID", getPayoneMerchantId());
testInternalProperties.put("TEST_DATA_PAYONE_PORTAL_ID", getPayonePortalId());
testInternalProperties.put("TEST_DATA_PAYONE_SUBACC_ID", getPayoneSubAccId());
testInternalProperties.put("FIRST_TENANT_CT_PROJECT_KEY", getProjectKey());
testInternalProperties.put("FIRST_TENANT_CT_CLIENT_ID", getClientId());
testInternalProperties.put("FIRST_TENANT_CT_CLIENT_SECRET", getClientSecret());
testInternalProperties.put("FIRST_TENANT_PAYONE_KEY", getPayoneKey());
testInternalProperties.put("FIRST_TENANT_PAYONE_SUBACC_ID", getPayoneSubAccId());
testInternalProperties.put("FIRST_TENANT_PAYONE_MERCHANT_ID", getPayoneMerchantId());
testInternalProperties.put("FIRST_TENANT_PAYONE_PORTAL_ID", getPayonePortalId());
PropertyProvider propertyProvider = Main.getPropertyProvider();
List<Function<String, String>> propertiesGetters = propertyProvider.getPropertiesGetters();
propertiesGetters.add(testInternalProperties::get);
Main.main(new String[0]);
}
@Test
public void verifyCreditCardTransferPayoneRequestIsSuccess() throws Exception {
// Prepare
final String paymentId = createPayment("CREDIT_CARD", "40", "EUR");
// Test
final HttpResponse httpResponse = executeGetRequest(format(URL_HANDLE_PAYMENT + paymentId, DEFAULT_PORT));
// Assert
assertThat(httpResponse.getStatusLine().getStatusCode()).isIn(HttpStatus.SC_ACCEPTED, HttpStatus.SC_OK);
final PagedQueryResult<Payment> paymentPagedQueryResult =
CTP_CLIENT.execute(PaymentQuery.of()
.withPredicates(QueryPredicate.of(format("id=\"%s\"", paymentId))))
.toCompletableFuture().join();
assertThat(paymentPagedQueryResult.getResults().get(0))
.satisfies(
payment -> {
assertThat(payment.getPaymentStatus().getInterfaceCode()).isEqualTo(APPROVED.toString());
assertThat(payment.getTransactions().get(0).getState()).isEqualTo(TransactionState.SUCCESS);
});
}
@Test
public void verifyPaypalWalletTransferPayoneAuthorizationRequestIsSuccess() throws Exception {
// Prepare
final String paymentId = preparePaymentWithAuthorizedAmountAndOrder();
// Test
final HttpResponse httpResponse = executeGetRequest(format(URL_HANDLE_PAYMENT + paymentId, DEFAULT_PORT));
// Assert
assertThat(httpResponse.getStatusLine().getStatusCode()).isIn(HttpStatus.SC_ACCEPTED, HttpStatus.SC_OK);
final PagedQueryResult<Payment> paymentPagedQueryResult =
CTP_CLIENT.execute(PaymentQuery.of()
.withPredicates(QueryPredicate.of(format("id=\"%s\"", paymentId))))
.toCompletableFuture().join();
assertThat(paymentPagedQueryResult.getResults().get(0))
.satisfies(
payment -> {
assertThat(payment.getPaymentStatus().getInterfaceCode()).isEqualTo(REDIRECT.toString());
});
}
@Nonnull
private static String preparePaymentWithAuthorizedAmountAndOrder() {
final Map<String, Object> customFieldKeysMap = new HashMap<>();
customFieldKeysMap.put(CustomFieldKeys.SUCCESS_URL_FIELD, "https://example.com/success");
customFieldKeysMap.put(CustomFieldKeys.ERROR_URL_FIELD, "https://example.com/error");
customFieldKeysMap.put(CustomFieldKeys.CANCEL_URL_FIELD, "https://example.com/cancel");
customFieldKeysMap.put(CustomFieldKeys.REDIRECT_URL_FIELD, "https://example.com/redirect");
customFieldKeysMap.put(CustomFieldKeys.REFERENCE_FIELD, String.valueOf(new Random().nextInt() + System.nanoTime()));
customFieldKeysMap.put(CustomFieldKeys.LANGUAGE_CODE_FIELD, "en");
final MonetaryAmount monetaryAmount = MoneyImpl.ofCents(4000, "EUR");
final PaymentDraft paymentDraft =
PaymentDraftBuilder.of(monetaryAmount)
.paymentMethodInfo(PaymentMethodInfoBuilder.of()
.method("WALLET-PAYPAL")
.paymentInterface("PAYONE")
.build())
.custom(CustomFieldsDraft.ofTypeKeyAndObjects(
CustomTypeBuilder.PAYMENT_WALLET, customFieldKeysMap))
.build();
final Payment payment = CTP_CLIENT.executeBlocking(PaymentCreateCommand.of(paymentDraft));
final CartDraft cartDraft = CartDraftBuilder.of(Monetary.getCurrency("EUR")).build();
CTP_CLIENT.executeBlocking(CartUpdateCommand.of(
CTP_CLIENT.executeBlocking(CartCreateCommand.of(cartDraft)),
Arrays.asList(
AddPayment.of(payment),
SetShippingAddress.of(Address.of(CountryCode.DE)),
SetBillingAddress.of(Address.of(CountryCode.DE).withLastName("Test Buyer"))
)));
CTP_CLIENT.executeBlocking(PaymentUpdateCommand.of(payment, AddTransaction.of(TransactionDraftBuilder
.of(TransactionType.AUTHORIZATION, monetaryAmount, ZonedDateTime.now())
.state(TransactionState.PENDING)
.build())));
return payment.getId();
}
@Test
public void verifyKlarnaStartSesssionRequestIsSuccess() throws Exception {
// Prepare
final String paymentId = createKlarnaPayment("INVOICE-KLARNA", "40", "EUR");
// Test
final HttpResponse httpResponse = executeGetRequest(format(URL_START_SESSION + paymentId, DEFAULT_PORT));
// Assert
// assertThat(httpResponse.getStatusLine().getStatusCode()).isIn(HttpStatus.SC_OK);
final PagedQueryResult<Payment> paymentPagedQueryResult =
CTP_CLIENT.execute(PaymentQuery.of()
.withPredicates(QueryPredicate.of(format("id=\"%s\"", paymentId))))
.toCompletableFuture().join();
// assertThat(paymentPagedQueryResult.getResults().get(0))
// .satisfies(
// payment -> {
// assertThat(payment.getPaymentStatus().getInterfaceCode()).isEqualTo(APPROVED.toString());
// assertThat(payment.getTransactions().get(0).getState()).isEqualTo(TransactionState
// .SUCCESS);
// });
}
}
|
package vamk.java.assignment6;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Application2 {
private static enum choice {
UNKNOWN,
CONTINUE,
SEARCH,
EXIT
}
private static ArrayList<Entry> entries = new ArrayList<Entry>();
public static void main(String[] args) throws Exception {
choice userChoice = choice.UNKNOWN;
do {
userChoice = ask();
switch(userChoice) {
case CONTINUE:
addEntry();
break;
case SEARCH:
searchEntry();
break;
}
} while (userChoice != choice.EXIT);
}
private static void addEntry() throws Exception {
Scanner sc = new Scanner(System.in);
Pattern p = Pattern.compile(".*[^a-zA-Z0-9 ].*");
String name = "";
String comment = "";
Date date = new Date();
System.out.println("\n");
System.out.print("Name: ");
name = sc.nextLine();
if (p.matcher(name).matches()) {
throw new Exception("Special characters not allowed");
}
System.out.print("Comment: ");
comment = sc.nextLine();
if (p.matcher(comment).matches()) {
throw new Exception("Special characters not allowed");
}
entries.add(new Entry(name, comment, date));
}
private static void searchEntry() {
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.nextLine();
for (Entry entry : entries) {
if (entry.getName().equals(name)) {
System.out.println(entry);
}
}
}
private static choice ask() {
Scanner sc = new Scanner(System.in);
choice userChoice = choice.UNKNOWN;
System.out.println("\n");
System.out.println("1. Add entry");
System.out.println("2. Search entry");
System.out.println("0. Exit");
System.out.print("\nChoice (0, 1, 2): ");
switch(sc.nextInt()) {
case 0:
userChoice = choice.EXIT;
break;
case 1:
userChoice = choice.CONTINUE;
break;
case 2:
userChoice = choice.SEARCH;
break;
default:
userChoice = choice.UNKNOWN;
break;
}
return userChoice;
}
}
|
package com.jim.multipos.ui.cash_management.dialog;
import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.Window;
import com.jim.mpviews.RecyclerViewWithMaxHeight;
import com.jim.multipos.R;
import com.jim.multipos.data.DatabaseManager;
import com.jim.multipos.data.db.model.order.Order;
import com.jim.multipos.data.db.model.order.PayedPartitions;
import com.jim.multipos.ui.cash_management.adapter.PaymentTypesAdapter;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by Sirojiddin on 14.02.2018.
*/
public class CloseOrderWithPayDialog extends Dialog {
@BindView(R.id.rvPaymentTypes)
RecyclerViewWithMaxHeight rvPaymentTypes;
private PaymentTypesAdapter adapter;
public CloseOrderWithPayDialog(@NonNull Context context, DatabaseManager databaseManager, Order order, OnPaymentTypeSelected onPaymentTypeSelected) {
super(context);
View dialogView = getLayoutInflater().inflate(R.layout.payments_list_dialog, null);
ButterKnife.bind(this, dialogView);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(dialogView);
View v = getWindow().getDecorView();
v.setBackgroundResource(android.R.color.transparent);
rvPaymentTypes.setLayoutManager(new LinearLayoutManager(context));
rvPaymentTypes.setMaxHeight(300);
adapter = new PaymentTypesAdapter();
rvPaymentTypes.setAdapter(adapter);
adapter.setData(databaseManager.getPaymentTypes());
double dueSum = order.getForPayAmmount() - order.getTotalPayed();
adapter.setListener(paymentType -> {
if (dueSum == 0) {
onPaymentTypeSelected.onPaymentTypeSelect();
} else {
PayedPartitions partitions = new PayedPartitions();
partitions.setOrderId(order.getId());
partitions.setPaymentType(paymentType);
partitions.setValue(dueSum);
List<PayedPartitions> payedPartitions = new ArrayList<>();
payedPartitions.add(partitions);
databaseManager.insertPayedPartitions(payedPartitions).blockingGet();
onPaymentTypeSelected.onPaymentTypeSelect();
}
dismiss();
});
}
public interface OnPaymentTypeSelected {
void onPaymentTypeSelect();
}
}
|
package cz.zcu.fav.kiv.eitm.menubot;
import java.util.ArrayList;
import java.util.List;
public class Restaurant {
String name;
List<String> menu;
String menuString;
public Restaurant(String name, int menuSize) {
this.name = name;
this.menu = new ArrayList<>(menuSize);
this.menuString = null;
}
public void createMenuString(StringBuilder sb) {
for (int i = 0; i < this.menu.size(); i++) {
sb.append(this.menu.get(i));
if (i != this.menu.size() -1)
sb.append(" ••• ");
}
this.menuString = sb.toString();
sb.setLength(0);
}
}
|
package net.d4rk.inventorychef.inventory.expandablelistview.roomembedded.database.dao;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* Created by d4rk on 30/03/2018.
*/
@Entity(tableName = "Purchase")
public class Purchase {
@PrimaryKey(autoGenerate = true)
private long id;
@ColumnInfo(name = "IngredientID")
private long ingredientId;
@ColumnInfo(name = "Amount")
private int amount;
@ColumnInfo(name = "PurchaseTimestamp")
private long purchaseTimestamp;
@ColumnInfo(name = "Deleted")
private boolean deleted;
@ColumnInfo(name = "DeleteTimestamp")
private long deleteTimestamp;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getIngredientId() {
return ingredientId;
}
public void setIngredientId(long ingredientId) {
this.ingredientId = ingredientId;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public long getPurchaseTimestamp() {
return purchaseTimestamp;
}
public void setPurchaseTimestamp(long purchaseTimestamp) {
this.purchaseTimestamp = purchaseTimestamp;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public long getDeleteTimestamp() {
return deleteTimestamp;
}
public void setDeleteTimestamp(long deleteTimestamp) {
this.deleteTimestamp = deleteTimestamp;
}
}
|
package ReaderDemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author Bohdan Skrypnyk
*/
public class BRRead {
public static void main(String args[]) {
try {
char c;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any symbol\nor press c to exit");
do {
//the method read symbols from the input stream and return it as the integer
//char used to convert unicode
c = (char) bf.read();
} while (c != 'c');// the system will loop until the user press character 'c'
} catch (IOException ex) {
System.out.println("Exception");
}
}
}
|
package sevenkyu.onesandzeroes;
import java.util.List;
import java.util.stream.Collectors;
class OnesAndZeros {
public int convertBinaryArrayToInt(List<Integer> binary) {
String binaryString = binary.stream()
.map(String::valueOf)
.collect(Collectors.joining());
return Integer.parseInt(binaryString, 2);
}
}
|
package com.toshevski.android.shows.adapters;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.toshevski.android.shows.databases.MyData;
import com.toshevski.android.shows.pojos.Series;
import com.toshevski.android.shows.R;
import java.util.ArrayList;
public class SeriesAdapter extends BaseAdapter {
private ArrayList<Series> items;
private LayoutInflater inflater;
private Context ctx;
public SeriesAdapter(Context ctx, ArrayList<Series> items) {
this.items = items;
this.ctx = ctx;
this.inflater = LayoutInflater.from(ctx);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Series getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, final ViewGroup parent) {
final Series ser = items.get(position);
final ViewHolder vh;
if (convertView == null) {
vh = new ViewHolder();
//convertView = inflater.inflate(R.layout.series_layout, parent, false);
convertView = inflater.inflate(R.layout.series_layout_v2, parent, false);
vh.showImage = (ImageView) convertView.findViewById(R.id.sImage);
vh.showName = (TextView) convertView.findViewById(R.id.sTitle);
vh.showHeader = (TextView) convertView.findViewById(R.id.sHeader);
vh.showSubHeader = (TextView) convertView.findViewById(R.id.sSubHeader);
vh.showRating = (TextView) convertView.findViewById(R.id.sFooter);
vh.showStatus = (TextView) convertView.findViewById(R.id.sStatus);
vh.showProgress = (ProgressBar) convertView.findViewById(R.id.sUnfinishedProgress);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.showImage.setImageDrawable(MyData.getImage(ser.getImageLink()));
vh.showName.setText(ser.getTitle());
vh.showProgress.getIndeterminateDrawable().setColorFilter(Color.WHITE,
PorterDuff.Mode.DST_IN);
if (ser.isRefresh()) {
vh.showStatus.setVisibility(View.INVISIBLE);
vh.showSubHeader.setVisibility(View.INVISIBLE);
vh.showRating.setVisibility(View.INVISIBLE);
vh.showProgress.setIndeterminate(true);
vh.showHeader.setText(ctx.getString(R.string.refreshing));
} else {
vh.showProgress.setIndeterminate(false);
vh.showStatus.setVisibility(View.VISIBLE);
vh.showRating.setVisibility(View.VISIBLE);
vh.showSubHeader.setVisibility(View.VISIBLE);
int unf = ser.getUnfinished();
vh.showHeader.setText(ser.getOverview());
vh.showSubHeader.setText(String.format("%s %d",
ctx.getString(R.string.total_episodes), ser.getTotalEpisodes()));
vh.showRating.setText(String.format("%s %.2f",
ctx.getString(R.string.rating), ser.getRating()));
int progress = (int) (100f / ser.getTotalEpisodes() *
(ser.getTotalEpisodes() - unf));
vh.showProgress.setProgress(progress);
if (unf == 0) {
vh.showStatus.setText(ctx.getString(R.string.done_series));
} else if (unf == 1) {
vh.showStatus.setText(ctx.getString(R.string.one_more_episode));
} else {
vh.showStatus.setText(String.format("%d %s", unf, ctx.getString(R.string.left_episodes)));
}
}
return convertView;
}
// Methods
/*
private Drawable getImage(String name) {
Log.i("SA_v2:getImage", name);
try {
FileInputStream fis = new FileInputStream(new File(ctx.getFilesDir(), name));
Bitmap b = BitmapFactory.decodeStream(fis);
return new BitmapDrawable(Resources.getSystem(), b);
} catch (Exception e) {
Log.i("SA_v2.getImage:", e.getMessage());
e.printStackTrace();
}
return null;
}
*/
// Inner class
static private class ViewHolder {
public ImageView showImage;
public TextView showName;
public TextView showHeader;
public TextView showSubHeader;
public TextView showRating;
public ProgressBar showProgress;
public TextView showStatus;
}
}
|
import java.util.*;
public class MainMemory {
static int size = 16777216;
String[] data = new String[size];
public String[] read(int entry,int blocksize){
return Arrays.copyOfRange(data, entry, entry+blocksize);
}
public void write(int entry, String value){
data[entry] = value;
}
public String readone(int entry){
return data[entry];
}
}
|
package modul4.chapter2;
import java.util.Scanner;
public class Wochentag {
public static void main(String[] args) {
Wochentag wochentag = new Wochentag();
System.out.println("Type in a number from 1 to 7. The number will appear as a weekday.");
System.out.println(wochentag.übersetze());
}
public String übersetze() {
int number = new Scanner(System.in).nextInt();
switch (number) {
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 7:
return "Sunday";
default:
return "You didn't type a valid number";
}
}
}
|
/**
*
*/
package com.goodhealth.web.service.impl;
import com.goodhealth.web.dao.OrderItemRepository;
import com.goodhealth.web.service.OrderItemService;
import com.goodhealth.web.entity.OrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author 24663
* @date 2019年2月25日
* @Description
*/
@Service
public class OrderItemServiceImp implements OrderItemService {
@Autowired
private OrderItemRepository itemRepository;
/* (non-Javadoc)
* @see OrderItemService#saveItem()
*/
@Override
public void saveItem(OrderItem item) throws Exception {
itemRepository.save(item);
}
}
|
package com.controller;
import com.alibaba.fastjson.JSONObject;
import com.bean.IntervalPlan;
import com.mapper.IntervalPlanMapper;
import com.service.IntervalPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class IntervalPlanController {
@Autowired
IntervalPlanService intervalPlanService;
@Autowired
IntervalPlanMapper intervalPlanMapper;
@RequestMapping("/selectIntervalPlan")
@ResponseBody
public JSONObject selectIntervalPlan(IntervalPlan intervalPlan) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("intervalPlanList",intervalPlanService.getIntervalPlan(intervalPlan));
return jsonObject;
}
@RequestMapping("/insertIntervalPlan")
@ResponseBody
public JSONObject insertIntervalPlan(IntervalPlan intervalPlan) {
JSONObject jsonObject = new JSONObject();
Integer result = intervalPlanMapper.insert(intervalPlan);
if(result > 0 ){
jsonObject.put("info","插入成功!");
}else{
jsonObject.put("info","插入失败!");
}
return jsonObject;
}
@RequestMapping("/deleteIntervalPlan")
@ResponseBody
public JSONObject deleteIntervalPlan(IntervalPlan intervalPlan) {
JSONObject jsonObject = new JSONObject();
Integer result = intervalPlanMapper.delete(intervalPlan);
if(result > 0 ){
jsonObject.put("info","删除成功!");
}else{
jsonObject.put("info","删除失败!");
}
return jsonObject;
}
@RequestMapping("/updateIntervalPlan")
@ResponseBody
public JSONObject updateIntervalPlan(IntervalPlan intervalPlan) {
JSONObject jsonObject = new JSONObject();
Integer result = intervalPlanMapper.updateByPrimaryKeySelective(intervalPlan);
if(result > 0 ){
jsonObject.put("info","更新成功!");
}else{
jsonObject.put("info","更新失败!");
}
return jsonObject;
}
}
|
package www.chaayos.com.chaimonkbluetoothapp.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import www.chaayos.com.chaimonkbluetoothapp.R;
import www.chaayos.com.chaimonkbluetoothapp.adapters.SummaryCustomAdapter;
import www.chaayos.com.chaimonkbluetoothapp.db.DatabaseAdapter;
import www.chaayos.com.chaimonkbluetoothapp.domain.model.new_model.OrderItemsSummary;
public class OrderSummaryActivity extends AppCompatActivity {
private TextView totalOrders;
private TextView totalOrdersAmount;
private Button cancelButton;
private Button proceedButton;
private RecyclerView recyclerView;
protected SummaryCustomAdapter mAdapter;
private List<OrderItemsSummary> orderItemsSummaryList;
private int totalOrdersCount = 0;
private double totalAmountValue = 0.0;
private TextView subTotalAmount;
DatabaseAdapter databaseAdapter;
private double subTotalAmountValue = 0.0;
private Button closeButton;
private RelativeLayout cancelSubmitRv;
private boolean isCalledFromAdminPanelActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_summary);
orderItemsSummaryList = getIntent().getParcelableArrayListExtra("showOrderSummaryActivity");
totalOrdersCount = getIntent().getIntExtra("totalOrdersCount",-1);
totalAmountValue = getIntent().getDoubleExtra("totalAmountValue",-1.0);
subTotalAmountValue = getIntent().getDoubleExtra("subTotalAmount",-1.0);
isCalledFromAdminPanelActivity = getIntent().getBooleanExtra("ADMINPANEL",false);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width * 0.8),(int)(height * 0.8));
databaseAdapter = new DatabaseAdapter(OrderSummaryActivity.this);
totalOrders = (TextView) findViewById(R.id.totalOrders);
totalOrdersAmount = (TextView) findViewById(R.id.ordersTotalAmount);
subTotalAmount = (TextView) findViewById(R.id.subtotalAmount);
totalOrders.setText("Total Orders: " + String.valueOf(totalOrdersCount));
totalOrdersAmount.setText("TotalAmount : Rs " +String.valueOf(totalAmountValue));
subTotalAmount.setText("Rs " + subTotalAmountValue);
proceedButton = (Button) findViewById(R.id.proceedButton);
cancelButton = (Button) findViewById(R.id.cButton);
recyclerView = (RecyclerView) findViewById(R.id.ordersSummaryRv);
closeButton = (Button) findViewById(R.id.clButton);
cancelSubmitRv = (RelativeLayout) findViewById(R.id.cancelSubmitRv);
if(isCalledFromAdminPanelActivity){
showCloseButton();
}else {
closeButton.setVisibility(View.INVISIBLE);
}
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new SummaryCustomAdapter(orderItemsSummaryList,this);
recyclerView.setAdapter(mAdapter);
proceedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(OrderSummaryActivity.this,"Day close completed successfully",Toast.LENGTH_LONG).show();
Intent intent = new Intent(OrderSummaryActivity.this,LoginActivity.class);
startActivity(intent);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
private void showCloseButton(){
cancelSubmitRv.setVisibility(View.INVISIBLE);
closeButton.setVisibility(View.VISIBLE);
}
}
|
package com.tencent.mm.plugin.scanner.util;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.modelsimple.h;
class e$3 implements OnCancelListener {
final /* synthetic */ e mMX;
final /* synthetic */ h mMY;
e$3(e eVar, h hVar) {
this.mMX = eVar;
this.mMY = hVar;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(this.mMY);
if (this.mMX.mMU != null) {
this.mMX.mMU.o(1, null);
}
}
}
|
package nowcoder.剑指offer;
/**
* @Author: Mr.M
* @Date: 2019-03-07 10:42
* @Description: 二叉搜索树与双向链表
**/
public class T26 {
// public TreeNode Convert(TreeNode pRootOfTree) {
//
// }
}
|
package com.media2359.mediacorpspellinggame.game.typeA;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.media2359.mediacorpspellinggame.R;
import com.media2359.mediacorpspellinggame.data.Question;
import com.media2359.mediacorpspellinggame.data.Section;
import com.media2359.mediacorpspellinggame.factory.GameProgressManager;
import com.media2359.mediacorpspellinggame.game.GameActivity;
import com.media2359.mediacorpspellinggame.game.typeC.TypeCGameFragment;
import com.media2359.mediacorpspellinggame.game.typeE.TypeEGameFragment;
import com.media2359.mediacorpspellinggame.utils.CommonUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by xijunli on 17/2/17.
*/
public class TypeAWaitingFragment extends Fragment {
private static final String ARGS_QUESTION = "args_question";
private static final String ARGS_GAME_TYPE = "args_game_type";
@BindView(R.id.btnGo)
Button btnGo;
@BindView(R.id.tvInstruction)
TextView tvInstruction;
@BindView(R.id.tvCurrentScore)
TextView tvCurrentScore;
@BindView(R.id.tvQuestionCount)
TextView tvQuestionCount;
private Question question;
public static TypeAWaitingFragment newInstance(Question question, String gameType) {
Bundle args = new Bundle();
args.putParcelable(ARGS_QUESTION, question);
args.putString(ARGS_GAME_TYPE, gameType);
TypeAWaitingFragment fragment = new TypeAWaitingFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
question = getArguments().getParcelable(ARGS_QUESTION);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_game_waiting, container, false);
ButterKnife.bind(this, root);
return root;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bind();
}
private void bind() {
tvCurrentScore.setText(String.valueOf(GameProgressManager.getInstance().getTotalScore()));
int qid = GameProgressManager.getInstance().getLastAttemptedQuestionPos() + 1;
final Section game = ((GameActivity) getActivity()).getCurrentGame();
String questionCount = CommonUtils.getQuestionCountString(getActivity(), qid, game.getQuestionCount());
tvQuestionCount.setText(questionCount);
tvInstruction.setText(game.getQuestionInstruction());
btnGo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String gameType = getArguments().getString(ARGS_GAME_TYPE);
if (gameType == null || gameType.isEmpty() || gameType.equalsIgnoreCase("2")){
throw new IllegalArgumentException("Game Type is not supported");
}
// if (gameType.equalsIgnoreCase("1")) {
// ((GameActivity) getActivity()).replaceFragment(TypeAGameFragment.newInstance(question));
// } else if (gameType.equalsIgnoreCase("3") || gameType.equalsIgnoreCase("4")) {
// //((GameActivity) getActivity()).replaceFragment(TypeCGameFragment.newInstance(question));
// ((GameActivity) getActivity()).replaceFragment(TypeAGameFragment.newInstance(question));
// } else if (gameType.equalsIgnoreCase("5")) {
// ((GameActivity) getActivity()).replaceFragment(TypeEGameFragment.newInstance());
// }
if (gameType.equalsIgnoreCase("5")) {
((GameActivity) getActivity()).replaceFragment(TypeEGameFragment.newInstance());
} else {
((GameActivity) getActivity()).replaceFragment(TypeAGameFragment.newInstance(question));
}
}
});
}
}
|
package pl.finsys.formHashmap;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ContactController {
private static Map<String, String> contactMap = new HashMap<>();
static {
contactMap.put("name", "John");
contactMap.put("lastname", "Lennon");
contactMap.put("genres", "Rock, Pop");
}
@RequestMapping(value = "/show", method = RequestMethod.GET)
public ModelAndView get() {
ContactForm contactForm = new ContactForm();
contactForm.setContactMap(contactMap);
return new ModelAndView("addContact" , "contactForm", contactForm);
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute("contactForm") ContactForm contactForm) {
System.out.println(contactForm);
if(null != contactForm.getContactMap()) {
contactMap = contactForm.getContactMap();
System.out.println(contactMap);
System.out.println(contactMap.keySet());
}
return new ModelAndView("showContact", "contactForm", contactForm);
}
}
|
package com.tencent.mm.g.a;
import android.content.Context;
public final class ra$a {
public String cbP;
public Context context;
}
|
package com.jlgproject.util;
import okhttp3.MediaType;
/**
* @author 王锋 on 2017/5/3.
*/
public class ConstUtils {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static final String IOGIN_INFO="loginInfo";
public static final String HOME_INFO="homeInfo";
public static final String VIDEO_LISTS="videoInfo";
public static final String CHECKBOX_AGREEMENT="gouxuan";//勾选
public static final String CANCEL_AGREEMENT="quxiao";//取消
public static final String PD="pd";//确认
public static final String MY_PAGER="my_pager";
public static final String MONEY="money";//钱
public static final String OPEN_DEBT_MONEY="0.02";//
public static final String DEBT_BEIAN="0.01";//
public static final String ASSET_ID="assetId";//资产Id key
public static final String IS_OWER="isOwer";//资产Id key
public static final String ESC="esc";//退出表示
public static final String WEIXIN_ADDID="wxbc0753acdfa4e7c3";//微信AppID
public static final String USER_TYPE="userType";//
public static final String USER_PHONE="phone";//
public static final String HANG_TYPE="hangType";//
public static final String DYJH_ID="dyjh_id";//
public static final String YYB_SC="com.tencent.android.qqdownloader";//应用宝市场
public static final String HUAWEI_SC="com.huawei.appmarket";//华为市场
public static final String XIAOMI_SC="com.xiaomi.market";//小米市场
public static final String VIVO_SC="com.huawei.appmarket";//VIVO市场
public static final String OPPO_SC="com.huawei.appmarket";//OPPO市场
public static final int USER_1=1;//总行
public static final int USER_2=2;//省
public static final int USER_3=3;//市
public static final int USER_4=4;//债行(服务行)
public static final int USER_5=5;//拓展行
public static final int USER_6=6;//云债行
public static final int USER_7=7;//商学院
public static final int USER_8=8;//超级用户
public static final String[] Tab_Name = {
"未解决",
"已解决",
};
public static final String[] Tab_Zsr_Name = {
"债事企业",
"债事自然人",
};
public static final String[] Tab_wailt_Name={
"全部","收入","支出"
};
/**
* 正则:手机号(简单)
*/
public static final String REGEX_MOBILE_SIMPLE = "^[1]//d{10}$";
/**
* 正则:手机号(精确)
* <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p>
* <p>联通:130、131、132、145、155、156、175、176、185、186</p>
* <p>电信:133、153、173、177、180、181、189</p>
* <p>全球星:1349</p>
* <p>虚拟运营商:170</p>
*/
public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))//d{8}$";
/**
* 正则:电话号码
*/
public static final String REGEX_TEL = "^0//d{2,3}[- ]?//d{7,8}";
/**
* 正则:身份证号码18位
*/
public static final String REGEX_ID_CARD18 = "^[1-9]//d{5}[1-9]//d{3}((0//d)|(1[0-2]))(([0|1|2]//d)|3[0-1])//d{3}([0-9Xx])$";
/**
* 正则:邮箱
*/
public static final String REGEX_EMAIL = "^//w+([-+.]//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*$";
/**
* 正则:URL
*/
public static final String REGEX_URL = "[a-zA-z]+://[^//s]*";
/**
* 正则:汉字
*/
public static final String REGEX_ZH = "^[//u4e00-//u9fa5]+$";
/**
* 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-18位
*/
public static final String REGEX_USERNAME = "^[//w//u4e00-//u9fa5]{6,18}(?<!_)$";
/**
* 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年
*/
public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* 正则:QQ号
*/
public static final String REGEX_TENCENT_NUM = "[1-9][0-9]{4,}";
}
|
package com.zbj.multithread;
public class ThreadTest {
}
|
package com.fixit.factories;
import android.content.Context;
import com.fixit.config.AppConfig;
import com.fixit.rest.adapters.SynchronizationResultDeserializer;
import com.fixit.synchronization.SynchronizationResult;
import com.fixit.utils.DateUtils;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Credentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by Kostyantin on 12/19/2016.
*/
public class RetrofitFactory {
public static Retrofit createRetrofitClient(Context context, String baseUrl, String user, String password) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(createGeneralHttpClient(context, user, password))
.addConverterFactory(createGeneralGsonConverterFactory())
.build();
}
public static Retrofit createServerRetrofitClient(Context context, String url) {
return new Retrofit.Builder()
.baseUrl(url)
.client(createServerHttpClient(context))
.addConverterFactory(createServerGsonConverterFactory())
.build();
}
public static GsonConverterFactory createGeneralGsonConverterFactory() {
return GsonConverterFactory.create(
new GsonBuilder()
.setDateFormat(DateUtils.FORMAT_RFC_2822)
.create()
);
}
private static GsonConverterFactory createServerGsonConverterFactory() {
return GsonConverterFactory.create(
new GsonBuilder()
.setDateFormat(DateUtils.FORMAT_REST_DATE)
.registerTypeAdapter(SynchronizationResult.class, new SynchronizationResultDeserializer())
.create()
);
}
private static OkHttpClient createGeneralHttpClient(Context context, String user, String password) {
return initHttpClientBuilder(context)
.addInterceptor(new BasicAuthorizationInterceptor(user, password))
.build();
}
private static OkHttpClient createServerHttpClient(Context context) {
String apiKey = AppConfig.getString(context, AppConfig.KEY_API_KEY, "");
String userAgent = AppConfig.getString(context, AppConfig.KEY_USER_AGENT, "");
return initHttpClientBuilder(context)
.addInterceptor(new ServerAuthorizationInterceptor(userAgent, apiKey))
.build();
}
private static OkHttpClient.Builder initHttpClientBuilder(Context context) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(
AppConfig.getInteger(context, AppConfig.KEY_RETROFIT_C_TO, 30).longValue(),
TimeUnit.SECONDS
)
.readTimeout(
AppConfig.getInteger(context, AppConfig.KEY_RETROFIT_R_TO, 30).longValue(),
TimeUnit.SECONDS
)
.writeTimeout(
AppConfig.getInteger(context, AppConfig.KEY_RETROFIT_W_TO, 30).longValue(),
TimeUnit.SECONDS
);
if(!AppConfig.isProduction(context)) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(loggingInterceptor);
}
return builder;
}
private static class BasicAuthorizationInterceptor implements Interceptor {
private final String credentials;
BasicAuthorizationInterceptor(String userName, String password) {
this.credentials = Credentials.basic(userName, password);
}
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", credentials);
requestBuilder.method(original.method(),original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
}
private static class ServerAuthorizationInterceptor implements Interceptor {
private final String userAgent;
private final String apiKey;
ServerAuthorizationInterceptor(String userAgent, String apiKey) {
this.userAgent = userAgent;
this.apiKey = apiKey;
}
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request request = original.newBuilder()
.header("User-Agent", userAgent)
.header("X-Authorization", apiKey)
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
}
}
|
package com.example.estudiante.gps;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.location.Location;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private GPSDataContentProvider gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Ubicacion ub = new Ubicacion(this);
gps = new GPSDataContentProvider();
if(gps.onCreate()){
//Esta funcion es para enviarle los parametros de Carlos
//onLocationChanged(Location loc);
//Esto es sólo para efectos de prueba:
ContentValues values = new ContentValues();
values.put(GPSData.GPSPoint.LONGITUDE,"100");
values.put(GPSData.GPSPoint.LATITUDE,"200");
values.put(GPSData.GPSPoint.TIME,"300");
//esta funcion es para insertar
getContentResolver().insert(GPSDataContentProvider.CONTENT_URI, values);
//esta funcion es para consultar
Cursor c = gps.consultar();
if (c.moveToFirst()) {
do{
if(c.moveToFirst()){
float lat;
float longitud;
int time;
lat = c.getFloat(1);
longitud = c.getFloat(2);
time = c.getInt(3);
Toast.makeText(getApplicationContext(),"Esto es latitud:"+lat+"Esto es longitud:"+longitud+"Esto es time:"+time,Toast.LENGTH_SHORT).show();
}
} while (c.moveToNext());
}
}
}
public void onLocationChanged( final Location loc){
Thread th= new Thread() {
public void run()
{
ContentValues values = new ContentValues();
Double lon = loc.getLongitude();
Long time = loc.getTime();
values.put(GPSData.GPSPoint.LONGITUDE, loc.getLongitude());
values.put(GPSData.GPSPoint.LATITUDE, loc.getLatitude());
values.put(GPSData.GPSPoint.TIME, loc.getTime());
//AlarmManager chromtap
//string del GPS y luego cada 15 minutos se graba en el
{ try
{
while(true)
{
//Thread.sleep(15000);
Thread.sleep(5000);
{
//Toast.makeText(getApplicationContext(), "Latitude " + loc.getLatitude() + " et longitude " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
getContentResolver().insert(GPSDataContentProvider.CONTENT_URI, values);
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
};
th.start();
}
}
|
package com.wllfengshu.mysql.init;
import com.alibaba.fastjson.JSON;
import com.wllfengshu.mysql.common.Cache;
import com.wllfengshu.mysql.common.Constant;
import com.wllfengshu.mysql.exception.CustomException;
import com.wllfengshu.mysql.utils.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 系统初始化
*
* @author wangll
*/
@Order(1)
@Slf4j
@Component
@RequiredArgsConstructor
public class InitRunner implements CommandLineRunner {
@Override
public void run(String... args) {
log.info("正在初始化");
try {
cacheDbTableFrmMap();
}catch (Exception e){
log.error("初始化失败,程序退出", e);
System.exit(-1);
}
log.info("初始化完毕");
}
/**
* 把所有的表
*/
private void cacheDbTableFrmMap() throws CustomException {
log.info("正在缓存所有的表结构");
List<String> dbNames = FileUtils.readDirForDirName(Constant.DATA_PATH);
for (String dbName : dbNames){
List<String> tableNames = FileUtils.readDirForFileName(Constant.DATA_PATH + '/' + dbName, Constant.DATA_FILE_FRM);
for (String tableName : tableNames){
String tableContent = FileUtils.readFile(Constant.DATA_PATH + '/' + dbName + '/' + tableName + Constant.DATA_FILE_FRM);
Cache.DB_TABLE_FRM_MAP.put(dbName + '-' + tableName, tableContent);
}
}
log.info("表结构缓存完毕" + JSON.toJSONString(Cache.DB_TABLE_FRM_MAP));
}
}
|
package com.example.eldadzipori.atidaprovals;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.onesignal.OneSignal;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView messagesListView ;
ArrayList<aprovedMessage> items;
boolean isTeacher = false;
String grade ;
aprovedUser user ;
int limit = 5;
Button btnChangeCode;
ProgressDialog pd;
void Refresh(boolean b )
{
pd.show();
if(!isTeacher){
ParseQuery<aprovedMessage> query = new ParseQuery<aprovedMessage>(aprovedMessage.class);
query.whereEqualTo("Student", user);
query.orderByDescending("createdAt");
if(b) {
query.setLimit(limit);
}
query.findInBackground(new FindCallback<aprovedMessage>() {
@Override
public void done(List<aprovedMessage> list, ParseException e) {
items = (ArrayList)list;
messageAdapter adapter = new messageAdapter(MainActivity.this,0,items);
messagesListView.setAdapter(adapter);
pd.dismiss();
}
});
}
else {
isTeacher = true;
ParseQuery<aprovedMessage> query = new ParseQuery<aprovedMessage>(aprovedMessage.class);
query.whereEqualTo("Teacher", user);
query.orderByDescending("createdAt");
if(b){
query.setLimit(limit);
}
query.findInBackground(new FindCallback<aprovedMessage>() {
@Override
public void done(List<aprovedMessage> list, ParseException e) {
items = (ArrayList)list;
messageAdapter adapter = new messageAdapter(MainActivity.this,0,items);
messagesListView.setAdapter(adapter);
pd.dismiss();
}
});
}
}
@Override
public void onBackPressed() {
AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this,R.style.AppTheme_Dark_Dialog);
dialog.setTitle("Warning!!!");
dialog.setMessage("Are you sure you want to logout?");
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ParseUser.logOut();
finish();
}
});
dialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pd = new ProgressDialog(MainActivity.this,R.style.AppTheme_Dark_Dialog);
pd.setMessage("data is coming from server...");
pd.setIndeterminate(true);
btnChangeCode = (Button)findViewById(R.id.btnChangeCode);
messagesListView = (ListView)findViewById(R.id.lvMessages);
user = (aprovedUser) ParseUser.getCurrentUser();
try {
user.fetchIfNeeded();
grade = user.getGrade();
}
catch (Exception e)
{
}
OneSignal.idsAvailable(new OneSignal.IdsAvailableHandler() {
@Override
public void idsAvailable(String userId, String registrationId) {
user.put("oneSignalId",userId);
try{
user.save();
}
catch (Exception e){}
}
});
if(user.isTeacher()) {
ParsePush.subscribeInBackground(user.getString("FirstName")+user.getString("LastName"));
isTeacher = true;
messagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(MainActivity.this,AppvrovalActivity.class);
i.putExtra("name",items.get(position).getStudent().getFullName());
i.putExtra("message",items.get(position).getMessage());
i.putExtra("time",items.get(position).getTimeOfLeaving().toString());
i.putExtra("is",items.get(position).isAprroved());
i.putExtra("id",items.get(position).getObjectId());
startActivity(i);
}
});
}
else {
isTeacher = false;
btnChangeCode.setVisibility(View.INVISIBLE);
}
Refresh(true);
btnChangeCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Prompt();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
if(!isTeacher) {
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, SendMessageActivity.class));
}
});
}
else {
fab.hide();
}
}
void Prompt(){
LayoutInflater inflater = LayoutInflater.from(this);
View promptView = inflater.inflate(R.layout.eddittext_dialog_layout,null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this,R.style.AppTheme_Dark_Dialog);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptView);
final EditText userInput = (EditText) promptView
.findViewById(R.id.editTextDialogUserInput);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
// edit text
if (userInput.getText().length() == 5) {
userInput.setError(null);
if (aprovedCode.changeCodeForGrade(grade, userInput.getText().toString())) {
AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme_Dark_Dialog);
b.setTitle("Succses!!!");
b.setMessage("Code Was Changed Succsesfuly");
b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.dismiss();
b.show();
} else {
AlertDialog.Builder b = new AlertDialog.Builder(MainActivity.this, R.style.AppTheme_Dark_Dialog);
b.setTitle("Opps!!!");
b.setMessage("Something went wrong");
b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.dismiss();
b.show();
}
} else {
userInput.setError("only 5 charecters");
}
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setTitle("Change Grade Code");
// show it
alertDialog.show();
}
@Override
protected void onResume() {
super.onResume();
Refresh(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
ParseUser.getCurrentUser().logOut();
finish();
return true;
}
else if(id == R.id.action_limitFive)
{
limit = 5;
Refresh(true);
}
else if(id == R.id.action_limitOne){
limit = 1;
Refresh(true);
}
else if(id == R.id.action_Refresh){
Refresh(true);
}
else if(id == R.id.action_limitall){
Refresh(false);
}
return super.onOptionsItemSelected(item);
}
}
|
package br.usp.memoriavirtual.modelo.fachadas.remoto;
import java.util.List;
import br.usp.memoriavirtual.modelo.entidades.Autor;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
public interface EditarAutorRemote {
public List<Autor> listarAutores(String strDeBusca) throws ModeloException;
public void editarAutor(Autor autor) throws ModeloException;
public Autor getAutor(Long id) throws ModeloException;
}
|
package com.upu.zenka.broadcasttest.tools;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* Created by ThinkPad on 2018/12/28.
*/
public class Getip {
//获取IP地址
public static String getLocalIpStr(Context context){
WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo=wifiManager.getConnectionInfo();
return intToIpAddr(wifiInfo.getIpAddress());
}
private static String intToIpAddr(int ip){
return (ip & 0xFF)+"."
+ ((ip>>8)&0xFF) + "."
+ ((ip>>16)&0xFF) + "."
+ ((ip>>24)&0xFF);
}
public static String getHostIP() {
String hostIp = "127.0.0.0";
try {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (ia instanceof Inet6Address) {
continue;// skip ipv6
}
String ip = ia.getHostAddress();
if (!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
Log.i("yao", "SocketException");
e.printStackTrace();
}
return hostIp;
}
}
|
package ch01.ex01_15;
interface Lookup {
Object find(String name);
}
|
package com.company.ch13_HashTable;
import java.util.TreeMap;
public class HashTable<K, V> {
private final int[] capacity
={53,97,193,389,769,1543,3079,6151,12289,24593,
49157,98317,196613,393241,786433,1572869,3145739,6291469,
12582917,25165843,50331653,100663319,201326611,402653189,805306457,1610612741};
private static final int upperTol=10;
private static final int lowerTol=2;
private int capacityIndex=0;
private int M;
private int size;
private TreeMap<K, V>[] hashTable;
public HashTable() {
this.M = capacity[capacityIndex];
size = 0;
hashTable = new TreeMap[M];
for (int i = 0; i < M; i++) {
hashTable[i] = new TreeMap<>();
}
}
private int hash(K key) {
return (key.hashCode() & 0x7fffffff) % M;
}
public int getSize() {
return size;
}
public void add(K key, V value) {
TreeMap<K, V> map = hashTable[hash(key)];
if (map.containsKey(key))
map.put(key, value);
else {
map.put(key, value);
size++;
}
if(size>=upperTol*M&&capacityIndex+1<capacity.length){
capacityIndex++;
resize(capacity[capacityIndex]);
}
}
public V remove(K key) {
TreeMap<K, V> map = hashTable[hash(key)];
V res = null;
if (map.containsKey(key)) {
res = map.remove(key);
size--;
}
if(size<lowerTol*M&&capacityIndex-1>=0){
resize(capacity[capacityIndex]);
}
return res;
}
private void resize(int newM){
TreeMap<K,V>[] newHashTable=new TreeMap[newM];
for (int i = 0; i < newM; i++) {
newHashTable[i]=new TreeMap<>();
}
int oldM=M;
this.M=newM;
for (int i = 0; i < oldM; i++) {
TreeMap<K,V>map= hashTable[i];
for (K k : map.keySet()) {
newHashTable[hash(k)].put(k,map.get(k));
}
}
this.hashTable=newHashTable;
}
public void set(K key, V value) {
TreeMap<K, V> map = hashTable[hash(key)];
if (!map.containsKey(key))
throw new IllegalArgumentException(key + " doesn't exist!");
map.put(key, value);
}
public boolean contains(K key) {
return hashTable[hash(key)].containsKey(key);
}
public V get(K key){
return hashTable[hash(key)].get(key);
}
}
|
package com.cloudera.CachingTest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.security.NoSuchAlgorithmException;
import net.spy.memcached.MemcachedClient;
public class MemCache implements CacheService {
private MemcachedClient memcached;
public MemCache() throws IOException {
try {
this.memcached = new MemcachedClient(new InetSocketAddress("192.168.2.105", 11211));
} catch (IOException e) {
throw new IOException(e);
}
}
public boolean put(CachedObject object) {
memcached.set(object.getKey() + "-f", 3600, object.getFirstName());
memcached.set(object.getKey() + "-l", 3600, object.getLastName());
memcached.set(object.getKey() + "-a", 3600, object.getAge());
memcached.set(object.getKey() + "-e", 3600, object.getEmail());
memcached.set(object.getKey() + "-p", 3600, object.getPassword());
return true;
}
public CachedObject get(String email)
throws NoSuchAlgorithmException, UnsupportedEncodingException {
String key = Person.getKey(email);
String f = memcached.get(key + "-f").toString();
String l = memcached.get(key + "-l").toString();
int a = Integer.parseInt(memcached.get(key + "-a").toString());
String e = memcached.get(key + "-e").toString();
String p = memcached.get(key + "-p").toString();
CachedObject obj = new Person(f, l, a, e);
obj.setHashedPassword(p);
return obj;
}
}
|
package io.rudin.electricity.tariff.swiss.data;
import org.junit.Assert;
import org.junit.Test;
import io.rudin.electricity.tariff.swiss.data.holiday.SwissHolidayRepository;
import io.rudin.electricity.tariff.swiss.data.holiday.SwissHolidays;
public class SwissHolidayRepositoryTest {
@Test
public void testInstance(){
SwissHolidays holidays = SwissHolidayRepository.getInstance();
Assert.assertNotNull(holidays);
Assert.assertNotNull(holidays.getHolidays());
Assert.assertFalse(holidays.getHolidays().isEmpty());
}
}
|
package com.example.healthmanage.base;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.request.target.ViewTarget;
import com.example.healthmanage.R;
import com.example.healthmanage.bean.network.response.LoginResponse;
import com.example.healthmanage.ui.fragment.qualification.bean.DoctorInfo;
import com.example.healthmanage.utils.Utils;
import com.hdl.CrashExceptioner;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseIM;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.parfoismeng.slidebacklib.SlideBack;
import com.parfoismeng.slidebacklib.callback.SlideBackCallBack;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import org.jetbrains.annotations.NotNull;
import java.util.Iterator;
import java.util.List;
import static com.example.healthmanage.utils.Constants.HTAG;
public class BaseApplication extends Application implements Application.ActivityLifecycleCallbacks{
// 防止多次点击造成的页面一直返回
private static final int MIN_DELAY_TIME = 400; // 两次点击间隔不能少于400ms 往大调也可以
private static long lastClickTime;
//static 代码段可以防止内存泄露
static {
//设置全局的Header构建器
SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
@Override
public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.darker_gray);//全局设置主题颜色
return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header,默认是 贝塞尔雷达Header
}
});
//设置全局的Footer构建器
SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
@Override
public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
//指定为经典Footer,默认是 BallPulseFooter
return new ClassicsFooter(context).setDrawableSize(20);
}
});
}
private static Application sInstance;
//token
private static String token = "";
//用户信息
private static LoginResponse.DataBean.UserInfoBean userInfoBean;
public static String getToken() {
return token == null ? "token is null" : token;
}
public static void setToken(String token) {
BaseApplication.token = token;
}
private static String integrals;
public static String getIntegrals() {
return integrals;
}
public static void setIntegrals(String integrals) {
BaseApplication.integrals = integrals;
}
public static LoginResponse.DataBean.UserInfoBean getUserInfoBean() {
return userInfoBean;
}
public static void setUserInfoBean(LoginResponse.DataBean.UserInfoBean userInfoBean) {
BaseApplication.userInfoBean = userInfoBean;
}
@Override
public void onCreate() {
super.onCreate();
setApplication(this);
//LiveEventBus配置
LiveEventBus
.config()
.autoClear(true)
.lifecycleObserverAlwaysActive(true);
//glide报错缺失
ViewTarget.setTagId(R.id.glide_tag);
//奔溃页面
CrashExceptioner.init(this);
initHx();
// registerActivityLifecycleCallbacks(this);
}
private String getAppName(int pID) {
String processName = null;
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List l = am.getRunningAppProcesses();
Iterator i = l.iterator();
PackageManager pm = this.getPackageManager();
while (i.hasNext()) {
ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
try {
if (info.pid == pID) {
processName = info.processName;
return processName;
}
} catch (Exception e) {
// Log.d("Process", "Error>> :"+ e.toString());
}
}
return processName;
}
private void initHx() {
int pid = android.os.Process.myPid();
String processAppName = getAppName(pid);
// 如果APP启用了远程的service,此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次,加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行,如果查到的process name不是APP的process name就立即返回
if (processAppName == null ||!processAppName.equalsIgnoreCase(this.getPackageName())) {
Log.e("processAppName", "enter the service process!");
// 则此application::onCreate 是被service 调用的,直接返回
return;
}
EMOptions options = new EMOptions();
// 默认添加好友时,是不需要验证的,改成需要验证
options.setAcceptInvitationAlways(false);
// 是否自动将消息附件上传到环信服务器,默认为True是使用环信服务器上传下载,如果设为 false,需要开发者自己处理附件消息的上传和下载
options.setAutoTransferMessageAttachments(true);
// 是否自动下载附件类消息的缩略图等,默认为 true 这里和上边这个参数相关联
options.setAutoDownloadThumbnail(true);
//设置是否删除会议室信息
options.setDeleteMessagesAsExitChatRoom(false);
//初始化
if (EaseIM.getInstance().init(this,options)){
//在做打包混淆时,关闭debug模式,避免消耗不必要的资源
EMClient.getInstance().setDebugMode(true);
}
}
/**
* 当主工程没有继承BaseApplication时,可以使用setApplication方法初始化BaseApplication
*
* @param application
*/
public static synchronized void setApplication(@NonNull Application application) {
sInstance = application;
//初始化工具类
Utils.init(application);
//注册监听每个activity的生命周期,便于堆栈式管理
application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
AppManager.getAppManager().addActivity(activity);
Log.d(HTAG, "onActivityCreated==========>: " + activity.getClass().getSimpleName());
}
@Override
public void onActivityStarted(Activity activity) {
Log.d(HTAG, "onActivityStarted==========>: " + activity.getClass().getSimpleName());
}
@Override
public void onActivityResumed(Activity activity) {
Log.d(HTAG, "onActivityResumed==========>: " + activity.getClass().getSimpleName());
}
@Override
public void onActivityPaused(Activity activity) {
Log.d(HTAG, "onActivityPaused==========>: " + activity.getClass().getSimpleName());
}
@Override
public void onActivityStopped(Activity activity) {
Log.d(HTAG, "onActivityStopped==========>: " + activity.getClass().getSimpleName());
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.d(HTAG, "onActivitySaveInstanceState==========>: " + activity.getClass().getSimpleName());
}
@Override
public void onActivityDestroyed(Activity activity) {
AppManager.getAppManager().removeActivity(activity);
Log.d(HTAG, "onActivityDestroyed==========>: " + activity.getClass().getSimpleName());
}
});
}
/**
* 获得当前app运行的Application
*/
public static Application getInstance() {
if (sInstance == null) {
throw new NullPointerException("please inherit BaseApplication or call setApplication.");
}
return sInstance;
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
// 在需要滑动返回的Activity中注册,最好但非必须在onCreate中
SlideBack.with(activity)
.haveScroll(true)
.edgeMode(SlideBack.EDGE_LEFT)
.callBack(new SlideBackCallBack() {
@Override
public void onSlideBack() {
activity.finish();
}
})
.register();
}
@Override
public void onActivityStarted(@NonNull @NotNull Activity activity) {
}
@Override
public void onActivityResumed(@NonNull @NotNull Activity activity) {
}
@Override
public void onActivityPaused(@NonNull @NotNull Activity activity) {
}
@Override
public void onActivityStopped(@NonNull @NotNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull @NotNull Activity activity, @NonNull @NotNull Bundle outState) {
}
@Override
public void onActivityDestroyed(@NonNull @NotNull Activity activity) {
SlideBack.unregister(activity);
}
public static boolean isFastClick() { //这个方法可以放到公共类里
boolean flag = true;
long currentClickTime = System.currentTimeMillis();
if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
flag = false;
}
lastClickTime = currentClickTime;
return flag;
}
}
|
package com.github.mikephil.klinelib.model;
/**
* Desc: 深度图数据
* Author ltt
* Email: litt@mixotc.com
* Date: 2018/6/12.
*/
public class DepthMapData {
private double price;//收盘价
private long vol;//数量
private long date;//时间
private int type;//类型:0买;1卖
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public long getVol() {
return vol;
}
public void setVol(long vol) {
this.vol = vol;
}
public long getDate() {
return date;
}
public void setDate(long date) {
this.date = date;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "DepthMapData{" +
"price=" + price +
", vol=" + vol +
", date=" + date +
", type=" + type +
'}';
}
}
|
package com.miaosha.demo.controller;
import com.miaosha.demo.error.BusinessException;
import com.miaosha.demo.error.EmBusinessError;
import com.miaosha.demo.response.CommonReturnType;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @Classname BaseController
* @Description 公共的功能设计到基类中
*
* @Date 2019/10/21 19:56
* @Author gt
*/
public class BaseController {
public final static String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";
// 定义exception handler解决为被controller层吸收的异常. (符合spring钩子类定义的设计思想)
// 业务逻辑的错误, 并不是服务器端不能处理
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.OK)
public Object handlerException(HttpServletRequest request, Exception ex) {
/*
version-1, 返回很多无用的信息,不优雅
final CommonReturnType commonReturnType = new CommonReturnType();
commonReturnType.setStatus("fail");
commonReturnType.setData(ex);
return commonReturnType;
*/
/*
version-2
BusinessException businessException = (BusinessException)ex;
final CommonReturnType commonReturnType = new CommonReturnType();
commonReturnType.setStatus("fail");
final Map<String, Object> responseData = new HashMap<>();
responseData.put("errCode", businessException.getErrCode());
responseData.put("errMsg", businessException.getErrMsg());
commonReturnType.setData(responseData);
return commonReturnType;*/
// version-3 : 重构一下代码,美化
final Map<String, Object> responseData = new HashMap<>();
if (ex instanceof BusinessException) {
BusinessException businessException = (BusinessException)ex;
responseData.put("errCode", businessException.getErrCode());
responseData.put("errMsg", businessException.getErrMsg());
} else {
responseData.put("errCode", EmBusinessError.UNKNOWN_ERROR.getErrCode());
responseData.put("errMsg", EmBusinessError.UNKNOWN_ERROR.getErrMsg());
}
return CommonReturnType.create(responseData, "fail");
}
}
|
package com.salespipeline.service.validator;
import static com.salespipeline.domain.Person.verify;
import com.salespipeline.domain.Person;
import com.salespipeline.integration.registryIdentification.response.VerifyPersonResponse;
import org.springframework.stereotype.Component;
@Component
public class MatchInformationComponent {
public boolean match(final VerifyPersonResponse verifyPersonResponse, final Person person) {
return verify(verifyPersonResponse, person);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.