text
stringlengths 10
2.72M
|
|---|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package loc.dto;
/**
*
* @author hi
*/
public class ProductDTO {
public String productID, name, image, categoryID;
private double price;
private int quantity;
private String description;
private String createDate;
private String expireDate;
private String updateDate;
private String status;
public ProductDTO() {
}
public ProductDTO(String productID, String name, String image, String categoryID, double price, int quantity, String description, String createDate, String expireDate, String updateDate, String status) {
this.productID = productID;
this.name = name;
this.image = image;
this.categoryID = categoryID;
this.price = price;
this.quantity = quantity;
this.description = description;
this.createDate = createDate;
this.expireDate = expireDate;
this.updateDate = updateDate;
this.status = status;
}
public ProductDTO(String productID, String name, String image, String categoryID, double price, int quantity, String description, String createDate, String expireDate, String status) {
this.productID = productID;
this.name = name;
this.image = image;
this.categoryID = categoryID;
this.price = price;
this.quantity = quantity;
this.description = description;
this.createDate = createDate;
this.expireDate = expireDate;
this.status = status;
}
public ProductDTO(String productID, String name, String image, String categoryID, double price, int quantity) {
this.productID = productID;
this.name = name;
this.image = image;
this.categoryID = categoryID;
this.price = price;
this.quantity = quantity;
}
public ProductDTO(String productID, String name, String image, String categoryID, double price, int quantity, String createDate, String expireDate) {
this.productID = productID;
this.name = name;
this.image = image;
this.categoryID = categoryID;
this.price = price;
this.quantity = quantity;
this.createDate = createDate;
this.expireDate = expireDate;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getProductID() {
return productID;
}
public void setProductID(String productID) {
this.productID = productID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategoryID() {
return categoryID;
}
public void setCategoryID(String categoryID) {
this.categoryID = categoryID;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getExpireDate() {
return expireDate;
}
public void setExpireDate(String expireDate) {
this.expireDate = expireDate;
}
public String getUpdateDate() {
return updateDate;
}
public void setUpdateDate(String updateDate) {
this.updateDate = updateDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package com.example.DesInterSpring.dto;
import javax.validation.constraints.NotBlank;
public class LoginUsuario {
@NotBlank
private String nombre;
@NotBlank
private String password;
public String getNombre() {
return nombre;
}
public void setNombre(String nombreUsuario) {
this.nombre = nombreUsuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package com.pds.rn.rectactivity;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.facebook.react.ReactActivityDelegate;
import javax.annotation.Nullable;
public class RnActivityDelegate extends ReactActivityDelegate {
private Bundle bundle;
public RnActivityDelegate(Activity activity, @Nullable String mainComponentName) {
super(activity, mainComponentName);
}
public RnActivityDelegate(FragmentActivity fragmentActivity,
@Nullable String mainComponentName) {
super(fragmentActivity, mainComponentName);
}
@Nullable
@Override
protected Bundle getLaunchOptions() {
return bundle;
}
public void setLaunchOptions(Bundle bundle) {
this.bundle = bundle;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}
|
package com.example.administrator.halachavtech.Model.Hazmana;
/**
* Created by Administrator on 11/01/2017.
*/
public class Status {
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Status(String description) {
this.description = description;
}
public Status() {
}
@Override
public String toString() {
return "Status{" +
"description='" + description + '\'' +
'}';
}
}
|
package ru.startandroid.places.events;
public class Event {
private int type;
public int getType() {
return type;
}
void setType(int type) {
this.type = type;
}
}
|
import java.util.Scanner;
public class CharacterCounter {
public static void main(String[] args) {
System.out.println("\nEnter size of your list: ");
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt();
char[] list = new char[size];
for (int k = 0; k < list.length; ++k) {
System.out.println("\nEnter a name for the position # " + k + " :");
list[k] = keyboard.next().charAt(0);
}
System.out.println("\nEnter your search query: ");
char input = keyboard.next().charAt(0);
System.out.println("");
int times = isMembers(list, input, size);
System.out.println("The characters is in the list " + times);
}
public static int isMembers(char[] list, char input, int size) {
int temp = 0;
if (isMembers(list, input, size - 1) <= temp) {
if (input == list[size] && size <= list.length) {
System.out.println("Input found at position " + size);
System.out.println("Program terminated. ");
temp++;
}
return temp;
}
return temp;
}
}
|
package cn.zhaoliang5156.monthmoni.mvp.mainmvp;
import java.util.List;
import cn.zhaoliang5156.monthmoni.base.net.HttpCallback;
import cn.zhaoliang5156.monthmoni.bean.Category;
import cn.zhaoliang5156.monthmoni.bean.RightResponse;
/**
* Copyright (C), 2015-2019, 八维集团
* Author: zhaoliang
* Date: 2019/4/30 10:39 AM
* Description: 首页分类的契约接口
*/
public interface MainContract {
/*
V:
P:
M:
*/
interface IMainView {
void showLeft(List<Category> categoryList);
void showRight(List<RightResponse> rightResponse);
}
interface IMainModel {
void loadData(String url, HttpCallback callback);
}
interface IMainPresetner {
void attach(IMainView view);
void detach();
void requestLeftData(String url);
void requestRightData(String url);
}
}
|
package com.tencent.mm.plugin.appbrand;
import android.content.Context;
class u$1 implements Runnable {
final /* synthetic */ String dhF;
final /* synthetic */ int fen;
final /* synthetic */ u feo;
final /* synthetic */ Context val$context;
u$1(u uVar, Context context, String str, int i) {
this.feo = uVar;
this.val$context = context;
this.dhF = str;
this.fen = i;
}
public final void run() {
m.f(this.val$context, this.dhF, this.fen);
}
}
|
package ro.redeul.google.go.lang.parser.parsing.statements;
import com.intellij.lang.PsiBuilder;
import ro.redeul.google.go.lang.lexer.GoElementType;
import ro.redeul.google.go.lang.parser.GoElementTypes;
import ro.redeul.google.go.lang.parser.GoParser;
import ro.redeul.google.go.lang.parser.parsing.util.ParserUtils;
public class ForStatement implements GoElementTypes {
public static boolean parse(PsiBuilder builder, GoParser parser) {
PsiBuilder.Marker marker = builder.mark();
if (!ParserUtils.getToken(builder, kFOR)) {
marker.rollbackTo();
return false;
}
ParserUtils.skipNLS(builder);
GoElementType forType = FOR_WITH_CONDITION_STATEMENT;
if ( builder.getTokenType() != pLCURCLY ) {
forType = parseConditionOrForClauseOrRangeClause(builder, parser);
}
parser.parseBody(builder);
marker.done(forType);
return true;
}
private static GoElementType parseConditionOrForClauseOrRangeClause(
PsiBuilder builder, GoParser parser)
{
PsiBuilder.Marker clause = builder.mark();
parser.parseExpression(builder, true);
if ( pLCURCLY == builder.getTokenType() ) {
clause.drop();
return FOR_WITH_CONDITION_STATEMENT;
}
clause.rollbackTo();
if ( tryParseRangeClause(builder, parser) ) {
return FOR_WITH_RANGE_STATEMENT;
}
parser.parseStatementSimple(builder, true);
ParserUtils.getToken(builder, oSEMI, "semicolon.expected");
ParserUtils.skipNLS(builder);
parser.parseExpression(builder, true);
ParserUtils.getToken(builder, oSEMI, "semicolon.expected");
ParserUtils.skipNLS(builder);
parser.parseStatementSimple(builder, true);
return FOR_WITH_CLAUSES_STATEMENT;
}
private static boolean tryParseRangeClause(PsiBuilder builder, GoParser parser) {
PsiBuilder.Marker m = builder.mark();
parser.parseExpressionList(builder, true);
if ( builder.getTokenType() == oVAR_ASSIGN || builder.getTokenType() == oASSIGN ) {
ParserUtils.advance(builder);
ParserUtils.skipNLS(builder);
if ( builder.getTokenType() == kRANGE ) {
ParserUtils.getToken(builder, kRANGE);
parser.parseExpression(builder, true);
m.drop();
return true;
}
}
m.rollbackTo();
return false;
}
}
|
package fr.windea.tuto.controller;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import fr.windea.tuto.R;
import fr.windea.tuto.model.User;
public class MainActivity extends AppCompatActivity {
private static final int GAME_ACTIVITY_REQUEST_CODE = 1;
private static final String GAME_ACTIVITY_USER_USERNAME = "username";
private static final String GAME_ACTIVITY_USER_SCORE = "score";
private TextView mGreetingText;
private EditText mNameInput;
private Button mPlayButton;
private User mUser;
private SharedPreferences mPreferences;
private int mScore;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (GAME_ACTIVITY_REQUEST_CODE == requestCode && RESULT_OK == resultCode) {
mScore = data.getIntExtra(GameActivity.BUNDLE_EXTRA_SCORE, 0);
mPreferences.edit().putInt(GAME_ACTIVITY_USER_SCORE, mScore).apply();
greetUser();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUser = new User();
mPreferences = getPreferences(MODE_PRIVATE);
mGreetingText = findViewById(R.id.activity_main_greeting_txt);
mNameInput = findViewById(R.id.activity_main_name_input);
mPlayButton = findViewById(R.id.activity_main_play_btn);
mPlayButton.setEnabled(false);
greetUser();
mNameInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int count, int after) {
mPlayButton.setEnabled(s.toString().length() != 0);
}
@Override
public void afterTextChanged(Editable s) {
}
});
mPlayButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mUser.setFirstName(mNameInput.getText().toString());
mPreferences.edit().putString(GAME_ACTIVITY_USER_USERNAME, mUser.getFirstName()).apply();
Intent gameActivityIntent = new Intent(MainActivity.this, GameActivity.class);
startActivityForResult(gameActivityIntent, GAME_ACTIVITY_REQUEST_CODE);
}
});
}
protected void greetUser() {
String firstname = mPreferences.getString(GAME_ACTIVITY_USER_USERNAME, null);
if (firstname != null) {
mScore = mPreferences.getInt(GAME_ACTIVITY_USER_SCORE, 0);
mGreetingText.setText("Re, " + firstname + ". Ton dernier score est de " + mScore + ", tu reviens pour grind le ladder du discord ?");
mNameInput.setText(firstname);
mNameInput.setSelection(firstname.length());
mPlayButton.setEnabled(true);
}
}
}
|
package cwiczenie;
public class PowEquation implements ICalculable {
private double liczba1;
private double liczba2;
public PowEquation(double liczba1, double liczba2) {
this.liczba1 = liczba1;
this.liczba2 = liczba2;
}
public double calculate(){
double potega = Math.pow(liczba1, liczba2);
return potega;
}
}
|
public class PrintFormatDemo { //%s and %.2f and print f
public static void main(String[] args) {
String value = "Maria";
double salary = 256.00;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.printf("Enter how many hours did %s work?", value);
int hours = input.nextInt();
double hourlyRate = salary / hours;
System.out.printf("%-s's hourly rate is %.2f", value, hourlyRate); //the negative creates a space
}
}
|
package com.project.linkedindatabase.jsonToPojo;
import com.project.linkedindatabase.domain.chat.Chat;
import com.project.linkedindatabase.domain.chat.Message;
import com.project.linkedindatabase.utils.DateConverter;
import lombok.*;
import java.util.ArrayList;
import java.util.List;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ChatJson {
private Long id;
private Boolean isArchive;
private Boolean markUnread;
private Long myProfileId;// foreign key to profile table.
private ProfileJson myProfile;
private Long otherProfileId;// foreign key to profile table.
private ProfileJson otherProfile;
private List<MessageJson> messageJsons = new ArrayList<>();
public static ChatJson convertToJson(Chat chat)
{
ChatJson chatJson = new ChatJson();
chatJson.setId(chat.getId());
chatJson.setIsArchive(chat.getIsArchive());
chatJson.setMarkUnread(chat.getMarkUnread());
chatJson.setMyProfileId(chat.getProfileId1());
chatJson.setOtherProfileId(chat.getProfileId2());
return chatJson;
}
public Chat convertToMessage()
{
Chat chat = new Chat();
chat.setId(getId());
chat.setIsArchive(getIsArchive());
chat.setMarkUnread(getMarkUnread());
chat.setProfileId1(getMyProfileId());
chat.setProfileId2(getOtherProfileId());
return chat;
}
}
|
package com.arkaces.aces_marketplace_api;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "email")
public class EmailSettings {
private String fromName;
private String fromEmailAddress;
}
|
package questoes;
import questoes.*;
public class TestJogador {
public static void main(String[] args) {
Jogador j1 = new Jogador(100, 1, 400);
Jogador j2 = new Jogador(200, 2, 800);
j1.atacar(j2);
j2.atacar(j1);
System.out.println("pontos Jogador 1: " + j1.pontosAtuais);
System.out.println("pontos Jogador 2: " + j2.pontosAtuais);
}
}
|
package org.a55889966.bleach.saran.tourguide;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import android.text.TextUtils;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.GeofencingEvent;
import java.util.ArrayList;
import java.util.List;
public class GeofencePendingIntentService extends IntentService {
// Entered : BDBL, Basundhara Shopping Complex
public GeofencePendingIntentService() {
super("GeofencePendingIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent event = GeofencingEvent.fromIntent(intent);
int transitionType = event.getGeofenceTransition();
List<Geofence> triggeringGeofences = event.getTriggeringGeofences();
String transitionString = "";
switch (transitionType){
case Geofence.GEOFENCE_TRANSITION_ENTER:
transitionString = "Entered";
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
transitionString = "Exited";
}
ArrayList<String>triggeringGeofenceIDs = new ArrayList<>();
for(Geofence g : triggeringGeofences){
triggeringGeofenceIDs.add(g.getRequestId());
}
String notificationString = transitionString+" : "+ TextUtils.join(", ",triggeringGeofenceIDs);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String id = "org.a55889966.bleach.saran.tourguide.888.000.###";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The user-visible name of the channel.
CharSequence name = "Product";
// The user-visible description of the channel.
String description = "Notifications regarding our products";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = null;
mChannel = new NotificationChannel(id, name,importance);
// Configure the notification channel.
mChannel.setDescription(description);
mChannel.enableLights(true);
// Sets the notification light color for notifications posted to this
// channel, if the device supports this feature.
mChannel.setLightColor(Color.RED);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,id)
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Happy Travelling!")
.setContentText(notificationString)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_MAX);
notificationManager.notify(919,builder.build());
}
}
|
package com.tencent.mm.plugin.account.model;
import android.os.Bundle;
import android.os.Message;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.f.a.a$a;
import com.tencent.mm.ui.f.a.d;
import com.tencent.mm.ui.f.a.e;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
class g$2 implements a$a {
final /* synthetic */ g eOc;
g$2(g gVar) {
this.eOc = gVar;
}
public final void pF(String str) {
if (str == null || str.length() == 0) {
x.e("MicroMsg.RefreshTokenRunner", "response is null or nil");
g.a(this.eOc, 1, "response is null or nil");
} else if (!str.contains("access_token") || str.length() <= 12) {
try {
e.aaX(str);
} catch (Throwable e) {
x.e("MicroMsg.RefreshTokenRunner", "parseJson exception : " + e.getMessage());
x.printErrStackTrace("MicroMsg.RefreshTokenRunner", e, "", new Object[0]);
} catch (d e2) {
String str2 = "errCode = " + e2.mErrorCode + ", errType = " + e2.utw + ", errMsg = " + e2.getMessage();
x.e("MicroMsg.RefreshTokenRunner", "parseJson facebookerror, " + str2);
x.printErrStackTrace("MicroMsg.RefreshTokenRunner", e2, "", new Object[0]);
g.a(this.eOc, 3, str2);
return;
}
g.a(this.eOc, 2, "parseJson error");
} else {
try {
JSONObject aaX = e.aaX(str);
if (aaX.has("access_token")) {
Bundle bundle = new Bundle();
Iterator keys = aaX.keys();
while (keys.hasNext()) {
String str3 = (String) keys.next();
JSONArray optJSONArray = aaX.optJSONArray(str3);
Double valueOf = Double.valueOf(aaX.optDouble(str3));
String optString = aaX.optString(str3);
if (optJSONArray == null || optJSONArray.length() > 0) {
int i;
if (optJSONArray != null) {
if (!Double.isNaN(optJSONArray.optDouble(0))) {
double[] dArr = new double[optJSONArray.length()];
for (i = 0; i < optJSONArray.length(); i++) {
dArr[i] = optJSONArray.optDouble(i);
}
bundle.putDoubleArray(str3, dArr);
}
}
if (optJSONArray != null && optJSONArray.optString(0) != null) {
String[] strArr = new String[optJSONArray.length()];
for (i = 0; i < optJSONArray.length(); i++) {
strArr[i] = optJSONArray.optString(i);
}
bundle.putStringArray(str3, strArr);
} else if (!valueOf.isNaN()) {
bundle.putDouble(str3, valueOf.doubleValue());
} else if (optString != null) {
bundle.putString(str3, optString);
} else {
System.err.println("unable to transform json to bundle " + str3);
}
} else {
bundle.putStringArray(str3, new String[0]);
}
}
g gVar = this.eOc;
Message obtain = Message.obtain();
obtain.what = 2;
obtain.setData(bundle);
gVar.handler.sendMessage(obtain);
return;
}
} catch (Throwable e3) {
x.printErrStackTrace("MicroMsg.RefreshTokenRunner", e3, "", new Object[0]);
}
g.a(this.eOc, 2, "decodeUrl fail");
}
}
public final void b(IOException iOException) {
x.e("MicroMsg.RefreshTokenRunner", "onIOException");
g.a(this.eOc, 2, iOException.getMessage());
}
public final void a(FileNotFoundException fileNotFoundException) {
x.e("MicroMsg.RefreshTokenRunner", "onFileNotFoundException");
g.a(this.eOc, 2, fileNotFoundException.getMessage());
}
public final void a(MalformedURLException malformedURLException) {
x.e("MicroMsg.RefreshTokenRunner", "onMalformedURLException");
g.a(this.eOc, 2, malformedURLException.getMessage());
}
}
|
package com.accp.controller;
public class CyfController {
}
|
///////////////////////////////////////////////////////////////////////////////
// ALL STUDENTS COMPLETE THESE SECTIONS
// Main Class File: AppStore.java
// Files: User.java
// Semester: (course) Fall 2015
//
// Author: Xiaojun He
// Email: xhe66@wisc.edu
// CS Login: xiaojun
// Lecturer's Name: Jim Skrentny
///////////////////////////////////////////////////////////////////////////////
import java.util.*;
/**
* Stores all the information of a certain user and related apps
*
* @author Xiaojun He
*
*/
public class User {
private String email;
private String password;
private String firstName;
private String lastName;
private String country;
private String type;
private List<App> dlapps = new ArrayList<App>();
private List<App> ulapps = new ArrayList<App>();
/**
* Construct a object of user
*
* @param email
* @param password
* @param firstName
* @param lastName
* @param country
* @param type
* developer or user
* @throws IllegalArgumentException
* throw exception when object is not valid
*/
public User(String email, String password, String firstName,
String lastName, String country, String type)
throws IllegalArgumentException {
if (email == null || password == null || firstName == null
|| lastName == null || country == null
|| !(type.equals("user") || type.equals("developer")))
throw new IllegalArgumentException();
this.email = email;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.country = country;
this.type = type;
}
/**
* get user's email
*
* @return email address
*/
public String getEmail() {
return this.email;
}
/**
* Verify password user put in
*
* @param testPassword
* the password user input
* @return true if password is right, false if the password is wrong
*/
public boolean verifyPassword(String testPassword) {
if (testPassword == null)
throw new IllegalArgumentException();
return (testPassword.equals(this.password));
}
/**
* get user's first name
*
* @return user's first name
*/
public String getFirstName() {
return this.firstName;
}
/**
* get user's last name
*
* @return user's last name
*/
public String getLastName() {
return this.lastName;
}
/**
* get user's country
*
* @return country
*/
public String getCountry() {
return this.country;
}
/**
* check if user is developer
*
* @return true if user is developer, false if not
*/
public boolean isDeveloper() {
return this.type.equals("developer");
}
/**
* promote user as developer
*/
public void subscribeAsDeveloper() {
this.type = "developer";
}
/**
* add certain app to user's download list
*
* @param app
*/
public void download(App app) {
if (app == null)
throw new IllegalArgumentException();
dlapps.add(app);
}
/**
* add certain app to user's uploadd list
*
* @param app
*/
public void upload(App app) {
if (app == null)
throw new IllegalArgumentException();
ulapps.add(app);
}
/**
* get all downloaded apps of user
*
* @return list of downloaded apps
*/
public List<App> getAllDownloadedApps() {
return dlapps;
}
/**
* get all uploaded apps of user
*
* @return list of uploaded apps
*/
public List<App> getAllUploadedApps() {
return ulapps;
}
}
|
package com.devs4j.Rest.Services;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.swing.DefaultRowSorter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import com.devs4j.Rest.Model.User;
import com.github.javafaker.Faker;
@Service
public class UserServices {
@Autowired
private Faker faker;
private List<User> users = new ArrayList<User>();
public Faker getFaker() {
return faker;
}
public void setFaker(Faker faker) {
this.faker = faker;
}
@PostConstruct
public void init() {
for(int i=0; i<100; i++) {
users.add(new User(faker.funnyName().name(),faker.name().name(),faker.dragonBall().character()));
}
}
@Cacheable("users") // para guadra en caheche la respuest, la confifuracipon esta en la clase CacheConfig
public User getUserByUserName(String nameUser){
try {//se simula una respuest tardada
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
// la primera vez se tardará el tiempo original
//pero despues solo regresará lo que ya tiene en cahce y en realidas ya no se ejecuta el metodo
//y la respuesta es más rapida
return users.stream().filter(x -> x.getUser().equals(nameUser))
.findAny().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND,String.format("User %s not fount ",nameUser)));
}
public List<User> getUsersByUserNameRequestParam(String nameUser) {
if(nameUser != null) {
return users.stream().filter(u -> u.getUser().startsWith(nameUser)).collect(Collectors.toList());
}else {
return users;
}
}
public User createUser(User user) {
if(users.stream().anyMatch(x -> x.getUser().equals(user.getUser()))) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND,String.format("User %s not fout", user.getUser()));
}
users.add(user);
//User user = repository.save(user) // esto se suele usar si se le crea un Id al usuario, pero no es est eel caso
return user;
}
public User updateUser(String nameUser,User user) {
User userByUserName = getUserByUserName(nameUser);
userByUserName.setNickName(user.getNickName());
userByUserName.setPassword(user.getPassword());
return userByUserName;
}
public void deleteUser(String nameUser) {
User userByUserName = getUserByUserName(nameUser);
users.remove(userByUserName);
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
|
package com.chuxin.family.net;
/**
* 服务端返回的值
* @author shichao.wang
*
*/
public class CxNetworkResult {
public final static int NET_SUCCESS = 0; //成功:客户端根据API规则解析应答数据;
public final static int NET_SUCCESS_ADDITION = 1; //成功:但有附加信息;客户端根据API规则解析应答数据;msg字段包含信息内容(文本或URL)
public final static int NET_FAIL_BY_MAINTENANCE = 2; //失败:因运维操作而导致的访问失败;msg字段包含信息内容(文本或URL)
public final static int NET_FAIL_BY_LOW_VERSION = 3; //失败:客户端版本不能满足服务器要求;
public final static int NET_FAIL_BY_LONGPOLLING = 4; //失败;超时导致的失败(用于长轮训)
public final static int NET_FAIL_BY_NEED_REGISTE = 999; //未注册账号(目前在登录时会发生)
public final static int NET_FAIL_BY_UNLOGIN = 1000; //用户未登录:业务要求用户登录
public final static int NET_FAIL_BY_ILLEGAL_STATE = 2000; //用户输入不合法:服务器API应答失败,用户输入不合法,msg包含解析;
public final static int NET_FAIL_BY_RPC = 3000; //服务器异常:后台RPC服务器失败
public final static int NET_FAIL_BY_OTHER = -1; //其他原因导致的失败
}
|
package com.example.shoaib.movein;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import static android.support.v4.app.ActivityCompat.startActivity;
public class MyView extends View {
int counter=0;
Paint paint1,paint2,paint3,paint4,paint5,paint6,paint7;
// Path path;
float sourcex;
float sourcey;
float destx;
float desty;
int nodeKhy2X=500;
int nodeControlX=500;
int nodeKhy1X=500;
int nodeNasconX=500;
int nodeFaculty1X=500;
int nodeFaculty2X=500;
int nodeFaculty3X=500;
int nodeRawalX=500;
int nodeLadiesRoomX=700;
int nodeMensRoomX=700;
int node201X=700;
int node202X=700;
int node203X=700;
int nodeExamRoomX=700;
int nodeAcademicsX=700;
int nodeFaculty4X=700;
int node210X=700;
int node211X=700;
int noderoomX=600;
int nodeKhy2Y=55;
int nodeControlY=365;
int nodeKhy1Y=515;
int nodeNasconY=825;
int nodeFaculty1Y=995;
int nodeFaculty2Y=1125;
int nodeFaculty3Y=1255;
int nodeRawalY=1385;
int node2LadiesRoomY=55;
int node2MensRoomY=185;
int node201Y=315;
int node202Y=485;
int node203Y=655;
int nodeExamRoomY=995;
int nodeAcademicsY=1095;
int nodeFaculty4Y=1235;
int node210Y=1365;
int node211Y=1485;
int noderoomY=1485;
private Path path = new Path();
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
paint1 = new Paint();
paint1.setColor(Color.CYAN);
paint1.setStrokeWidth(10);
paint1.setStyle(Paint.Style.STROKE);
paint2 =new Paint();
paint2.setColor(Color.BLUE);
paint2.setStrokeWidth(10);
paint2.setStyle(Paint.Style.STROKE);
paint3 =new Paint();
paint3.setColor(Color.GRAY);
paint3.setStrokeWidth(10);
paint3.setStyle(Paint.Style.STROKE);
paint4 =new Paint();
paint4.setColor(Color.BLACK);
paint4.setStrokeWidth(5);
paint4.setStyle(Paint.Style.STROKE);
paint5 =new Paint();
paint5.setColor(Color.RED);
paint5.setStrokeWidth(10);
paint5.setStyle(Paint.Style.FILL_AND_STROKE);
paint6 =new Paint();
paint6.setColor(Color.GREEN);
paint6.setStrokeWidth(10);
paint6.setStyle(Paint.Style.FILL_AND_STROKE);
paint7 =new Paint();
paint7.setColor(Color.MAGENTA);
paint7.setStrokeWidth(10);
paint7.setStyle(Paint.Style.STROKE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//rooms on left side
//drawRect(left, top, right, bottom, paint)
canvas.drawRect(150, 10, 1050, 1650, paint1);
canvas.drawRect(180, 50, 480, 160, paint2);
canvas.drawRect(180, 180, 480, 290, paint2);
canvas.drawRect(180, 310, 480, 460, paint2);
canvas.drawRect(180, 480, 480, 630, paint2);
canvas.drawRect(180, 650, 480, 800, paint2);
canvas.drawRect(180, 820, 480, 970, paint2);
canvas.drawRect(180, 990, 480, 1140, paint2);
canvas.drawRect(180, 1160, 480, 1310, paint2);
canvas.drawRect(180, 1330, 480, 1480, paint2);
canvas.drawRect(180, 1500, 480, 1630, paint2);
//rooms on right side
canvas.drawRect(720, 50, 1020, 160, paint2);
canvas.drawRect(720, 180, 1020, 290, paint2);
canvas.drawRect(720, 310, 1020, 460, paint2);
canvas.drawRect(720, 480, 1020, 630, paint2);
canvas.drawRect(720, 650, 1020, 800, paint2);
canvas.drawRect(720, 990, 1020, 1140, paint2);
canvas.drawRect(720, 1160, 1020, 1310, paint2);
canvas.drawRect(720, 1330, 1020, 1480, paint2);
canvas.drawRect(720, 1500, 1020, 1630, paint2);
canvas.drawRect(500, 1500, 700, 1630, paint2);
canvas.drawCircle(740,900,15,paint2);
//path in the centre
canvas.drawLine(500, 20, 500, 1480, paint3);
canvas.drawLine(700, 20, 700, 820, paint3);
canvas.drawLine(700, 980, 700, 1480, paint3);
canvas.drawLine(700, 980, 700, 1480, paint3);
canvas.drawLine(700, 820, 1040, 820, paint3);
canvas.drawLine(700, 970, 1040, 970, paint3);
canvas.drawLine(500, 1480, 700, 1480, paint3);
paint4.setTextSize(40);
//for Naming the rooms on left side
canvas.drawText("Reveal Lab", 200, 100, paint4);
canvas.drawCircle(440,130,18,paint5);
canvas.drawText("TA's Office", 200, 230, paint4);
canvas.drawCircle(440,255,18,paint5);
canvas.drawText("Lab Instructors", 200, 380, paint4);
canvas.drawCircle(440,430,18,paint5);
canvas.drawText("Room # 305", 200, 530, paint4);
canvas.drawCircle(440,600,18,paint5);
canvas.drawText("Faculty Offices", 200, 730, paint4);
canvas.drawCircle(440,770,18,paint5);
canvas.drawText("Boys Common ", 200, 900, paint4);
canvas.drawCircle(440,940,18,paint5);
canvas.drawText("Room", 200, 950, paint4);
canvas.drawText("Room # 316", 200, 1100, paint4);
canvas.drawCircle(440,1110,18,paint5);
canvas.drawText("Room # 315", 200, 1280, paint4);
canvas.drawCircle(440,1280,18,paint5);
canvas.drawText("Room # 314", 200, 1450, paint4);
canvas.drawCircle(440,1450,18,paint5);
canvas.drawText("FYP Lab", 200, 1590, paint4);
canvas.drawCircle(440,1600,18,paint5);
//for Naming the rooms on left side
canvas.drawText("Ladies Room", 750, 100, paint4);
canvas.drawCircle(980,130,18,paint5);
canvas.drawText("Men's Room", 750, 230, paint4);
canvas.drawCircle(980,260,18,paint5);
canvas.drawText("Room # 301", 750, 380, paint4);
canvas.drawCircle(980,430,18,paint5);
canvas.drawText("Room # 302", 750, 530, paint4);
canvas.drawCircle(980,600,18,paint5);
canvas.drawText("Room # 303", 750, 730, paint4);
canvas.drawCircle(980,770,18,paint5);
canvas.drawText("Store", 750, 1100, paint4);
canvas.drawCircle(980,1110,18,paint5);
canvas.drawText("Room # 310", 750, 1280, paint4);
canvas.drawCircle(990,1280,18,paint5);
canvas.drawText("Room # 311", 750, 1450, paint4);
canvas.drawCircle(990,1450,18,paint5);
canvas.drawText("Karakoram Lab", 730, 1590, paint4);
canvas.drawCircle(980,1540,18,paint5);
canvas.drawText("Graduate", 510, 1590, paint4);
canvas.drawText("Lab", 510, 1620, paint4);
canvas.drawCircle(670,1540,18,paint5);
//for naming 3rd floor on path
canvas.drawText(" 3rd ", 550, 50, paint4);
canvas.drawText(" Floor ", 530, 100, paint4);
canvas.drawText(" 3rd Floor ", 850, 900, paint4);
canvas.drawText(" 3rd ", 550, 1420, paint4);
canvas.drawText(" Floor ", 530, 1450, paint4);
//drawRect(left, top, right, bottom, paint)
canvas.drawCircle(50,60,30,paint6);
canvas.drawCircle(50,180,30,paint7);
}
@Override
public boolean onTouchEvent( MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
float x = event.getX();
float y = event.getY();
if(counter==1)
{
sourcex = event.getX();
sourcey = event.getY();
Toast toast5 = Toast.makeText(getContext(),"source"+" "+sourcex+" "+sourcey,Toast.LENGTH_SHORT);
toast5.show();
counter=2;
}
if ((x>=20 && x<=80) && (y>=30 && y<=90))
{
Toast toast4 = Toast.makeText(getContext(),"Navigation started, tap on source",Toast.LENGTH_SHORT);
toast4.show();
// Toast toast5 = Toast.makeText(getContext(),"Navigation started",Toast.LENGTH_SHORT);
//toast5.show();
counter=1;
}
if ((x>=20 && x<=80) && (y>=150 && y<=210))
{ invalidate();
Toast toast4 = Toast.makeText(getContext(),"Navigation ended",Toast.LENGTH_SHORT);
toast4.show();
// Toast toast5 = Toast.makeText(getContext(),"Navigation started",Toast.LENGTH_SHORT);
//toast5.show();
counter=0;
}
//checks for red buttons used for image display
if ((x>=420 && x<=460))
{
if (y>=110 && y<=150)
{
// Toast toast2 = Toast.makeText(getContext(),"Khyber II pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Reveal Lab");
getContext().startActivity(Intent);
}
else if (y>=235 && y<=275)
{
// Toast toast2 = Toast.makeText(getContext(),"Control room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","TA's Office");
getContext().startActivity(Intent);
}
else if (y>=410 && y<=450)
{
//Toast toast2 = Toast.makeText(getContext(),"Khyber I pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Lab Instructors");
getContext().startActivity(Intent);
}
else if (y>=580 && y<=620)
{
// Toast toast2 = Toast.makeText(getContext(),"Nascon room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","305");
getContext().startActivity(Intent);
}
else if (y>=750 && y<=790)
{
// Toast toast2 = Toast.makeText(getContext(),"Faculty offices pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Faculty1");
getContext().startActivity(Intent);
}
else if (y>=920 && y<=960)
{
// Toast toast2 = Toast.makeText(getContext(),"Faculty offices pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Boys Common Room");
getContext().startActivity(Intent);
}
else if (y>=1090 && y<=1130)
{
// Toast toast2 = Toast.makeText(getContext(),"Faculty offices pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","316");
getContext().startActivity(Intent);
}
else if (y>=1260 && y<=1300)
{
// Toast toast2 = Toast.makeText(getContext(),"Rawal lab pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","315");
getContext().startActivity(Intent);
}
else if (y>=1430 && y<=1470)
{
// Toast toast2 = Toast.makeText(getContext(),"Rawal lab pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","314");
getContext().startActivity(Intent);
}
else if (y>=1580 && y<=1620)
{
// Toast toast2 = Toast.makeText(getContext(),"Rawal lab pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Fyp Lab");
getContext().startActivity(Intent);
}
}
else if ((x>=960 && x<=1000))
{
if (y>=110 && y<=150)
{
// Toast toast2 = Toast.makeText(getContext(),"Ladies room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Ladies room");
getContext().startActivity(Intent);
}
else if (y>=240 && y<=280)
{
// Toast toast2 = Toast.makeText(getContext(),"Men's room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Men's room");
getContext().startActivity(Intent);
}
else if (y>=410 && y<=450)
{
// Toast toast2 = Toast.makeText(getContext(),"201 room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","301");
getContext().startActivity(Intent);
}
else if (y>=580 && y<=620)
{
// Toast toast2 = Toast.makeText(getContext(),"202 room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","302");
getContext().startActivity(Intent);
}
else if (y>=750 && y<=790)
{
// Toast toast2 = Toast.makeText(getContext(),"203 room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","303");
getContext().startActivity(Intent);
}
else if (y>=1090 && y<=1130)
{
// Toast toast2 = Toast.makeText(getContext(),"Exam room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Store");
getContext().startActivity(Intent);
}
else if (y>=1260 && y<=1300)
{
// Toast toast2 = Toast.makeText(getContext(),"Academics room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","310");
getContext().startActivity(Intent);
}
else if (y>=1430 && y<=1470)
{
// Toast toast2 = Toast.makeText(getContext(),"Faculty4 room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","311");
getContext().startActivity(Intent);
}
else if (y>=1520 && y<=1560)
{
// Toast toast2 = Toast.makeText(getContext(),"210 room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Karakoram Lab");
getContext().startActivity(Intent);
}
}
else if ((x>=650 && x<=690) && (y>=1520 && y<=1560))
{
// Toast toast2 = Toast.makeText(getContext(),"faculty5 room pressed",Toast.LENGTH_SHORT);
// toast2.show();
Intent Intent = new Intent(getContext(), ImageFileFloor3.class);
Intent.putExtra("image","Graduate Lab");
getContext().startActivity(Intent);
}
break;
// case MotionEvent.ACTION_MOVE:
// Toast toast1 = Toast.makeText(getContext(),"Hello",Toast.LENGTH_LONG);
// toast1.show();
// break;
// case MotionEvent.ACTION_UP:
// Toast toast2 = Toast.makeText(getContext(),"Hello",Toast.LENGTH_LONG);
// toast2.show();
// break;
}
invalidate();
return true;
}
}
|
package Exceptions;
public class ActivityNotFoundException extends Exception{
private static final long serialVersionUID = 313;
public ActivityNotFoundException(String errorMessage) {
super(errorMessage);
}
}
|
package com.xingen.calendarview.bean;
import android.content.Context;
import com.xingen.calendarview.utils.month.MonthUtils;
import com.xingen.calendarview.utils.size.ViewUtils;
import java.util.List;
/**
* Created by ${xinGen} on 2018/1/2.
* blog:http://blog.csdn.net/hexingen
*/
public class MonthBean {
/**
* 当前年,月
*/
private String currentMonth;
/**
* 一个月的最大天数
*/
private int currentMaxDay;
/**
* 第一天属于周几
*/
private int firstDayWeek;
/**
* 一个月的天数
*/
private List<DayBean> dayList;
/**
* 控件的绘制参数
*/
private ViewBean viewBean;
public ViewBean getViewBean() {
return viewBean;
}
public void setViewBean(ViewBean viewBean) {
this.viewBean = viewBean;
}
public String getCurrentMonth() {
return currentMonth;
}
public void setCurrentMonth(String currentMonth) {
this.currentMonth = currentMonth;
}
public int getCurrentMaxDay() {
return currentMaxDay;
}
public void setCurrentMaxDay(int currentMaxDay) {
this.currentMaxDay = currentMaxDay;
}
public int getFirstDayWeek() {
return firstDayWeek;
}
public void setFirstDayWeek(int firstDayWeek) {
this.firstDayWeek = firstDayWeek;
}
public List<DayBean> getDayList() {
return dayList;
}
public void setDayList(List<DayBean> dayList) {
this.dayList = dayList;
}
public static class Builder {
private MonthBean monthBean;
public Builder() {
this.monthBean = new MonthBean();
}
/**
* 设置一个月份
* @param viewStyleBean
* @param monthText
* @return
*/
public Builder setMonthText(ViewStyleBean viewStyleBean,String monthText){
this.monthBean.setCurrentMonth(monthText);
MonthUtils.calculationMonth(monthText,this.monthBean);
MonthUtils.calculationDay(viewStyleBean,this.monthBean);
return this;
}
/**
* 动态计算view的一些参数
* @param context
* @param viewStyleBean
* @return
*/
public Builder setCalculateViewData(Context context,ViewStyleBean viewStyleBean){
ViewBean viewBean=ViewUtils.calculateViewData(context,this.monthBean,viewStyleBean);
this.monthBean.setViewBean(viewBean);
MonthUtils.calculationDayRect(this.monthBean,viewBean.getWeekHeight(),(int) (viewBean.getWidth()*viewStyleBean.getPaddingProportion()), viewBean.getRowSize(), viewBean.getColumnSize());
return this;
}
public MonthBean builder() {
return monthBean;
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.poo;
import java.util.ArrayList;
import java.util.Map;
/**
*
* @author Mayitho Bustos R
*/
public class UberVan extends Car {
Map<String, Map<String, Integer>> typeCarAcepted;
ArrayList<String> seatsMaterial;
private int passenger;
public UberVan(String license, Account driver) {
super(license, driver);
}
public UberVan(String license, Account driver, Map<String, Map<String, Integer>> typeCarAcepted, ArrayList<String> seatsMaterial) {
super(license, driver);
this.typeCarAcepted = typeCarAcepted;
this.seatsMaterial = seatsMaterial;
}
@Override
public void setPassenger(int passenger) {
if (passenger == 6) {
this.passenger = passenger;
} else {
System.out.println("Necesitas asignar 6 pasajeros");
}
}
}
|
package com.yuta.clocktime.model;
public class District {
private String city;
private String timezone;
private int flag;
public District() {
super();
}
public District(String city, String timezone, int flag) {
super();
this.city = city;
this.timezone = timezone;
this.flag = flag;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTimezone() {
return timezone;
}
public void setTimezone(String timezone) {
this.timezone = timezone;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
}
|
package com.xuecheng.framework.exception;
import com.xuecheng.framework.model.response.ResultCode;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class CustomerException extends RuntimeException {
private ResultCode resultCode;
public ResultCode getResultCode() {
return this.resultCode;
}
}
|
package cdn.shared.message.types;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import cdn.shared.message.IMessage;
public class PeerRouterListMessage implements IMessage {
private RouterInfo[] routers;
public PeerRouterListMessage(RouterInfo[] routers) {
this.routers = routers;
}
public PeerRouterListMessage(byte[] bytes) {
ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
try {
DataInputStream s = new DataInputStream(stream);
int numberOfRouters = s.readInt();
routers = new RouterInfo[numberOfRouters];
for (int i = 0; i < numberOfRouters; i++) {
int routerSize = s.readInt();
byte[] reader = new byte[routerSize];
s.read(reader, 0, routerSize);
routers[i] = new RouterInfo(reader);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public RouterInfo[] getRouters() {
return routers;
}
@Override
public MessageType getType() {
return MessageType.PEER_ROUTER_LIST;
}
@Override
public byte[] getWireFormat() {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try {
DataOutputStream s = new DataOutputStream(stream);
s.writeInt(getType().ordinal());
s.writeInt(routers.length);
for (int i = 0; i < routers.length; i++) {
byte[] bytes = routers[i].getWireFormat();
s.writeInt(bytes.length);
s.write(bytes);
}
s.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream.toByteArray();
}
}
|
package twilight.bgfx;
public enum TextureFormat {
BC1, // DXT1
BC2, // DXT3
BC3, // DXT5
BC4, // LATC1/ATI1
BC5, // LATC2/ATI2
BC6H, // BC6H
BC7, // BC7
ETC1, // ETC1 RGB8
ETC2, // ETC2 RGB8
ETC2A, // ETC2 RGBA8
ETC2A1, // ETC2 RGB8A1
PTC12, // PVRTC1 RGB 2BPP
PTC14, // PVRTC1 RGB 4BPP
PTC12A, // PVRTC1 RGBA 2BPP
PTC14A, // PVRTC1 RGBA 4BPP
PTC22, // PVRTC2 RGBA 2BPP
PTC24, // PVRTC2 RGBA 4BPP
Unknown, // compressed formats above
R1, R8, R16, R16F, R32, R32F, RG8, RG16, RG16F, RG32, RG32F, BGRA8, RGBA16, RGBA16F, RGBA32, RGBA32F, R5G6B5, RGBA4, RGB5A1, RGB10A2, R11G11B10F,
UnknownDepth, // depth formats below
D16, D24, D24S8, D32, D16F, D24F, D32F, D0S8,
Count;
}
|
package com.ng.ngcommon.http;
import java.io.Serializable;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
/**
* Created by hd_01 on 2016/9/29.
*/
public class HttpResult implements Serializable {
public Boolean suc;
public String msg;
public transient String rs;
public Integer code;
public Boolean getSuc() {
return suc;
}
public void setSuc(Boolean suc) {
this.suc = suc;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getRs() {
return rs;
}
public void setRs(String rs) {
this.rs = rs;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
|
package com.example.xiaox.goline2.common;
/**
* Created by xiaox on 1/29/2017.
*/
public enum RequestResult {
NoResponse,
Refuse,
Accept
}
|
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
public class copyOnWriteSet {
public static void main(String[] args) {
Set<Integer> lhs = new CopyOnWriteArraySet<>();
lhs.add(88);
lhs.add(188);
lhs.add(288);
lhs.add(388);
Iterator<Integer> i = lhs.iterator();
while(i.hasNext())
{
System.out.println(i.next());
lhs.add(488);
}
}
}
|
package com.holmes.leecode;
import java.util.Arrays;
/**
* @author Administrator
*/
public class SearchMatrix {
public static void main(String[] args) {
int[][] matrix = new int[][]{
{1, 4, 7, 11, 15},
{2, 5, 8, 12, 19},
{3, 6, 9, 16, 22},
{10, 13, 14, 17, 24},
{18, 21, 23, 26, 30}
};
System.out.println(new SearchMatrix().searchMatrix(matrix, 20));
System.out.println(new SearchMatrix().searchMatrix(matrix, 5));
System.out.println(new SearchMatrix().searchMatrix(matrix, 30));
}
public boolean searchMatrix(int[][] matrix, int target) {
for (int i = 0; i < matrix.length; i++) {
if (matrix[i].length >= 1 && matrix[i][0] <= target && matrix[i][matrix[i].length - 1] >= target) {
if (Arrays.binarySearch(matrix[i], target) >= 0) {
return true;
} else if (matrix[i][0] > target) {
break;
}
}
}
return false;
}
}
|
package com.microlecture.servlet;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.microlecture.bean.ExamNotifyBean;
import com.microlecture.bean.HomePageBean;
import com.microlecture.bean.SubmitTestBean;
import com.microlecture.bean.TaskNotifyBean;
import com.microlecture.manager.SQLReader;
/**
* Servlet implementation class TastNotifyServlet
*/
@WebServlet("/TastNotifyServlet")
public class TastNotifyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private SQLReader reader;
private int id =0;
/**
* @see HttpServlet#HttpServlet()
*/
public TastNotifyServlet() {
super();
// TODO Auto-generated constructor stub
reader = new SQLReader();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
id = Integer.parseInt(request.getParameter("courseId"));
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setAttribute("json", getJSON().toString());
//SubmitTestBean bean = new SubmitTestBean();
//bean.parseJSON(getJSON().toString());
request.getRequestDispatcher("/WEB-INF/page/HomePageList.jsp").forward(
request, response);
}
private StringBuilder getJSON() {
StringBuilder json = new StringBuilder();
ArrayList<TaskNotifyBean> list = reader.getTaskNotify();
json.append('{');
json.append("\"length\":[{\"length\":"+list.size()+"}],");
for (int i = 0; i < list.size(); i++) {
json.append("\"TaskNotify"+i+"\":");
json.append(list.get(i).getJson());
}
json.deleteCharAt(json.length() - 1);
json.append('}');
return json;
}
}
|
package org.tomat.translate.brooklyn.print;
import org.tomat.translate.brooklyn.entity.*;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Representer;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
/**
* Created by Kiuby88 on 27/10/14.
*/
public class BrooklynYamlPrinter {
private Yaml yaml =null;
public BrooklynYamlPrinter(){
DumperOptions options= getDumperOptions();
Representer representer= getEmptyAndNullRepresenter();
configurePropertiesOrder(representer);
configureTags(representer);
yaml=new Yaml(representer, options);
}
private DumperOptions getDumperOptions(){
DumperOptions options= new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN);
return options;
}
private Representer getEmptyAndNullRepresenter(){
SkipEmptyAndNullRepresenter skipEmptyAndNullRepresenter=new SkipEmptyAndNullRepresenter();
skipEmptyAndNullRepresenter.setPropertyUtils(new PropertyOrderDefinition());
return skipEmptyAndNullRepresenter;
}
private Representer configurePropertiesOrder(Representer representer){
representer.setPropertyUtils(new PropertyOrderDefinition());
return representer;
}
private Representer configureTags(Representer representer){
representer.addClassTag(JBossBrooklynService.class, Tag.MAP);
representer.addClassTag(MySQLBrooklynService.class, Tag.MAP);
representer.addClassTag(BrooklynApplicationEntity.class, Tag.MAP);
representer.addClassTag(JettyBrooklynService.class, Tag.MAP);
representer.addClassTag(TomcatBrooklynService.class, Tag.MAP);
return representer;
}
public String print(Object o)
throws IOException {
StringWriter writer= new StringWriter();
print(o,writer);
return writer.toString();
}
public void print(Object o, String file)
throws IOException {
FileWriter fW=new FileWriter(file);
print(o, fW);
fW.close();
}
public void print(Object o, Writer writer)
throws IOException {
dumping(o,writer);
//yaml.dump(o, writer);
}
private void dumping(Object o, Writer writer)
throws IOException {
StringWriter writeForChanging = new StringWriter();
yaml.dump(o,writeForChanging);
String bufferForChanging=writeForChanging.toString();
bufferForChanging=bufferForChanging.replace("brooklynConfigProperties:","brooklyn.config:");
writer.write(bufferForChanging);
}
}
|
package com.leyou.user.controller;
import com.leyou.user.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
/**
* @auther ff
* @create 2018-08-02 19:49
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserControllerTest {
@Autowired
private UserController userController;
@Test
public void findUserByUsernameAndPassword() {
ResponseEntity<User> user = userController.findUserByUsernameAndPassword("tom123", "tom123");
System.out.println("user = " + user);
}
}
|
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author PhongFPT
*/
public class ComboboxDemo extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public ComboboxDemo() {
initComponents();
this.setTitle("Combobox demo");
lbAnimal.setText("");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
cbAnimal = new javax.swing.JComboBox();
lbAnimal = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
cbAnimal.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Bird", "Cat", "Dog", "Pig", "Rabbit", "Corgi", "Goat", "Shark" }));
cbAnimal.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cbAnimalActionPerformed(evt);
}
});
lbAnimal.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(94, 94, 94)
.addComponent(cbAnimal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(35, 35, 35)
.addComponent(lbAnimal, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(89, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(cbAnimal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addComponent(lbAnimal, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void cbAnimalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbAnimalActionPerformed
// TODO add your handling code here:
lbAnimal.setIcon(new ImageIcon("./AnimalPicture/"+cbAnimal.getSelectedItem().toString().toLowerCase()+".png"));
}//GEN-LAST:event_cbAnimalActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ComboboxDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ComboboxDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ComboboxDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ComboboxDemo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ComboboxDemo().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox cbAnimal;
private javax.swing.JLabel lbAnimal;
// End of variables declaration//GEN-END:variables
}
|
package com.example.tmnt.draganddraw;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.text.SimpleDateFormat;
public class DragandDrawActivity extends SimpleFragmentActivity {
@Override
protected Fragment createFragment() {
return new DragandDrawFragment();
}
}
|
package edu.metrostate.ics372.thatgroup.clinicaltrial.android.catalog;
import static org.junit.Assert.*;
import edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp;
import edu.metrostate.ics372.thatgroup.clinicaltrial.beans.UnitValue;
import java.time.LocalDateTime;
import org.junit.Test;
/**
* @author That Group
*String patientId, String id, LocalDateTime date, Object value, String clinicId)
*/
public class TempTest {
private static final String DEFAULT_PATIENT_ID = "test";
private static final String DEFAULT_ID = "test";
private static final LocalDateTime DEFAULT_DATE = LocalDateTime.now();
private static final Long LONG_VALUE = 99L;
private static final String DEFAULT_UNIT = "lbs";
private static final String STRING_VALUE = "99 lbs";
private static final String DEFAULT_CLINIC_ID = "test";
/**
* Test method for {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#toString()}.
*/
@Test
public final void testToString() {
Temp temp= new Temp();
temp.setClinicId(DEFAULT_CLINIC_ID);
temp.setPatientId(DEFAULT_PATIENT_ID);
temp.setId(DEFAULT_ID);
temp.setDate(DEFAULT_DATE);
temp.setValue(STRING_VALUE);
System.out.println(temp);
UnitValue value = (UnitValue) temp.getValue();
Long longVal = (Long) value.getNumberValue();
String strUnit = value.getUnit();
assertEquals(LONG_VALUE, longVal);
assertEquals(DEFAULT_UNIT, strUnit);
UnitValue newVal = new UnitValue(longVal, strUnit);
assertEquals(newVal, value);
}
/**
* Test method for {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#getValue()} and
* {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#setValue(java.lang.Object)}.
*/
@Test
public final void testLongValue() {
Temp temp= new Temp();
temp.setValue(LONG_VALUE);
UnitValue value = (UnitValue) temp.getValue();
Long longVal = (Long) value.getNumberValue();
String strUnit = value.getUnit();
UnitValue newVal = new UnitValue(longVal, strUnit);
assertEquals(newVal, value);
//assertEquals(LONG_VALUE, temp.getValue());
}
/**
* Test method for {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#getValue()} and
* {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#setValue(java.lang.Object)}.
*/
@Test
public final void testStringValue() {
Temp temp= new Temp();
temp.setValue(STRING_VALUE);
UnitValue value = (UnitValue) temp.getValue();
Long longVal = (Long) value.getNumberValue();
String strUnit = value.getUnit();
UnitValue newVal = new UnitValue(longVal, strUnit);
assertEquals(newVal, value);
//assertEquals(STRING_VALUE, temp.getValue());
}
/**
* Test method for {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#Temp()}.
*/
@Test
public final void testNoArgsConstrcutedTempTest() {
Temp temp = new Temp(null, null, null, STRING_VALUE, null);
temp.setPatientId(DEFAULT_PATIENT_ID);
assertNotNull(temp);
assertEquals(DEFAULT_PATIENT_ID, temp.getPatientId());
assertNull(temp.getId());
assertNull(temp.getDate());
assertNotNull(temp.getValue());
assertNull(temp.getClinicId());
}
/**
* Test method for {@link edu.metrostate.ics372.thatgroup.clinicaltrial.beans.Temp#Temp(java.lang.String, java.lang.String, java.time.LocalDateTime, java.lang.Object, java.lang.String)}.
*/
@Test
public final void testTempStringStringLocalDateTimeObjectString() {
Temp temp= new Temp(DEFAULT_PATIENT_ID, DEFAULT_ID, DEFAULT_DATE, LONG_VALUE, DEFAULT_CLINIC_ID);
temp.setPatientId(DEFAULT_PATIENT_ID);
UnitValue value = (UnitValue) temp.getValue();
Long longVal = (Long) value.getNumberValue();
String strUnit = value.getUnit();
UnitValue newVal = new UnitValue(longVal, strUnit);
//assertEquals(LONG_VALUE, temp.getValue());
assertEquals(newVal, value);//for unit value
assertEquals(newVal, value);
assertNotNull(temp);
assertEquals(DEFAULT_PATIENT_ID, temp.getPatientId());
assertEquals(DEFAULT_ID, temp.getId());
assertEquals(DEFAULT_DATE, temp.getDate());
assertEquals(DEFAULT_CLINIC_ID, temp.getClinicId());
}
}
|
package by.epam.concexamples.synchronizer.cyclicbarier;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
/**
* Created by Alex on 21.10.2016.
*/
public class Car extends Thread {
private String pilotName;
private CyclicBarrier cyclicBarrier;
public Car(String pilotName, CyclicBarrier cyclicBarrier){
this.pilotName = pilotName;
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
try {
System.out.println(pilotName + " подъехал к стартовой решетке.");
cyclicBarrier.await(); //Сообщаем что гонщик подъехал к старту.
System.out.println(pilotName + " возобновил гонку.");
} catch (BrokenBarrierException ex){
ex.printStackTrace();
} catch (InterruptedException ex){
ex.printStackTrace();
}
}
}
|
package viper.ui.watermark;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableColumn;
public class WatermarkTableModel extends AbstractTableModel
{
private String[] columnNames = {"Filename"};
private Object[][] data = {{"Filename"}};
private TableColumn column = null;
public WatermarkTableModel()
{
super();
}
public WatermarkTableModel(Object[][] data)
{
super();
this.data = data;
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return columnNames.length;
}
public String getColumnName(int col)
{
return columnNames[col].toString();
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return data.length;
}
@Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return data[arg0][arg1];
}
}
|
package day3_variables_dataTypes;
public class VariableDeclarion {
public static void main(String[] args) {
// decleration
byte inches;
int speed;
short month;
float salesComission;
double distance;
//assigned
inches=5;
speed=20;
month=2;
distance=20.2;
salesComission=5;
//Declared+Assigned
byte inches2=5;
System.out.println(inches);
System.out.println(salesComission);
byte number=5;
System.out.println("My number is " + number);
// Test case-- Check the balance with 100 accunt numbers
byte accuntnumber=20;
System.out.println("My number is " + accuntnumber);
String greeting;
greeting="HelloOmer";
System.out.println("greeting");
}
}
|
/**
* @(#) GenerateTxChannelSql.java
* module : CodeGenerator
* version : 版本管理系统中的文件版本
* date : 2012-3-23
* name : nilomiao
*/
package com.allinpay.generator.sql;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.allinpay.util.DateUtil;
/**
* <pre>
* 如果有任何对代码的修改,请按下面的格式注明修改的内容.
* 序号 时间 作者 修改内容
* 1. 2012-3-23 nilomiao created this class.
* </pre>
*/
public class GenerateTxChannelSql {
public static final String paraFile = "E:/dev-workspace/frame/IPP-env/change/transaction_parameters.xls";
/**
* @param args
*/
public static void main(String[] args) {
try {
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(paraFile));
HSSFSheet sheet = workbook.getSheet("channel");
int rowCount = sheet.getLastRowNum() + 1;
for (int i = 1; i < rowCount; i++) {
HSSFRow row = sheet.getRow(i);
HSSFCell cell1 = row.getCell(1);
if (null != cell1) {
String channelId = String.valueOf((int) row.getCell(1).getNumericCellValue());
String channelName = row.getCell(2).toString();
String orgCode = row.getCell(3).toString();
String merchantId = null == row.getCell(4) ? null : row.getCell(4).toString();
String merchantAcct = null == row.getCell(5) ? null : row.getCell(5).toString();
String publicKeyPath = null == row.getCell(6) ? null : row.getCell(6)
.toString();
String privateKeyPath = null == row.getCell(7) ? null : row.getCell(7)
.toString();
String privateKeyPassword = null == row.getCell(8) ? null : row.getCell(8)
.toString();
String confPath = null == row.getCell(9) ? null : row.getCell(9).toString();
String orgPublicKeyPath = null == row.getCell(10) ? null : row.getCell(10)
.toString();
String remark = null == row.getCell(11) ? null : row.getCell(11)
.toString();
StringBuffer buf = new StringBuffer();
buf.append("INSERT INTO gw_transaction_channel(");
buf.append("channel_id,name,org_id,");
buf.append("state,merchant_id, merchant_acct, public_key_path,");
buf.append("private_key_path, private_key_password, org_public_key_path,");
buf.append("conf_path, description,");
buf.append("create_datetime,create_operator,");
buf.append("last_update_datetime,last_update_operator");
buf.append(") VALUES(");
buf.append(channelId).append(",'").append(channelName).append("','");
buf.append(orgCode).append("',1,");
appendPara(merchantId, buf);
appendPara(merchantAcct, buf);
appendPara(publicKeyPath, buf);
appendPara(privateKeyPath, buf);
appendPara(privateKeyPassword, buf);
appendPara(orgPublicKeyPath, buf);
appendPara(confPath, buf);
appendPara(remark, buf);
String datetime = DateUtil.formatCurrDateTime(DateUtil.DF_Y_M_D_HMS);
appendPara(datetime, buf);
appendPara(null, buf);
appendPara(datetime, buf);
buf.append("null");
buf.append(");");
System.out.println(buf.toString());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void appendPara(String para, StringBuffer buf) {
if (null == para) {
buf.append(para).append(",");
} else {
buf.append("'").append(para).append("',");
}
}
}
|
/*
* Copyright (c) 2016 Mobvoi Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ticwear.design.widget;
import android.content.Context;
import android.os.Handler;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.Adapter;
import android.support.v7.widget.RecyclerView.ItemAnimator.ItemAnimatorFinishedListener;
import android.support.v7.widget.RecyclerView.Recycler;
import android.support.v7.widget.RecyclerView.State;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import ticwear.design.DesignConfig;
import ticwear.design.R;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.LOCAL_VARIABLE;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.SOURCE;
/**
* Enhanced LayoutManager that support focused status.
*
* Created by tankery on 4/13/16.
*/
public class FocusableLinearLayoutManager extends LinearLayoutManager
implements TicklableLayoutManager {
static final String TAG = "FocusableLLM";
/**
* Invalid focus state
*/
public static final int FOCUS_STATE_INVALID = -1;
/**
* Focus state on normal (not tickled).
*/
public static final int FOCUS_STATE_NORMAL = 0;
/**
* Focus state on central, means the item is focused when tickled.
*/
public static final int FOCUS_STATE_CENTRAL = 1;
/**
* Focus state on non central, means the item is not focused when tickled.
*/
public static final int FOCUS_STATE_NON_CENTRAL = 2;
private final Context mContext;
private final Handler mUiHandler;
@Nullable
private TicklableRecyclerView mTicklableRecyclerView;
@Nullable
private FocusLayoutHelper mFocusLayoutHelper;
private ScrollVelocityTracker mScrollVelocityTracker;
private boolean mScrollResetting;
private final FocusStateRequest mFocusStateRequest = new FocusStateRequest();
private final List<OnCentralPositionChangedListener> mOnCentralPositionChangedListeners;
private int mPreviousCentral;
/**
* To make-sure we have focus change when coordinate with {@link AppBarLayout},
* We should use a scroll to mock the offset.
*/
private int mScrollOffset;
private static final int INVALID_SCROLL_OFFSET = Integer.MAX_VALUE;
private final AppBarScrollController mAppBarScrollController;
public FocusableLinearLayoutManager(Context context) {
super(context, VERTICAL, false);
mContext = context;
mUiHandler = new Handler();
mOnCentralPositionChangedListeners = new ArrayList<>();
mPreviousCentral = RecyclerView.NO_POSITION;
mScrollOffset = INVALID_SCROLL_OFFSET;
mAppBarScrollController = new AppBarScrollController(mTicklableRecyclerView);
setInFocusState(false);
}
/**
* Adds a listener that will be called when the central item of the list changes.
*/
public void addOnCentralPositionChangedListener(OnCentralPositionChangedListener listener) {
mOnCentralPositionChangedListeners.add(listener);
}
/**
* Removes a listener that would be called when the central item of the list changes.
*/
public void removeOnCentralPositionChangedListener(OnCentralPositionChangedListener listener) {
mOnCentralPositionChangedListeners.remove(listener);
}
/**
* Clear all listeners that listening the central item of the list changes event.
*/
public void clearOnCentralPositionChangedListener() {
mOnCentralPositionChangedListeners.clear();
}
private void setInFocusState(boolean toFocus) {
boolean inFocus = mFocusLayoutHelper != null;
if (inFocus == toFocus) {
return;
}
if (toFocus && mTicklableRecyclerView != null) {
mFocusLayoutHelper = new FocusLayoutHelper(mTicklableRecyclerView, this);
} else if (mFocusLayoutHelper != null) {
mFocusLayoutHelper.destroy();
mFocusLayoutHelper = null;
}
// Restore offset
restoreOffset();
// Set flag so we will request focus state change on next layout.
// Or, we will notify immediately.
mFocusStateRequest.notifyOnNextLayout = true;
if (getChildCount() > 0) {
if (mFocusLayoutHelper != null) {
requestNotifyChildrenAboutFocus();
} else {
requestNotifyChildrenAboutExit();
}
}
requestSimpleAnimationsInNextLayout();
if (mTicklableRecyclerView != null && mTicklableRecyclerView.getAdapter() != null) {
mTicklableRecyclerView.getAdapter().notifyDataSetChanged();
}
}
private void restoreOffset() {
if (mTicklableRecyclerView == null)
return;
mScrollResetting = true;
if (mFocusLayoutHelper != null) {
mScrollOffset = mTicklableRecyclerView.getTop();
mTicklableRecyclerView.offsetTopAndBottom(-mScrollOffset);
mTicklableRecyclerView.scrollBy(0, -mScrollOffset);
} else {
if (mScrollOffset != INVALID_SCROLL_OFFSET) {
mTicklableRecyclerView.offsetTopAndBottom(mScrollOffset);
mTicklableRecyclerView.scrollBy(0, mScrollOffset);
mScrollOffset = INVALID_SCROLL_OFFSET;
}
}
mScrollResetting = false;
}
@Override
public void setTicklableRecyclerView(TicklableRecyclerView ticklableRecyclerView) {
mTicklableRecyclerView = ticklableRecyclerView;
}
@Override
public boolean validAdapter(Adapter adapter) {
// TODO: find a better way to valid adapter instead of instance a ViewHolder.
if (adapter != null && adapter.getItemCount() > 0) {
RecyclerView.ViewHolder viewHolder = adapter.createViewHolder(mTicklableRecyclerView,
adapter.getItemViewType(0));
if (!(viewHolder instanceof ViewHolder)) {
String msg = "adapter's ViewHolder should be instance of FocusableLinearLayoutManager.ViewHolder";
if (DesignConfig.DEBUG) {
throw new IllegalArgumentException(msg);
} else {
Log.w(TAG, msg);
return false;
}
}
}
return true;
}
@Override
public boolean interceptPreScroll() {
return mFocusLayoutHelper != null && mFocusLayoutHelper.interceptPreScroll();
}
@Override
public boolean useScrollAsOffset() {
return mFocusLayoutHelper != null;
}
@Override
public int getScrollOffset() {
return mScrollOffset == INVALID_SCROLL_OFFSET ? 0 : mScrollOffset;
}
/**
* Update offset to scroll.
*
* This will calculate the delta of previous offset and new offset, then apply it to scroll.
*
* @param scrollOffset new offset to scroll.
*
* @return the unconsumed offset (that needs to appending on raw offset).
*/
@Override
public int updateScrollOffset(int scrollOffset) {
if (mTicklableRecyclerView == null ||
this.mScrollOffset == INVALID_SCROLL_OFFSET ||
mAppBarScrollController.isAppBarChanging()) {
this.mScrollOffset = scrollOffset;
return 0;
}
if (this.mScrollOffset == scrollOffset) {
return 0;
}
int delta = scrollOffset - this.mScrollOffset;
int scroll = -delta;
int[] consumed = new int[2];
// Temporary disable nested scrolling.
mTicklableRecyclerView.scrollBySkipNestedScroll(0, scroll, consumed);
this.mScrollOffset -= consumed[1];
return scrollOffset - this.mScrollOffset;
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
}
@Override
public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
getHandler().removeCallbacks(exitFocusStateRunnable);
super.onDetachedFromWindow(view, recycler);
}
@Override
public void onLayoutChildren(Recycler recycler, State state) {
super.onLayoutChildren(recycler, state);
if (mFocusStateRequest.notifyOnNextLayout) {
mFocusStateRequest.notifyOnNextLayout = false;
// If the notify has a animation, we should make sure the notify is later than
// RecyclerView's animation. So they will not conflict.
if (mFocusStateRequest.animate) {
postOnAnimation(new Runnable() {
@Override
public void run() {
// We wait for animation time begin and notify on next main loop,
// So we can sure the notify is follow the state change animation.
notifyAfterLayoutOnNextMainLoop();
}
});
} else {
requestNotifyChildrenStateChanged(mFocusStateRequest);
}
}
}
private void notifyAfterLayoutOnNextMainLoop() {
mUiHandler.post(new Runnable() {
@Override
public void run() {
requestNotifyChildrenStateChanged(mFocusStateRequest);
}
});
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
@Override
public boolean getClipToPadding() {
return mFocusLayoutHelper == null && super.getClipToPadding();
}
@Override
public int getPaddingTop() {
return mFocusLayoutHelper != null ?
mFocusLayoutHelper.getVerticalPadding() :
super.getPaddingTop();
}
@Override
public int getPaddingBottom() {
return mFocusLayoutHelper != null ?
mFocusLayoutHelper.getVerticalPadding() :
super.getPaddingBottom();
}
@Override
public boolean canScrollVertically() {
return getChildCount() > 0;
}
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
int scrolled = super.scrollVerticallyBy(dy, recycler, state);
if (scrolled == dy) {
onScrollVerticalBy(dy);
}
return scrolled;
}
@Override
public void onScrollStateChanged(int state) {
if (mFocusLayoutHelper != null) {
mFocusLayoutHelper.onScrollStateChanged(state);
} else {
super.onScrollStateChanged(state);
}
}
private void onScrollVerticalBy(int dy) {
if (mScrollVelocityTracker == null && mFocusLayoutHelper != null) {
int itemHeight = mFocusLayoutHelper.getCentralItemHeight();
mScrollVelocityTracker =
new ScrollVelocityTracker(mContext, itemHeight);
}
boolean scrollFast = mScrollVelocityTracker != null &&
mScrollVelocityTracker.addScroll(dy);
if (getChildCount() > 0) {
if (mFocusLayoutHelper != null) {
requestNotifyChildrenAboutScroll(!scrollFast);
} else {
requestNotifyChildrenAboutExit();
}
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent e) {
exitFocusStateIfNeed(e);
return false;
}
@Override
public boolean dispatchTouchSidePanelEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
enterFocusStateIfNeed(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getHandler().postDelayed(exitFocusStateRunnable,
// after this period of time without focus state action (side panel event),
// we should exit focus state.
mContext.getResources().getInteger(R.integer.design_time_action_idle_timeout));
break;
}
return mFocusLayoutHelper != null && mFocusLayoutHelper.dispatchTouchSidePanelEvent(ev);
}
private void enterFocusStateIfNeed(@Nullable MotionEvent ev) {
getHandler().removeCallbacks(exitFocusStateRunnable);
if (mFocusLayoutHelper != null) {
return;
}
setInFocusState(true);
// Fix touch offset according to scroll-offset
// When enter focus state, offset of this view will transfer to scroll.
// So we must calculate the offset change into touch event.
if (ev != null && mScrollOffset != INVALID_SCROLL_OFFSET &&
ev.getAction() == MotionEvent.ACTION_DOWN) {
ev.offsetLocation(0, mScrollOffset);
}
}
private void exitFocusStateIfNeed() {
exitFocusStateIfNeed(null);
}
private void exitFocusStateIfNeed(@Nullable MotionEvent ev) {
getHandler().removeCallbacks(exitFocusStateRunnable);
if (mFocusLayoutHelper == null) {
return;
}
// Fix touch offset according to scroll-offset
// When exit focus state, scroll of this view will transfer to offset.
// So we must calculate the offset change into touch event.
if (ev != null && mScrollOffset != INVALID_SCROLL_OFFSET &&
ev.getAction() == MotionEvent.ACTION_DOWN) {
ev.offsetLocation(0, -mScrollOffset);
}
setInFocusState(false);
}
private Runnable exitFocusStateRunnable = new Runnable() {
@Override
public void run() {
exitFocusStateIfNeed();
}
};
void requestNotifyChildrenAboutScroll(boolean animate) {
if (mScrollResetting || mFocusLayoutHelper == null) {
return;
}
mFocusStateRequest.centerIndex = mFocusLayoutHelper.findCenterViewIndex();
mFocusStateRequest.animate = animate;
mFocusStateRequest.scroll = true;
requestNotifyChildrenStateChanged(mFocusStateRequest);
}
void requestNotifyChildrenAboutFocus() {
if (mScrollResetting || mFocusLayoutHelper == null) {
return;
}
mFocusStateRequest.centerIndex = mFocusLayoutHelper.findCenterViewIndex();
mFocusStateRequest.animate = true;
mFocusStateRequest.scroll = false;
requestNotifyChildrenStateChanged(mFocusStateRequest);
}
void requestNotifyChildrenAboutExit() {
if (mScrollResetting) {
return;
}
mFocusStateRequest.centerIndex = RecyclerView.NO_POSITION;
mFocusStateRequest.animate = true;
mFocusStateRequest.scroll = false;
requestNotifyChildrenStateChanged(mFocusStateRequest);
}
private void requestNotifyChildrenStateChanged(final FocusStateRequest request) {
if (request.notifyOnNextLayout) {
return;
}
boolean isRunning = mTicklableRecyclerView != null &&
mTicklableRecyclerView.getItemAnimator().isRunning(
new ItemAnimatorFinishedListener() {
@Override
public void onAnimationsFinished() {
if (mTicklableRecyclerView != null) {
notifyChildrenStateChanged(mTicklableRecyclerView, request);
}
}
});
if (DesignConfig.DEBUG_RECYCLER_VIEW) {
Log.v(TAG, "request state changed with item anim running? " + isRunning);
}
}
private void notifyChildrenStateChanged(@NonNull TicklableRecyclerView listView,
FocusStateRequest request) {
int top = ViewPropertiesHelper.getTop(listView);
int bottom = ViewPropertiesHelper.getBottom(listView);
int center = ViewPropertiesHelper.getCenterYPos(listView);
for (int index = 0; index < getChildCount(); ++index) {
View view = getChildAt(index);
int focusState = FOCUS_STATE_NORMAL;
if (request.centerIndex != RecyclerView.NO_POSITION) {
focusState = index == request.centerIndex ?
FOCUS_STATE_CENTRAL :
FOCUS_STATE_NON_CENTRAL;
}
final boolean animateStateChange = view.isShown() && request.animate;
notifyChildFocusStateChanged(listView, focusState, animateStateChange, view);
if (focusState == FOCUS_STATE_NORMAL) {
continue;
}
int childCenter = ViewPropertiesHelper.getCenterYPos(view);
int halfChildHeight = view.getHeight() / 2;
float progress = getCentralProgress(top + halfChildHeight, bottom - halfChildHeight, center, childCenter);
ViewHolder viewHolder = (ViewHolder) listView.getChildViewHolder(view);
final boolean animateProgressChange = view.isShown() && request.animate && !request.scroll;
notifyChildProgressUpdated(viewHolder, progress, animateProgressChange);
}
notifyOnCentralPositionChanged(listView, request.centerIndex);
}
private float getCentralProgress(int top, int bottom, int center, int childCenter) {
if (childCenter < top) {
childCenter = top;
}
if (childCenter > bottom) {
childCenter = bottom;
}
float progress;
if (childCenter > center) {
progress = (float) (bottom - childCenter) / (bottom - center);
} else {
progress = (float) (childCenter - top) / (center - top);
}
return progress;
}
private void notifyChildProgressUpdated(ViewHolder viewHolder, float progress, boolean animate) {
long defaultDuration = viewHolder.getDefaultAnimDuration();
long duration;
// We have a animation in progress.
if (viewHolder.animationStartTime > 0) {
long timePassed = System.currentTimeMillis() - viewHolder.animationStartTime;
viewHolder.animationPlayedTime += timePassed;
if (viewHolder.animationPlayedTime >= defaultDuration) {
// animation end.
viewHolder.animationStartTime = 0;
viewHolder.animationPlayedTime = 0;
duration = animate ? defaultDuration : 0;
} else {
// animation in progress, always play the rest duration.
duration = animate ?
defaultDuration :
defaultDuration - viewHolder.animationPlayedTime;
}
} else {
duration = animate ? defaultDuration : 0;
if (animate) {
// If we update progress with animation and no anim before,
// we enter the animation mode with a start time set.
viewHolder.animationStartTime = System.currentTimeMillis();
viewHolder.animationPlayedTime = 0;
}
}
viewHolder.onCentralProgressUpdated(progress, duration);
}
private void notifyChildFocusStateChanged(@NonNull TicklableRecyclerView listView,
int focusState, boolean animate, View view) {
ViewHolder viewHolder = (ViewHolder) listView.getChildViewHolder(view);
// Only call focus state change once.
if (viewHolder.prevFocusState != focusState) {
if (focusState == FOCUS_STATE_NORMAL) {
viewHolder.itemView.setFocusable(false);
viewHolder.itemView.setFocusableInTouchMode(false);
} else {
viewHolder.itemView.setFocusable(true);
viewHolder.itemView.setFocusableInTouchMode(true);
}
viewHolder.onFocusStateChanged(focusState, animate);
viewHolder.prevFocusState = focusState;
view.setClickable(focusState != FOCUS_STATE_NON_CENTRAL);
}
}
private void notifyOnCentralPositionChanged(@NonNull TicklableRecyclerView listView,
int centerIndex) {
int centerPosition = centerIndex == RecyclerView.NO_POSITION ?
RecyclerView.NO_POSITION : listView.getChildAdapterPosition(getChildAt(centerIndex));
if (centerPosition != mPreviousCentral) {
for (OnCentralPositionChangedListener listener : mOnCentralPositionChangedListeners) {
listener.onCentralPositionChanged(centerPosition);
}
mPreviousCentral = centerPosition;
}
}
public Handler getHandler() {
return mUiHandler;
}
private static class FocusStateRequest {
public boolean notifyOnNextLayout;
public int centerIndex;
public boolean animate;
public boolean scroll;
public FocusStateRequest() {
notifyOnNextLayout = false;
centerIndex = -1;
animate = false;
scroll = false;
}
@Override
public String toString() {
return "FocusStateRequest@" + hashCode() + "{" +
"notifyOnNext " + notifyOnNextLayout +
", center " + centerIndex +
", animate " + animate +
", scroll " + scroll +
"}";
}
}
/**
* Denotes that an integer parameter, field or method return value is expected
* to be a focus state value (e.g. {@link #FOCUS_STATE_CENTRAL}).
*/
@Documented
@Retention(SOURCE)
@Target({METHOD, PARAMETER, FIELD, LOCAL_VARIABLE})
@IntDef({FOCUS_STATE_INVALID, FOCUS_STATE_NORMAL, FOCUS_STATE_CENTRAL, FOCUS_STATE_NON_CENTRAL})
public @interface FocusState {}
/**
* An listener that receive messages for focus state change.
*
* @see #FOCUS_STATE_NORMAL
* @see #FOCUS_STATE_CENTRAL
* @see #FOCUS_STATE_NON_CENTRAL
*/
public interface OnFocusStateChangedListener {
/**
* Item's focus state has changed.
* @param focusState state of focus. can be {@link #FOCUS_STATE_NORMAL},
* {@link #FOCUS_STATE_CENTRAL}, {@link #FOCUS_STATE_NON_CENTRAL}
* @param animate interact with animation?
*/
void onFocusStateChanged(@FocusState int focusState, boolean animate);
}
public interface OnCentralProgressUpdatedListener {
/**
* When we are in focus state, item will be notified by the progress of going central.
*
* @param progress progress from edge to center. The value is in [0, 1],
* 1 means right on the view's center, 0 means on view's edge.
* @param animateDuration animate duration to that progress, if 0, means
* no animate at all.
*/
void onCentralProgressUpdated(float progress, long animateDuration);
}
private static class ScrollVelocityTracker {
private long mLastScrollTime = -1;
private final float mFastScrollVelocity;
ScrollVelocityTracker(@NonNull Context context, int itemHeight) {
long animationTime = context.getResources()
.getInteger(R.integer.design_anim_list_item_state_change);
mFastScrollVelocity = 1.5f * itemHeight / animationTime;
}
public boolean addScroll(int dy) {
boolean scrollFast = false;
long currentTime = System.currentTimeMillis();
if (mLastScrollTime > 0) {
long duration = currentTime - mLastScrollTime;
float velocity = (float) Math.abs(dy) / duration;
if (velocity > mFastScrollVelocity) {
scrollFast = true;
}
}
mLastScrollTime = currentTime;
return scrollFast;
}
}
/**
* An OnCentralPositionChangedListener can be set on a TicklableRecyclerView to receive messages
* when a central position changed event has occurred on that TicklableRecyclerView when tickled.
*
* @see #addOnCentralPositionChangedListener(OnCentralPositionChangedListener)
*/
public interface OnCentralPositionChangedListener {
/**
* Callback method to be invoked when TicklableRecyclerView's central item changed.
*
* @param position The adapter position of the central item, can be {@link RecyclerView#NO_POSITION}.
* If is {@link RecyclerView#NO_POSITION}, means the tickle state is changed to normal,
* so there is no central item.
*/
void onCentralPositionChanged(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
@FocusState
private int prevFocusState;
private long animationStartTime;
private long animationPlayedTime;
private final long defaultAnimDuration;
private final Interpolator focusInterpolator;
public ViewHolder(View itemView) {
super(itemView);
prevFocusState = FOCUS_STATE_INVALID;
animationStartTime = 0;
animationPlayedTime = 0;
defaultAnimDuration = itemView.getContext().getResources()
.getInteger(R.integer.design_anim_list_item_state_change);
focusInterpolator = new AccelerateDecelerateInterpolator();
}
/**
* When we are in focus state, item will be notified by the progress of going central.
* Override this method to do more smooth animation.
*
* @param progress progress from edge to center. The value is in [0, 1],
* 1 means right on the view's center, 0 means on view's edge.
* @param animateDuration animate duration to that progress, if 0, means
*/
protected void onCentralProgressUpdated(float progress, long animateDuration) {
if (itemView instanceof OnCentralProgressUpdatedListener) {
OnCentralProgressUpdatedListener item = (OnCentralProgressUpdatedListener) itemView;
item.onCentralProgressUpdated(progress, animateDuration);
} else {
float scaleMin = 1.0f;
float scaleMax = 1.1f;
float alphaMin = 0.6f;
float alphaMax = 1.0f;
float scale = scaleMin + (scaleMax - scaleMin) * progress;
float alphaProgress = getFocusInterpolator().getInterpolation(progress);
float alpha = alphaMin + (alphaMax - alphaMin) * alphaProgress;
transform(scale, alpha, animateDuration);
}
}
/**
* Focus state of view bind to this ViewHolder is changed.
*
* @param focusState new focus state of view.
* @param animate should apply a animate for this change? If not, just change
* the view immediately.
*/
protected void onFocusStateChanged(@FocusState int focusState, boolean animate) {
if (DesignConfig.DEBUG_RECYCLER_VIEW) {
Log.d(TAG, getLogPrefix() + "focus state to " + focusState + ", animate " + animate + getLogSuffix());
}
if (itemView instanceof OnFocusStateChangedListener) {
OnFocusStateChangedListener item = (OnFocusStateChangedListener) itemView;
item.onFocusStateChanged(focusState, animate);
} else {
if (focusState == FOCUS_STATE_NORMAL) {
transform(1.0f, 1.0f, animate ? getDefaultAnimDuration() : 0);
}
}
}
private void transform(float scale, float alpha, long duration) {
itemView.animate().cancel();
if (duration > 0) {
itemView.animate()
.setDuration(duration)
.alpha(alpha)
.scaleX(scale)
.scaleY(scale)
.start();
} else {
itemView.setScaleX(scale);
itemView.setScaleY(scale);
itemView.setAlpha(alpha);
}
}
/**
* If the transform needs a animation, use this duration for default.
*/
public long getDefaultAnimDuration() {
return defaultAnimDuration;
}
/**
* get the interpolator for focus usage, use the interpolator to interpolation
* the progress, so you can get a more obvious focus effect.
*
* @see #onCentralProgressUpdated
*/
public Interpolator getFocusInterpolator() {
return focusInterpolator;
}
protected final String getLogPrefix() {
int layoutPosition = getLayoutPosition();
int adapterPosition = getAdapterPosition();
return String.format(Locale.getDefault(),
"<%d,%d %8x,%8x>: ",
adapterPosition, layoutPosition,
hashCode(), itemView.hashCode());
}
protected final String getLogSuffix() {
return " with " + this + ", view " + itemView;
}
}
}
|
package org.dahotre.stockmonkey.model;
import java.util.Date;
/**
* POJO for event
*/
public class LambdaEvent {
String id;
String account;
String region;
Date time;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
}
|
package com.ken.backend.repository;
import com.ken.backend.entity.Customer;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.time.LocalDateTime;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class CustomerRepositoryTest {
@Autowired
private CustomerRepository customerRepository;
@Test
void findAll(){
System.out.println(customerRepository.findAll());
}
}
|
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import javax.swing.JOptionPane;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
/**
* This class is used to represent the user management interface
* @author Refined Storage developers
*
*/
public class GuiManageUsers extends Composite {
private Text inputIdRemove;
private Text inputName;
private Text inputPassword;
/**
* Object super
*/
public Object Super;
private Text inputIdAdd;
/**
* This method is represents the user management interface along with his functionality
* @param parent the composite parent
* @param style the desired style
* @param name the current user name
* @param Rs the refined storage
* @param Db the database
*/
public GuiManageUsers(Composite parent, int style, String name, Refined_storage Rs, DbFunctions Db) {
super(parent, style);
this.setVisible(false);
this.setVisible(true);
Super = this;
Composite composite = new Composite(this, SWT.NONE);
composite.setForeground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
composite.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
composite.setBounds(0, 0, 869, 80);
Button btnBack = new Button(composite, SWT.NONE);
btnBack.setText("Back");
btnBack.setBounds(10, 10, 75, 25);
btnBack.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
try {
((Control) Super).dispose();
new GuiListUsers(parent, style, name, Rs, Db);
} catch (Throwable e1) {
e1.printStackTrace();
}
}
});
Label labelMain_1 = new Label(composite, SWT.NONE);
labelMain_1.setText("Manage Users");
labelMain_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelMain_1.setFont(SWTResourceManager.getFont("Corbel", 20, SWT.NORMAL));
labelMain_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
labelMain_1.setBounds(342, 23, 229, 47);
Composite composite_1 = new Composite(this, SWT.NONE);
composite_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
composite_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_WIDGET_DARK_SHADOW));
composite_1.setBounds(0, 504, 869, 80);
Label labelSizing1 = new Label(this, SWT.NONE);
labelSizing1.setBounds(804, 542, 55, 15);
Label labelSizing2 = new Label(this, SWT.NONE);
labelSizing2.setBounds(10, 10, 55, 15);
String add1 = "admin", add2 ="employee";
this.pack();
this.setVisible(true);
Composite composite_2 = new Composite(this, SWT.NONE);
composite_2.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
composite_2.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
composite_2.setBounds(480, 86, 303, 361);
Label labelRemove = new Label(composite_2, SWT.NONE);
labelRemove.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelRemove.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelRemove.setBounds(87, 41, 118, 40);
labelRemove.setFont(SWTResourceManager.getFont("Segoe UI", 15, SWT.NORMAL));
labelRemove.setAlignment(SWT.CENTER);
labelRemove.setText("Remove");
Label labelId2 = new Label(composite_2, SWT.NONE);
labelId2.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelId2.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelId2.setBounds(62, 151, 45, 20);
labelId2.setText("ID");
inputIdRemove = new Text(composite_2, SWT.BORDER);
inputIdRemove.setBounds(128, 148, 112, 26);
Button btnRemove = new Button(composite_2, SWT.NONE);
btnRemove.setBounds(115, 275, 90, 30);
btnRemove.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String input2 = inputIdRemove.getText();
int i2 = Db.CheckValidId(input2);
try {
int flag = Rs.get_admin().rem_user(Db, i2, Rs);
if(flag == 0) {
JOptionPane.showMessageDialog(null, "Successfully removed id: " +i2);
clear("id2");
}else if(flag == 1) {
JOptionPane.showMessageDialog(null, "You can't delete yourself");
clear("id2");
}else if(flag == 2) {
JOptionPane.showMessageDialog(null, "Invalid id");
clear("id2");
}else if(flag == 3) {
JOptionPane.showMessageDialog(null, "ERROR");
}
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnRemove.setText("Remove");
Composite composite_2_1 = new Composite(this, SWT.NONE);
composite_2_1.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
composite_2_1.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
composite_2_1.setBounds(80, 86, 303, 361);
Combo selectRole = new Combo(composite_2_1, SWT.NONE);
selectRole.setBounds(155, 217, 100, 23);
selectRole.add(add1);
selectRole.add(add2);
Button btnAdd = new Button(composite_2_1, SWT.NONE);
btnAdd.setBounds(103, 273, 100, 30);
btnAdd.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String input1 = inputIdAdd.getText();
int i = Db.CheckValidId(input1);
String value = (String)selectRole.getText();
try {
int flag = Rs.get_admin().add_user(Db, value, i, inputName.getText().toString(), inputPassword.getText().toString());
if(flag == 0) {
JOptionPane.showMessageDialog(null, "Successfully added id: "+i);
clear("all");
}else if(flag == 1) {
JOptionPane.showMessageDialog(null, "This id is already being used");
clear("id1");
}else if(flag == 2) {
JOptionPane.showMessageDialog(null, "Invalid id");
clear("id1");
}else if(flag == 3) {
JOptionPane.showMessageDialog(null, "Invalid role");
selectRole.setText("");
}else {
JOptionPane.showMessageDialog(null, "ERROR");
}
} catch (Throwable e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnAdd.setText("Add");
Label labelName = new Label(composite_2_1, SWT.NONE);
labelName.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelName.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelName.setBounds(47, 150, 70, 20);
labelName.setText("Name");
Label labelPassword = new Label(composite_2_1, SWT.NONE);
labelPassword.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelPassword.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelPassword.setBounds(47, 185, 70, 20);
labelPassword.setText("Password");
Label labelRole = new Label(composite_2_1, SWT.NONE);
labelRole.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelRole.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelRole.setBounds(47, 217, 70, 20);
labelRole.setText("Role");
Label labelId = new Label(composite_2_1, SWT.NONE);
labelId.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelId.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelId.setBounds(47, 111, 70, 20);
labelId.setText("ID");
inputIdAdd = new Text(composite_2_1, SWT.BORDER);
inputIdAdd.setBounds(155, 108, 100, 26);
inputName = new Text(composite_2_1, SWT.BORDER);
inputName.setBounds(155, 147, 100, 26);
inputPassword = new Text(composite_2_1, SWT.BORDER);
inputPassword.setBounds(155, 182, 100, 26);
Label labelAdd = new Label(composite_2_1, SWT.NONE);
labelAdd.setBackground(SWTResourceManager.getColor(SWT.COLOR_GRAY));
labelAdd.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
labelAdd.setBounds(115, 28, 76, 40);
labelAdd.setFont(SWTResourceManager.getFont("Segoe UI", 15, SWT.NORMAL));
labelAdd.setAlignment(SWT.CENTER);
labelAdd.setText("Add");
Label labelLine = new Label(this, SWT.NONE);
labelLine.setText("______________");
labelLine.setFont(SWTResourceManager.getFont("Corbel", 16, SWT.NORMAL));
labelLine.setBounds(361, 461, 147, 40);
}
/**
* This method is used to clear the text boxes in the interface
* @param string : "all" clears all text boxes except the Id for
* remove box, "id1" clears only the Id for register box, "id2" clears
* only the Id for remove box
*/
protected void clear(String string) {
if(string.equals("all")){
inputName.setText("");
inputIdAdd.setText("");
inputPassword.setText("");
}
else if(string.equals("id1")) {
inputIdAdd.setText("");
}
else if(string.equals("id2")) {
inputIdRemove.setText("");
}
}
@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}
}
|
package com.kodilla.hibernate.invoice.dao;
import com.kodilla.hibernate.invoice.Invoice;
import com.kodilla.hibernate.invoice.Item;
import com.kodilla.hibernate.invoice.Product;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
@RunWith(SpringRunner.class)
@SpringBootTest
public class InvoiceDaoTestSuite {
@Autowired
private ProductDao productDao;
@Autowired
private ItemDao itemDao;
@Autowired
private InvoiceDao invoiceDao;
@Test
public void testInvoiceDaoSave() {
//Given
Product computerMouse1 = new Product("Gamer's mouse");
Product computerMouse2 = new Product("Gamer's mouse");
Product computerMouse3 = new Product("Gamer's mouse");
Product computerKeyboard3 = new Product("Ultraflat computer keyboard");
Product hardDrive2 = new Product("Hi-speed hard drive 10 000RPM");
Product product_ssd1 = new Product("Ultra capacity SSD drive");
Product product_ssd3 = new Product("Ultra capacity SSD drive");
Product lcdScreen1 = new Product("Frameless ultra flat hi-resolution LCD screen");
Product lcdScreen2 = new Product("Frameless ultra flat hi-resolution LCD screen");
Product multiCoreCpu2 = new Product("32-core, 128-thread, 5GHz universal purpose CPU from AMD");
Product graphicCard1 = new Product("Entry-level graphic card from AMD (8GB VRAM, 4096 cores)");
Product graphicCard3 = new Product("Entry-level graphic card from AMD (8GB VRAM, 4096 cores)");
Product spatialPrinter2 = new Product("Home use 3D printer to manufacture spare parts for daily use products");
Product spatialScanner1 = new Product("Home use 3D scanner for enthusiasts");
Product spatialScanner2 = new Product("Home use 3D scanner for enthusiasts");
Item scan1 = new Item(spatialScanner1, new BigDecimal(2399.0), 2);
Item graphic1 = new Item(graphicCard1, new BigDecimal(1300), 3);
Item ssd1 = new Item(product_ssd1, new BigDecimal(300), 8);
Item lcd1 = new Item(lcdScreen1, new BigDecimal(1699.95), 2);
Item mouse1 = new Item(computerMouse1, new BigDecimal(132), 4);
Item mouse2 = new Item(computerMouse2, new BigDecimal(131), 6);
Item printer2 = new Item(spatialPrinter2, new BigDecimal(3600), 1);
Item cpu2 = new Item(multiCoreCpu2, new BigDecimal(4500), 3);
Item hd2 = new Item(hardDrive2, new BigDecimal(1200), 6);
Item scan2 = new Item(spatialScanner2, new BigDecimal(2350), 2);
Item lcd2 = new Item(lcdScreen2, new BigDecimal(1680), 1);
Item keyb3 = new Item(computerKeyboard3, new BigDecimal(89), 5);
Item mouse3 = new Item(computerMouse3, new BigDecimal(131), 5);
Item graphic3 = new Item(graphicCard3, new BigDecimal(1300), 2);
Item ssd3 = new Item(product_ssd3, new BigDecimal(310), 6);
Invoice invoice1 = new Invoice("2019-01-00001");
invoice1.getItems().add(scan1);
invoice1.getItems().add(graphic1);
invoice1.getItems().add(ssd1);
invoice1.getItems().add(lcd1);
invoice1.getItems().add(mouse1);
Invoice invoice2 = new Invoice("2019-01-00234");
invoice2.getItems().add(mouse2);
invoice2.getItems().add(printer2);
invoice2.getItems().add(cpu2);
invoice2.getItems().add(hd2);
invoice2.getItems().add(scan2);
invoice2.getItems().add(lcd2);
Invoice invoice3 = new Invoice("2019-01-00375");
invoice3.getItems().add(keyb3);
invoice3.getItems().add(mouse3);
invoice3.getItems().add(graphic3);
invoice3.getItems().add(ssd3);
scan1.setInvoice(invoice1);
graphic1.setInvoice(invoice1);
ssd1.setInvoice(invoice1);
lcd1.setInvoice(invoice1);
mouse1.setInvoice(invoice1);
mouse2.setInvoice(invoice2);
printer2.setInvoice(invoice2);
cpu2.setInvoice(invoice2);
hd2.setInvoice(invoice2);
scan2.setInvoice(invoice2);
lcd2.setInvoice(invoice2);
keyb3.setInvoice(invoice3);
mouse3.setInvoice(invoice3);
graphic3.setInvoice(invoice3);
ssd3.setInvoice(invoice3);
//When
invoiceDao.save(invoice1);
int invoice1Id = invoice1.getId();
invoiceDao.save(invoice2);
int invoice2Id = invoice2.getId();
invoiceDao.save(invoice3);
int invoice3Id = invoice3.getId();
//Then
Assert.assertNotEquals(0, mouse1.getId());
Assert.assertNotEquals(0, keyb3.getId());
Assert.assertNotEquals(0, hd2.getId());
Assert.assertNotEquals(0, ssd1.getId());
Assert.assertNotEquals( ssd1.getId(), ssd3.getId());
Assert.assertNotEquals(0, invoice1Id);
Assert.assertNotEquals(0, invoice2Id);
Assert.assertNotEquals(0, invoice3Id);
//CleanUp
try {
invoiceDao.delete(invoice1Id);
invoiceDao.delete(invoice2Id);
invoiceDao.delete(invoice3Id);
} catch (Exception e) {
System.out.println("Sorry, unhandled exception occur.");
}
}
}
|
package com.komaxx.komaxx_gl.texturing;
import android.graphics.Bitmap;
import android.graphics.Rect;
import com.komaxx.komaxx_gl.MipMapBitmaps;
/**
* A TextureStrip is a texture that is automatically split up in
* separate rectangle chunks. Contains also logic to manage these
* "segments".
*
* @author Matthias Schicker
*/
public class TextureStrip extends Texture {
private final TextureStripConfig config;
private TextureStripper textureStripper;
// to be used during updates.
private MipMapBitmaps segmentTmpBmpHorizontal;
private MipMapBitmaps segmentTmpBmpVertical;
public TextureStrip(TextureStripConfig config) {
super(config);
this.config = config.clone();
computeTextureSize();
textureStripper = new TextureStripper(
this, new Rect(0,0,width,height), config.segmentWidth, config.segmentHeight, config.mayRotate);
}
@Override
public TextureStripConfig getConfig() {
return config;
}
private void computeTextureSize() {
switch (config.proportionsType){
case TextureStripConfig.PROPORTIONS_QUADRATIC:
computeQuadraticTextureSize();
break;
case TextureStripConfig.PROPORTIONS_COLUMN:
computeColumnTextureSize();
break;
case TextureStripConfig.PROPORTIONS_ROW:
computeRowTextureSize();
break;
default:
throw new RuntimeException("unknown texture strip proportions: " + config.proportionsType);
}
}
private void computeRowTextureSize() {
int nuSegmentHeight = findNextPowerOfTwo(config.segmentHeight);
height = config.segmentHeight = nuSegmentHeight;
int minWidth = config.segmentWidth * config.minSegmentCount;
if (minWidth > 2048) throw new RuntimeException("Can't create row texture with width > 2048");
width = findNextPowerOfTwo(minWidth);
}
private void computeColumnTextureSize() {
int nuSegmentWidth = findNextPowerOfTwo(config.segmentWidth);
width = config.segmentWidth = nuSegmentWidth;
int minHeight = config.segmentHeight * config.minSegmentCount;
if (minHeight > 2048) throw new RuntimeException("Can't create column texture with height > 2048");
height = findNextPowerOfTwo(minHeight);
}
private void computeQuadraticTextureSize() {
int tmpSize =
Math.max(findNextPowerOfTwo(config.minWidth),
findNextPowerOfTwo(config.minHeight));
while (computeSegmentCountQuadratic(tmpSize) < config.minSegmentCount){
tmpSize *=2;
}
width = height = tmpSize;
}
private int computeSegmentCountQuadratic(int tmpSize) {
int sWidth = config.segmentWidth;
int sHeight = config.segmentHeight;
if (sWidth > tmpSize || sHeight > tmpSize) return 0;
// horizontal
int segmentsPerColumn = tmpSize/sHeight;
int columns = tmpSize/sWidth;
int count = segmentsPerColumn * columns;
// vertical
int restX = tmpSize - (columns*sWidth);
segmentsPerColumn = tmpSize/sWidth;
columns = restX / sHeight;
count += columns*segmentsPerColumn;
return count;
}
public int getSegmentCount() {
return textureStripper.getSegmentCount();
}
/**
* Delivers the segment with the given id without side effects.
*/
public TextureSegment getSegment(short segmentId) {
return textureStripper.getSegment(segmentId);
}
/**
* Just delivers the segment in the strip whose last usage frame is longest ago.
*/
public TextureSegment getOldestSegment(){
return textureStripper.getOldestSegment();
}
public TextureSegment getSegment(int nuOwnerId, int frame){
TextureSegment ret = getOldestSegment();
ret.own(nuOwnerId, frame);
return ret;
}
@Override
public String toString() {
return "TextureStrip ("+width+"x"+height+") " + getSegmentCount() + " segments ("
+config.segmentWidth+"x"+config.segmentHeight+")";
}
/**
* removes the texture from the GL and frees all resources. GL thread only.
*/
@Override
public void delete() {
super.delete();
this.textureStripper = null;
if (segmentTmpBmpHorizontal != null){
segmentTmpBmpHorizontal.recycle();
segmentTmpBmpHorizontal = null;
}
if (segmentTmpBmpVertical != null){
segmentTmpBmpVertical.recycle();
segmentTmpBmpVertical= null;
}
}
public Bitmap createSegmentTmpBitmap() {
return Bitmap.createBitmap(config.segmentWidth, config.segmentHeight, getBitmapConfig());
}
}
|
/**
*
*/
package com.faac.occupancy.model;
/**
* @author nneikov
*
*/
public class Occupancy {
private String parkingId;
private int totalPlaces;
private int freeSpaces;
private String companyName;
public Occupancy() {
}
public Occupancy(String parkingId, int totalPlaces, int freeSpaces) {
this.parkingId = parkingId;
this.totalPlaces = totalPlaces;
this.freeSpaces = freeSpaces;
}
public String getParkingId() {
return parkingId;
}
public void setParkingId(String parkingId) {
this.parkingId = parkingId;
}
public int getTotalPlaces() {
return totalPlaces;
}
public void setTotalPlaces(int totalPlaces) {
this.totalPlaces = totalPlaces;
}
public int getFreeSpaces() {
return freeSpaces;
}
public void setFreeSpaces(int freeSpaces) {
this.freeSpaces = freeSpaces;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
}
|
package com.codependent.mutualauth;
/**
* Created by e076103 on 21-08-2018.
*/
public class CustomException extends RuntimeException {
public CustomException() {
super();
}
public CustomException(String message) {
super(message);
}
}
|
package org.hov.serviceimpl;
import org.hov.dao.TeamDAO;
import org.hov.model.Team;
import org.hov.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class TeamServiceImpl implements TeamService
{
@Autowired
TeamDAO teamDAO; //TeamDAOImpl Wired
@Override
public int addTeam(Team team)
{
return teamDAO.addTeam(team);
}
@Override
public boolean updateTeam(Team team)
{
return teamDAO.updateTeam(team);
}
@Override
public Team getTeamById(int teamId)
{
return teamDAO.getTeamById(teamId);
}
@Override
public boolean activateTeamById(int teamId)
{
return teamDAO.activateTeamById(teamId);
}
@Override
public boolean deactivateTeamById(int teamId)
{
return teamDAO.deactivateTeamById(teamId);
}
}
|
package KidneyExchange;
// Enumerate list of possible kidney types
public enum KidneyType {
A, B, C, D
}
|
import java.awt.*;
import java.awt.geom.*;
import java.awt.geom.Ellipse2D.Double;
import javax.swing.*;
public class ColorFrame implements Icon{
private int width;
private Color color;
public ColorFrame(int width) {
this.width = width;
this.color = Color.red;
}
public ColorFrame(int width, Color c) {
this.width = width;
this.color = c;
}
public int getIconWidth() {
return width;
}
public int getIconHeight() {
return width;
}
public void changeColor (Color c) {
color = c;
}
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D shape = (Graphics2D) g;
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, width, width);
shape.setColor(color);
shape.fill(circle);
shape.draw(circle);
}
public void repaint(Color c) {
this.color = c;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Color Changing Buttons");
ColorFrame circle = new ColorFrame(200);
JLabel label = new JLabel(circle);
frame.add(label);
JButton redButton = new JButton("Red");
redButton.addActionListener(event ->
{
circle.changeColor(Color.red);
label.repaint();
});
JButton greenButton = new JButton("Green");
greenButton.addActionListener(event ->
{
circle.changeColor(Color.green);
label.repaint();
});
JButton blueButton = new JButton("Blue");
blueButton.addActionListener(event ->
{
circle.changeColor(Color.blue);
label.repaint();
});
frame.setLayout(new FlowLayout());
frame.add(redButton);
frame.add(greenButton);
frame.add(blueButton);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
|
package eu.lsem.bakalarka.webfrontend.extensions.typeconverters;
import eu.lsem.bakalarka.dao.categories.CategoryDao;
import eu.lsem.bakalarka.dao.TagsDao;
import eu.lsem.bakalarka.model.Tag;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.TypeConverter;
import net.sourceforge.stripes.validation.ValidationError;
import net.sourceforge.stripes.validation.SimpleError;
import java.util.Locale;
import java.util.Collection;
public class TagTypeConverter implements TypeConverter<Tag> {
@SpringBean("tagsDao")
private TagsDao tagsDao;
public void setLocale(Locale locale) {
}
public Tag convert(String s, Class<? extends Tag> aClass, Collection<ValidationError> validationErrors) {
try {
return tagsDao.getTag(new Integer(s));
} catch (Exception e) {
validationErrors.add(new SimpleError("Chybny format."));
return null;
}
}
}
|
package nl.tim.aoc.day9;
import nl.tim.aoc.Challenge;
import nl.tim.aoc.Main;
import java.util.*;
public class Day9Challenge1 extends Challenge
{
private int players;
protected int end;
private LinkedList<Integer> game;
private HashMap<Integer, Long> score;
@Override
public void prepare() {
List<String> read = Main.readFile("9.txt");
game = new LinkedList<>();
score = new HashMap<>();
players = Integer.valueOf(read.get(0).split("\\s")[0]);
end = Integer.valueOf(read.get(0).split("\\s")[6]);
}
@Override
public Object run(String alternative) {
int currentPoint = 1;
int player = 0;
game.addFirst(0);
while (currentPoint <= end)
{
if (currentPoint % 23 == 0)
{
rot(-7);
score.put(player, score.getOrDefault(player, 0L) + currentPoint + game.removeFirst());
} else
{
rot(2);
game.addLast(currentPoint);
}
currentPoint += 1;
player += 1;
player %= players;
}
// 3443939356
// 408679
return Collections.max(score.values());
}
private void rot(int rotation)
{
if (rotation >= 0)
{
for (int i = 0; i < rotation; i++)
{
game.addFirst(game.removeLast());
}
} else
{
for (int i = 0; i < 0 - rotation - 1; i++)
{
game.addLast(game.removeFirst());
}
}
}
}
|
package com.pangpang6.utils.concurrent;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by jiangjg on 2017/5/27.
*/
public class ListConcurrent {
public static void main(String[] args) {
List<String> list = new CopyOnWriteArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
/*
int i = 0;
for(String item : list){
System.out.println(item);
if(i == 2){
list.remove(i);
}
i++;
}
*/
for(int j=0; j<list.size(); j++){
System.out.println(j + list.get(j));
if(j == 2){
System.out.println(list.get(j));
list.remove(j);
}
}
}
}
|
package br.com.acme.tasklist.controller;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import br.com.acme.tasklist.model.TaskList;
import br.com.acme.tasklist.service.TaskListService;
import br.com.acme.tasklist.service.TaskService;
@SpringBootTest
public class TaskListControllerTest {
@InjectMocks
TaskListController taskListController;
@Mock
TaskListService taskListService;
@Mock
TaskService taskService;
TaskList taskList;
@BeforeEach
public void init() {
taskList = new TaskList(1, "Task List #1");
}
@Test
public void testSaveTaskList() {
when(taskListService.save(taskList)).thenReturn(taskList);
ResponseEntity<TaskList> responseEntity = taskListController.saveTaskList(taskList);
assertTrue(taskList.toString().equals(responseEntity.getBody().toString()));
}
@Test
public void testSaveTaskWithoutTaskListData() {
taskList = new TaskList();
ResponseEntity<TaskList> responseEntity = taskListController.saveTaskList(taskList);
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(400);
}
@Test
public void testDeleteTaskList() {
when(taskListService.getById(taskList.getId())).thenReturn(Optional.of(taskList));
ResponseEntity responseEntity = taskListController.deleteTaskList(taskList.getId());
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(200);
}
@Test
public void testDeleteNonExistentTaskList() {
when(taskListService.getById(taskList.getId())).thenReturn(Optional.empty());
ResponseEntity responseEntity = taskListController.deleteTaskList(taskList.getId());
assertThat(responseEntity.getStatusCodeValue()).isEqualTo(400);
}
@Test
public void testGetAllTaskLists() {
List<TaskList> list = new ArrayList<TaskList>();
list.add(taskList);
when(taskListService.getAllTaskLists()).thenReturn(list);
ResponseEntity<List<TaskList>> responseEntity = taskListController.getAllTaskLists();
assertThat(responseEntity.getBody().toString()).isEqualTo(list.toString());
}
}
|
package org.cheng.login.activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.cheng.login.R;
import org.cheng.login.entity.Contact;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
@ContentView(R.layout.activity_minute)
public class MinuteActivity extends Activity implements View.OnClickListener{
//TextView控件初始化
@ViewInject(R.id.minute_tv_name)
private TextView minute_tv_name;
@ViewInject(R.id.minute_tv_tel)
private TextView minute_tv_tel;
@ViewInject(R.id.minute_tv_gender)
private TextView minute_tv_gender;
@ViewInject(R.id.minute_tv_email)
private TextView minute_tv_email;
@ViewInject(R.id.minute_tv_section)
private TextView minute_tv_section;
@ViewInject(R.id.minute_tv_post)
private TextView minute_tv_post;
//复制按钮初始化
@ViewInject(R.id.minute_img_name)
private ImageView minute_img_name;
@ViewInject(R.id.minute_img_post)
private ImageView minute_img_post;
@ViewInject(R.id.minute_img_section)
private ImageView minute_img_section;
@ViewInject(R.id.minute_img_tel)
private ImageView minute_img_tel;
@ViewInject(R.id.minute_img_gender)
private ImageView minute_img_gender;
@ViewInject(R.id.minute_img_email)
private ImageView minute_img_email;
//全选相对布局初始化
@ViewInject(R.id.minute_re_copyall)
private RelativeLayout minute_re_copyall;
private Contact contact;
private Toast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InStan();
contact=(Contact) getIntent().getSerializableExtra("contact");
minute_tv_name.setText(contact.getName());
minute_tv_post.setText(contact.getPost());
minute_tv_section.setText(contact.getSection());
minute_tv_tel.setText(contact.getTel());
minute_tv_gender.setText(contact.getGender());
minute_tv_email.setText(contact.getEmail());
}
private void InStan() {
x.view().inject(this);
//设置点击事件
minute_img_name.setOnClickListener(this);
minute_img_post.setOnClickListener(this);
minute_img_section.setOnClickListener(this);
minute_img_tel.setOnClickListener(this);
minute_img_gender.setOnClickListener(this);
minute_img_email.setOnClickListener(this);
minute_re_copyall.setOnClickListener(this);
}
public void copy(String content, Context context) {
// 得到剪贴板管理器
ClipboardManager cmb = (ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
cmb.setText(content.trim());
showInfo("复制成功!");
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.minute_img_name:
copy(minute_tv_name.getText().toString(),MinuteActivity.this);
break;
case R.id.minute_img_post:
copy(minute_tv_post.getText().toString(),MinuteActivity.this);
break;
case R.id.minute_img_section:
copy(minute_tv_section.getText().toString(),MinuteActivity.this);
break;
case R.id.minute_img_tel:
copy(minute_tv_tel.getText().toString(),MinuteActivity.this);
break;
case R.id.minute_img_gender:
copy(minute_tv_gender.getText().toString(),MinuteActivity.this);
break;
case R.id.minute_img_email:
copy(minute_tv_email.getText().toString(),MinuteActivity.this);
break;
case R.id.minute_re_copyall:
copy(contact.toString(),MinuteActivity.this);
break;
}
}
private void showInfo(String msg){
if (mToast != null) {
mToast.setText(msg);
mToast.setDuration(Toast.LENGTH_SHORT);
} else {
mToast = Toast.makeText(MinuteActivity.this, msg, Toast.LENGTH_SHORT);
}
mToast.show();
}
}
|
package com.tencent.mm.plugin.appbrand.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import com.tencent.mm.plugin.appbrand.jsapi.base.e;
import com.tencent.mm.plugin.appbrand.widget.g.a;
@SuppressLint({"AppCompatCustomView"})
public class f extends TextView implements e {
private a gEC;
private boolean gEe;
public f(Context context) {
super(context);
super.setIncludeFontPadding(false);
super.setLineSpacing(0.0f, 1.0f);
super.setSpannableFactory(new 1(this));
}
public void setLineHeight(int i) {
if (this.gEC == null) {
this.gEC = new a((float) i);
}
if (this.gEC.af((float) i)) {
invalidate();
}
}
public void setText(CharSequence charSequence, BufferType bufferType) {
if (bufferType == BufferType.NORMAL) {
bufferType = BufferType.SPANNABLE;
}
super.setText(charSequence, bufferType);
}
public void setInterceptEvent(boolean z) {
this.gEe = z;
}
public final boolean ail() {
return this.gEe;
}
}
|
/**
* @ClassName: MessageHandleServiceImpl
* @Description: TODO
* @author: cc
* @date: 2018年8月18日 上午11:48:28
*
*/
package cc.feefox.wechat.message.service.impl;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cc.feefox.wechat.common.result.WeChatResult;
import cc.feefox.wechat.common.util.MessageUtil;
import cc.feefox.wechat.message.model.BaseMessage;
import cc.feefox.wechat.message.model.NewsMessage;
import cc.feefox.wechat.message.service.interfaces.CodeHandleService;
import cc.feefox.wechat.message.service.interfaces.MessageHandleService;
/**
* @Package: cc.feefox.wechat.message.service.impl
* @author: cc
* @date: 2018年8月18日 上午11:48:28
*/
@Service
public class MessageHandleServiceImpl implements MessageHandleService {
private static final Logger logger = LoggerFactory.getLogger(MessageHandleServiceImpl.class);
@Autowired
private CodeHandleService codeHandleService;
/*
* 对来自微信的消息作出响应(包含消息和事件)
*
* @param inputStream
*
* @return
*
* @throws Exception
*/
@Override
public String handleMessage(Map<String, String> params) throws Exception {
logger.info("开始处理【message】信息");
String result = null;
if (params != null && params.size() > 0) {
BaseMessage msgInfo = new BaseMessage();
String createTime = params.get("CreateTime");
String msgId = params.get("MsgId");
msgInfo.setCreateTime((createTime != null && !"".equals(createTime)) ? Integer.parseInt(createTime) : 0);
msgInfo.setFromUserName(params.get("FromUserName"));
msgInfo.setMsgId((msgId != null && !"".equals(msgId)) ? Long.parseLong(msgId) : 0);
msgInfo.setToUserName(params.get("ToUserName"));
WeChatResult resp = codeHandleService.handleCode(params, msgInfo);
if (null == resp) {
// String str = "<xml>\r\n" + " <ToUserName><![CDATA[oWnU700PB2HTtgzReJva2GzPmp0E]]></ToUserName>\r\n"
// + " <FromUserName><![CDATA[gh_23ba766d4f8c]]></FromUserName>\r\n"
// + " <CreateTime><![CDATA[1534324363936]]></CreateTime>\r\n"
// + " <MsgType><![CDATA[news]]></MsgType>\r\n" + " <FuncFlag><![CDATA[0]]></FuncFlag>\r\n"
// + " <ArticleCount><![CDATA[2]]></ArticleCount>\r\n" + " <Articles>\r\n" + " <item>\r\n"
// + " <Title><![CDATA[飞狐互动:feefox]]></Title>\r\n"
// + " <Description><![CDATA[欢迎关注我的个人博客<a href=\"http://118.25.62.232/images/showreel.jpg\">图片</a><a href=\"http://118.25.62.232/images/showreel.jpg\">图片</a>]]></Description>\r\n"
// + " <PicUrl><![CDATA[http://118.25.62.232/images/showreel.jpg]]></PicUrl>\r\n"
// + " <Url><![CDATA[http://118.25.62.232/apple/]]></Url>\r\n" + " </item>\r\n"
// + " <item>\r\n" + " <Title><![CDATA[飞狐互动:feefox]]></Title>\r\n"
// + " <Description><![CDATA[欢迎关注我的个人博客<a href=\"http://118.25.62.232/images/showreel.jpg\">图片</a><a href=\"http://118.25.62.232/images/showreel.jpg\">图片</a>]]></Description>\r\n"
// + " <PicUrl><![CDATA[http://118.25.62.232/images/showreel.jpg]]></PicUrl>\r\n"
// + " <Url><![CDATA[http://118.25.62.232/apple/]]></Url>\r\n" + " </item>\r\n"
// + " </Articles>\r\n" + "</xml>";
// return str;
return null;
}
if (3 == resp.getType()) {
String str = "<xml>\n" + " <ToUserName><![CDATA[ou0pTwM2io_lD0ihQOywTSFSqwTU]]></ToUserName>\n"
+ " <FromUserName><![CDATA[fromuser]]></FromUserName>\n"
+ " <CreateTime>1399197672</CreateTime>\n"
+ " <MsgType><![CDATA[transfer_customer_service]]></MsgType>\n" + " </xml>";
if (str.contains("fromuser")) {
str.replace("fromuser", resp.getObject().toString());
}
return str;
}
boolean success = resp.isSuccess(); // 如果 为true,则表示返回xml文件, 直接转换即可,否则按类型
if (success) {
result = resp.getObject().toString();
} else {
int type = resp.getType(); // 这里规定 1 图文消息 否则直接转换
if (type == WeChatResult.NEWSMSG) {
NewsMessage message = (NewsMessage) resp.getObject();
result = MessageUtil.newsMessagegToXml(message);
return result;
} else {
BaseMessage baseMessage = (BaseMessage) resp.getObject();
result = MessageUtil.baseMessageToXml(baseMessage);
return result;
}
}
} else {
result = "msg is wrong";
}
return result;
}
}
|
package com.jaxrs.calcApp;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.Produces;
@Path("calc")
public class RestCalculator {
@GET
@Path("/addition/{a}/{b}")
@Produces(MediaType.TEXT_PLAIN)
public String addPlainText(@PathParam("a") Double a,
@PathParam("b") Double b) {
//System.out.println("Value of A: "+a);
//System.out.println(("Value of B is: "+b));
return a + b + "";
}
@GET
@Path("/addition/{a}/{b}")
@Produces(MediaType.TEXT_XML)
public String addition(@PathParam("a") Double a, @PathParam("b") Double b)
{
Double aval = a;
Double bval = b;
return "<addition>"+
"<a>" + aval + "</a>"
+ "<b>" + bval + "</b>"
+ "<result>" + (aval+bval) + "</result>"
+ "</addition>";
}
}
|
package pe.egcc.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import pe.egcc.eureka.service.PartidaService;
public class ListaRegistros {
public List<Map<String, ?>> getItems() {
// Proceso
PartidaService partidaService;
partidaService = new PartidaService();
List<Map<String, ?>> lista = partidaService.listarTipoRegistos();
return lista;
}
}
|
package com.tencent.mm.plugin.wear.model.e;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.e.b.g;
import com.tencent.mm.e.c.d;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.wear.model.a;
import com.tencent.mm.plugin.wear.model.d.c;
import com.tencent.mm.protocal.c.cfe;
import com.tencent.mm.protocal.c.cff;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.aa;
import com.tencent.qqpinyin.voicerecoapi.c$a;
import java.util.LinkedList;
public final class p implements e {
public static final String pJW = (aa.duN + "tmp_wearvoicetotext.spx");
public boolean ceW = false;
public LinkedList<Integer> ftL = new LinkedList();
public c pJX;
public com.tencent.qqpinyin.voicerecoapi.c pJY;
public d pJZ;
private int pKa = 0;
public int pKb;
public int pKc;
public final void reset() {
x.i("MicroMsg.Wear.VoiceToTextServer", "reset: sessionId=%s", new Object[]{Integer.valueOf(this.pKb)});
if (this.pJZ != null) {
this.pJZ.wA();
this.pJZ = null;
x.i("MicroMsg.Wear.VoiceToTextServer", "reset speexWriter");
}
if (this.pJY != null) {
this.pJY.stop();
this.pJY = null;
x.i("MicroMsg.Wear.VoiceToTextServer", "reset voiceDetectAPI");
}
if (this.pJX != null) {
this.pJX.eoE = true;
au.DF().b(349, this);
au.DF().c(this.pJX);
this.pJX = null;
}
this.pKc = 0;
this.ceW = false;
this.pKa = 0;
this.pKb = -1;
this.ftL.clear();
}
public final void a(int i, int i2, String str, l lVar) {
if (lVar instanceof c) {
c cVar = (c) lVar;
cff cff;
if (i != 0 || i2 != 0) {
au.DF().b(349, this);
cff = new cff();
cff.szk = cVar.talker;
cff.rBM = "";
cff.qZk = -1;
cff.szO = false;
a.bSl().pIS.a(new a(this, cVar.mFO, cff));
} else if (cVar.pJN) {
au.DF().b(349, this);
cff = new cff();
cff.szk = cVar.talker;
if (bi.oW(cVar.pJM)) {
cff.rBM = "";
cff.qZk = -1;
cff.szO = false;
} else {
x.i("MicroMsg.Wear.VoiceToTextServer", "receive text: %s", new Object[]{cVar.pJM});
cff.rBM = cVar.pJM;
cff.qZk = 0;
cff.szO = true;
}
a.bSl().pIS.a(new a(this, cVar.mFO, cff));
}
}
}
public final void a(int i, cfe cfe) {
if (cfe.rdU == null) {
x.i("MicroMsg.Wear.VoiceToTextServer", "voice data is null");
return;
}
byte[] toByteArray = cfe.rdU.toByteArray();
this.pKa += this.pJZ.a(new g.a(toByteArray, cfe.rvV), 0, false);
x.i("MicroMsg.Wear.VoiceToTextServer", "write bytes: %d", new Object[]{Integer.valueOf(this.pKa)});
short[] sArr = new short[(cfe.rvV / 2)];
for (int i2 = 0; i2 < cfe.rvV / 2; i2++) {
sArr[i2] = (short) ((toByteArray[i2 * 2] & 255) | (toByteArray[(i2 * 2) + 1] << 8));
}
c$a c_a = new c$a();
this.pJY.a(sArr, cfe.rvV / 2, c_a);
x.i("MicroMsg.Wear.VoiceToTextServer", "state.vad_flag: " + c_a.vgN);
if (c_a.vgN == 2) {
this.pKc = 1;
} else if (c_a.vgN == 3) {
this.pKc = 2;
}
if (this.pKc != 0) {
if (this.pKc < 0) {
if (this.ftL.size() > 10) {
this.ftL.removeLast();
}
this.ftL.addFirst(Integer.valueOf(i));
}
if (this.pKc == 1) {
cff cff = new cff();
cff.szk = this.pJX.talker;
cff.rBM = "";
cff.qZk = this.pKc;
cff.szO = true;
a.bSl().pIS.a(new a(this, this.pJX.mFO, cff));
this.pKc = 0;
}
}
if (!this.ceW && this.pKa > 3300) {
this.ceW = true;
au.DF().a(this.pJX, 0);
}
}
}
|
package io.eodc.ripple.activities;
import android.annotation.SuppressLint;
import android.content.AsyncQueryHandler;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.Telephony;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.telephony.SmsMessage;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import io.eodc.ripple.BuildConfig;
import io.eodc.ripple.R;
import io.eodc.ripple.TextMessage;
import io.eodc.ripple.adapters.MessageHistoryAdapter;
import timber.log.Timber;
public class ConversationActivity extends AppCompatActivity {
private static final int INBOX_TOKEN = 0;
private static final int SENT_TOKEN = 1;
private BroadcastReceiver newSmsReceiver;
ConstraintLayout mMessageComposer;
RelativeLayout mComposerLayout;
EditText mMessageComposerInput;
ImageView mSendButton;
TextView mJumpRecents;
ImageView mAttachIcon;
RecyclerView conversationMsgs;
MessageHistoryAdapter adapter;
List<TextMessage> messages;
@Override
protected void onCreate(Bundle savedInstanceState) {
// Setup Activity Basics
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
if (!Telephony.Sms.getDefaultSmsPackage(this).equals(getPackageName())) {
Intent intent = new Intent(Telephony.Sms.Intents.ACTION_CHANGE_DEFAULT);
intent.putExtra(Telephony.Sms.Intents.EXTRA_PACKAGE_NAME, getPackageName());
startActivity(intent);
}
mAttachIcon = findViewById(R.id.attach_icon);
mMessageComposer = findViewById(R.id.msg_composer);
mMessageComposerInput = findViewById(R.id.message_composer_input);
mJumpRecents = findViewById(R.id.jump_recents);
mComposerLayout = findViewById(R.id.new_message_container);
mSendButton = findViewById(R.id.send_button);
conversationMsgs = findViewById(R.id.conversation_msgs);
if (savedInstanceState == null) {
messages = new ArrayList<>();
final List<Long> msgDates = new ArrayList<>();
@SuppressLint("HandlerLeak")
AsyncQueryHandler queryHandler = new AsyncQueryHandler(this.getContentResolver()) {
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
int bodyIndex = cursor.getColumnIndex(Telephony.Sms.BODY);
int dateIndex = cursor.getColumnIndex(Telephony.Sms.DATE);
while (cursor.moveToNext()) {
TextMessage newMsg = new TextMessage(cursor.getString(bodyIndex), cursor.getLong(dateIndex));
if (token == INBOX_TOKEN) {
messages.add(newMsg);
msgDates.add(newMsg.getDate());
} else if (token == SENT_TOKEN) {
newMsg.setFromUser();
int index = Math.abs(Collections.binarySearch(msgDates, newMsg.getDate(), Collections.reverseOrder()) + 1);
msgDates.add(index, newMsg.getDate());
messages.add(index, newMsg);
}
}
}
};
queryHandler.startQuery(INBOX_TOKEN,
null,
Telephony.Sms.Inbox.CONTENT_URI,
new String[]{Telephony.Sms.ADDRESS,
Telephony.Sms.BODY,
Telephony.Sms.DATE},
Telephony.Sms.ADDRESS + "= ?",
new String[]{""},
Telephony.Sms.DEFAULT_SORT_ORDER);
queryHandler.startQuery(SENT_TOKEN,
null,
Telephony.Sms.Sent.CONTENT_URI,
new String[]{Telephony.Sms.ADDRESS,
Telephony.Sms.BODY,
Telephony.Sms.DATE},
Telephony.Sms.ADDRESS + "= ?",
new String[]{""},
Telephony.Sms.DEFAULT_SORT_ORDER);
} else {
String savedMsgContent = savedInstanceState.getString("savedMsgContent");
messages = savedInstanceState.getParcelableArrayList("messageList");
if (savedMsgContent != null)
mMessageComposerInput.setText(savedMsgContent);
}
// Plant Timber tree if debug build
if (BuildConfig.DEBUG)
Timber.plant(new Timber.DebugTree());
// Initialize UI
Toolbar mToolbar = findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Timber.i("Toolbar initialized");
newSmsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
Object[] pdus = (Object[]) extras.get("pdus");
for (Object pdu : pdus) {
SmsMessage newMsg = SmsMessage.createFromPdu((byte[]) pdu);
addMessageToList(new TextMessage(newMsg.getMessageBody(), System.currentTimeMillis()));
}
}
}
};
LinearLayoutManager rvLayoutMan = new LinearLayoutManager(this);
rvLayoutMan.setReverseLayout(true);
rvLayoutMan.setStackFromEnd(true);
conversationMsgs.setLayoutManager(rvLayoutMan);
adapter = new MessageHistoryAdapter(messages, this);
conversationMsgs.setAdapter(adapter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(newSmsReceiver);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(newSmsReceiver, filter);
conversationMsgs.scrollToPosition(0);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("savedMsgContent", mMessageComposerInput.getText().toString());
outState.putParcelableArrayList("messageList", (ArrayList<TextMessage>) messages);
super.onSaveInstanceState(outState);
}
public void addMessageToList(TextMessage newMsg) {
messages.add(0, newMsg);
adapter.notifyDataSetChanged();
}
public void scrollToPresent(View view) {
LinearLayoutManager layoutManager = (LinearLayoutManager) conversationMsgs.getLayoutManager();
int currentPosition = layoutManager.findFirstCompletelyVisibleItemPosition();
if (currentPosition < 75)
conversationMsgs.smoothScrollToPosition(0);
else
conversationMsgs.scrollToPosition(0);
showComposer();
}
private void showComposer() {
mMessageComposer.animate()
.setDuration(100)
.translationY(0);
mJumpRecents.startAnimation(AnimationUtils.loadAnimation(this, R.anim.collapse_recents_notif));
mJumpRecents.postOnAnimation(new Runnable() {
@Override
public void run() {
mJumpRecents.setVisibility(View.INVISIBLE);
}
});
}
}
|
package spi.movieorganizer.controller.tmdb;
import spi.movieorganizer.data.collection.CollectionDM;
import spi.movieorganizer.data.movie.MovieDM;
public class TMDBRequestResult {
public static enum TMDBRequestType {
Movies,
Collections;
}
private MovieDM movieDM;
private CollectionDM collectionDM;
public void setMovieDM(final MovieDM movieDM) {
this.movieDM = movieDM;
}
public void setCollectionDM(final CollectionDM collectionDM) {
this.collectionDM = collectionDM;
}
public MovieDM getMovieDM() {
return this.movieDM;
}
public CollectionDM getCollectionDM() {
return this.collectionDM;
}
}
|
package com.jst.mapper;
import java.util.List;
import com.jst.model.Sys_function;
/**
* @author Administrator
*
*/
public interface Sys_PermissionMapper {
//通过角色查询权限
// List<Permission> selectById(int id);
//查询所有权限
List<Sys_function> listAll();
// //查询菜单权限
// List<Permission> listAllById(int id);
// //添加权限
// void insertPermission(Permission permission);
// //根据用户查询生成菜单的所有权限
// List<Permission> queryById(int id);
//根据角色id删除所有权限
void deleteById(int rid);
}
|
package lotto.step3.domain;
public class LottoShop {
public Lotteries receiveMoney(int money) {
new Money(money);
return new Lotteries(money / Money.LOTTO_PRICE);
}
}
|
package dominio;
import java.util.HashMap;
/**
* Una de las posibles razas de personajes que el jugador puede elegir La cual
* posee sus propias habilidades
*/
public class Orco extends Personaje {
/**
*/
private static final long serialVersionUID = 1L;
private static final int ENERGIAMINIMA = 10;
private static final int SALUDEXTRA = 10;
/**
* crea un personaje de raza "Orco" con nombre y casta enviados por
* parametro
* @param nombre Nombre del Personaje
* @param casta Clase Casta
* @param id ID del personaje
*/
public Orco(final String nombre, final Casta casta, final int id) {
super(nombre, casta, id);
}
/**
* crea un personaje de raza orco con todas sus caracteristicas enviadas por
* parametro (nombre, saluda, energia, fuerza, etc)
* @param nombre Nombre del Personaje
* @param salud Cantidad de salud
* @param energia Cantidad de energia
* @param fuerza Cantidad de fuerza
* @param destreza Cantidad de destreza
* @param inteligencia Cantidad de inteligencia
* @param casta Clase Casta
* @param experiencia Cantidad de experiencia
* @param nivel Cantidad de nivel
* @param idPersonaje ID del personaje
*/
public Orco(final String nombre, final int salud, final int energia,
final int fuerza, final int destreza, final int inteligencia,
final Casta casta, final int experiencia, final int nivel,
final int idPersonaje) {
super(nombre, salud, energia, fuerza, destreza, inteligencia,
casta, experiencia, nivel, idPersonaje);
}
/**
* permite el uso de la habilidad "Golpe Defensa" propia de la raza "orco" y
* establece sus efectos y condicion de uso
* @param atacado Es el recibe el danio
* @param random Numero random de evitar el danio
* @return true Si se puede utilizar la habilidad del Golpe Defensa
*/
public boolean habilidadRaza1(final Peleable atacado, final RandomGenerator random) {
HashMap<String, Integer> mapa = new HashMap<String, Integer>();
if (this.getEnergia() > ENERGIAMINIMA) {
mapa.put("energia", this.getEnergia() - ENERGIAMINIMA);
this.actualizar(mapa);
if (atacado.serAtacado(this.getDefensa() * 2, random) > 0) {
return true;
}
return true;
}
return false;
}
/**
* permite el uso de la habilidad "Mordisco de vida" propia de la raza
* "orco" y establece sus efectos y condicion de uso
* @param atacado Es el recibe el danio
* @param random Numero random de evitar el danio
* @return true Si se puede utilizar la habilidad del Mordisco de vida
*/
public boolean habilidadRaza2(final Peleable atacado, final RandomGenerator random) {
HashMap<String, Integer> mapa = new HashMap<String, Integer>();
if (this.getEnergia() > ENERGIAMINIMA) {
mapa.put("energia", this.getEnergia() - ENERGIAMINIMA);
this.actualizar(mapa);
int danioCausado = atacado.serAtacado(this.getFuerza(), random);
if (danioCausado > 0) {
this.serCurado(danioCausado);
return true;
}
}
return false;
}
@Override
public final int getSALUDEXTRA() {
return SALUDEXTRA;
}
@Override
public final int getENERGIAEXTRA() {
return 0;
}
@Override
public final String getNombreRaza() {
return "Orco";
}
@Override
public final String[] getHabilidadesRaza() {
return new String[] {"Golpe Defensa", "Mordisco de Vida" };
}
}
|
package com.innodox.library.controller;
import com.innodox.library.dataobject.UserModel;
import com.innodox.library.entity.User;
import com.innodox.library.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.logging.Logger;
@RequestMapping("/api")
@Component
@RestController
public class LoginContorller {
private static final Logger logger = Logger.getLogger(LoginContorller.class.getName());
private UserService userService;
@Autowired
public LoginContorller(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/loggingout", method = RequestMethod.GET)
public ResponseEntity<String> logout() {
// logger.info("ActualUser: " + SecurityContextHolder.getContext().getAuthentication().getName());
SecurityContextHolder.clearContext();
return new ResponseEntity<>("Logged out", HttpStatus.OK);
}
@RequestMapping(value = "/getactualuser", method = RequestMethod.GET)
public ResponseEntity<UserModel> getActualUser() {
// logger.info(SecurityContextHolder.getContext().getAuthentication().getName());
UserModel actualUser = userService.getActualUser();
return new ResponseEntity<>(actualUser, HttpStatus.OK);
}
@GetMapping("/ping")
public String getPing() {
return "OK";
}
}
|
package com.microsilver.mrcard.basicservice.config;
public class AlipayConfig {
// 1.商户appid
public static String APPID = "2018050860119126";
// 2.支付宝公钥
public static String ALIPAY_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnuw1rHyFT4T3kfl1I7C4REIbm1fS/Vui3fV4flthlXjBUhPAZ9gFNM66AqC7HYWAbjlKH28Pnu0Pez2iMy56F3EsSaE/VlqGVqHtqwyGRHUE+fi0hyIQtDk3UXsx46MffuvABoUKDc7YPEG4ExnE1aYnYGf2+Tb/5OAbkCbJKedp7vvxK/4uuD6op77g94SnrpcvQjmWq30W1dU8CK3Lfu0Wmy0QB4tQTvOJ7W3dS3oSz2WoW7c01yo1pIse/hOE9sO35vwVt7NLU4j28NC2uGYyOoD+nKLV9FI9vLmIUfPQSnuSKa9rl/i0DKWJL9fmhfc+FJOjFzpfNJD/ZLaZ0wIDAQAB";
// 3. 支付宝应用私钥
public static String ALIPAY_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDp80RmmzC6L+/I2Ak/hmQYT6XlbAnl6w0HHwdmf+BbQ3bmyhUTweYOhecd3b/+Huj2gP2jprylfX6+Gh89WiXDDXhEbZj4Nt0JektmvpxganyZFzq+2/NG5EHuwUPEwypIOfWD+4FuhfPnL1OnGLsIVZXlIxR9TyFukASs6bxElQF0bVrxy+dQz106s/Uj3e3SuwiprFj3zKG/Epcfy3sdv4VHgzJLmKQpiNciwOm6VzFmWxIEXfjZ+XlMQUsX29r8RYT0yKiimy+17y5ljiTcskAsix5yNSZB/rYTkKNptX2Gp1AyWHJHiUn5v2iAtgIx/EmV5X8xNTk5amYExXw9AgMBAAECggEAVn+aT7Gbb4ufxYuSx8kBozd3p/6tHjQs6fAgBVbMdhHYmXYoGtj7HW2GyTUe8m8tRU7l+KcCYtGmldUEreNxyM9nIy2+fC+UxBdSX5ekK8XTcar0DnM2XISyl/se+lYKgQ/k5bqM3XdreZO3AzYSmP9D36d7wOUMAFwBTolREa2tEUT8eInh+2xhvWVVvtsOM0O8GQs7UbjkO0ImUAylLkUNlUfcc4tT8bty50YfirymSUZafQNfGitz/FiI48jJV63EkysBUWPsWAi+H4LsfE11c3jQt97Nh8gPwvTWTN4/SVrd2froBDkPhZ2g1oKcJu78V1+6G4Vj7GvGbZxC5QKBgQD4oVjJQoQe/wGd7baZkggHrF1tDXfhyOJfgkMfNKgJlPI5+GoInchJTgw8cQySD1Nj8rSEPm+EpXZqCUO7tRniDIyKekDIphExfEwJJFO5uysfoyVoP1LkvOxhj9SETFCmNpPAB20exBR7hOCmEgycWxej9I1bZC+FbfyMSBDBQwKBgQDw4oaZgf7DLoX8+z9l26JPRJ0nAcCFiqNTckEvD3CufsX2sMcDKlMR+sFCZR5f4OTrvgrcNtn3m0ryhu2oRgOJjjTnJ+15JI5/HktRM9IcSDpan6pcZlcfGn8UjdQiDhRYSKBhrvEYQM/DWHhLqMkV865nSwcXPz7dXq0oULw0fwKBgEP/vMyuiHwBumt7DCnMKq4Oki61NEhoLKF6eukZ+atFNUptinJ41MJXujj9ojaAQopfYseYW9+ncU9m4UOBMGcGj5l//h/ia2lhWVpWuR9e9VhdwmlUiFNO6Ed2kuTsClKrMpWeclWrwv5VRSumXBSXRUvuIosQR37yqdOkEhEJAoGAf5m/azmtVn8iguwknTRHOm5CQRNwhEz4T4/Kb79iFU0aWJ80DL0y2+dU0HL4MBnVqfs1jYmQ1NTyUp6e7fCIlyk5ZOmFphJzWWsWwqEMv+aS4saJXADqTZOflae7o36J0GpIavZcyFgstnH65zk1q+c1j4ny66GZD3LDjwOVbskCgYEAs0CnuiazU+Wo4DrnSFHn9YMB19HyYYkBL1AVu7dWanuRf2Ooxpt0CRnYdOwRQQMbGO7xi/FC6ht6lqL5b7z/rgd5U2a9RT8ZwDo9tvAcOBXqm+Y60C0XBonMZZmpAbXxhX5oF0jnbQ6bSLvzGZW7kuC4NR2vWrkODhwOJ+TwJCM=";
// 4.服务器异步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
//public static String notify_url = "http://www.xxx.com/alipay/notify_url.do";
public static String notify_url = "http://211.149.164.182:8081/api/pay/notify";
// 5.页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 商户可以自定义同步跳转地址
public static String return_url = "http://211.149.164.182:8081/api/pay/notify";
// 6.请求网关地址
public static String URL = "https://openapi.alipay.com/gateway.do";
// 7.编码
public static String CHARSET = "UTF-8";
// 8.返回格式
public static String FORMAT = "json";
// 9.加密类型
public static String SIGNTYPE = "RSA2";
}
|
package com.example.administrator.comparision;
/**
* Created by Administrator on 2017/11/4.
*/
import android.graphics.drawable.Drawable;
public class AppInfo {
private Drawable image;
private String appName;
public AppInfo(Drawable image, String appName) {
this.image = image;
this.appName = appName;
}
public AppInfo() {
}
public Drawable getImage() {
return image;
}
public void setImage(Drawable image) {
this.image = image;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
}
|
package com.demo.LogicJob.Social;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.demo.LogicJob.Entity.AppUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.social.security.SocialUserDetails;
public class SocialUserDetailsImpl implements SocialUserDetails {
private static final long serialVersionUID = -5246117266247684905L;
private List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();
private AppUser appUser;
public SocialUserDetailsImpl(AppUser appUser, String roleNames) {
this.appUser = appUser;
GrantedAuthority authority = new SimpleGrantedAuthority(roleNames);
list.add(authority);
UserDetails userDetails = (UserDetails) new User(appUser.getUserName(), //
appUser.getEncrytedPassword(), list);
}
@Override
public String getUserId() {
return this.appUser.getUserId() + "";
}
@Override
public String getUsername() {
return appUser.getUserName();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return list;
}
@Override
public String getPassword() {
return appUser.getEncrytedPassword();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
|
package com.union.design.common.util;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class DiskUtilsTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void compress() throws IOException {
final String rootDir = "D:\\api";
final String sourceDir = "apache-ant-1.10.7";
final String snapshotArchive = sourceDir+".zip";
String outputFile = Paths.get(rootDir, snapshotArchive).toString();
final Checksum checksum = new CRC32();
DiskUtils.compress(rootDir,sourceDir,outputFile,checksum);
}
@Test
public void decompress() throws IOException {
final String readerPath = "D:\\api\\apache-ant-1.10.7.zip";
final String snapshotArchive = "apache-ant-1.10.7";
final String sourceFile = Paths.get("D:\\", snapshotArchive).toString();
final Checksum checksum = new CRC32();
DiskUtils.decompress(readerPath,sourceFile,checksum);
}
@Test
public void test(){
String permissionResource="private:.*:.*";
String Resource="private:*:config/1";
System.out.println(Pattern.matches(permissionResource, Resource));
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* 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 vanadis.core.reflection;
import vanadis.core.lang.VarArgs;
import java.lang.reflect.Method;
public final class GetNSet {
public static String getterName(String property) {
return "get" + upcased(property);
}
public static String booleanGetterName(String property) {
return "is" + upcased(property);
}
public static String setterName(String property) {
return "set" + upcased(property);
}
private static String upcased(String property) {
return property.substring(0, 1).toUpperCase() + property.substring(1);
}
public static String getNonBooleanProperty(Method method) {
return getNonBooleanProperty(method.getName());
}
public static String getProperty(Method method) {
return getProperty(method.getName());
}
public static String setProperty(Method method) {
return setProperty(method.getName());
}
public static String property(Method method) {
return property(method.getName());
}
public static String getNonBooleanProperty(String methodName) {
return resolveByPrefix(methodName, true, "get");
}
public static String getProperty(String methodName) {
return resolveByPrefix(methodName, true, "get", "is");
}
public static String setProperty(String methodName) {
return resolveByPrefix(methodName, true, "set");
}
public static String property(String methodName) {
return resolveByPrefix(methodName, true, "set", "get", "is");
}
public static String resolveByPrefix(String base, String... prefices) {
return resolveByPrefix(base, false, prefices);
}
public static String resolveByPrefix(String base, boolean downcase, String... prefices) {
if (VarArgs.present(prefices)) {
for (String prefix : prefices) {
String suffix = suffix(base, downcase, prefix);
if (suffix != null) {
return suffix;
}
}
}
return base;
}
private static String suffix(String base, boolean downcase, String prefix) {
int len = prefix.length();
if (base.length() > len && base.startsWith(prefix) && Character.isUpperCase(base.charAt(len))) {
String sub = base.substring(len);
return downcase ? sub.substring(0, 1).toLowerCase() + sub.substring(1) : sub;
}
return null;
}
private GetNSet() { }
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package repository;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author Elif
*/
@ManagedBean(name = "pageController")
@RequestScoped
public class PageController {
public String moveToFindUsersPage() {
return "findUsersPage?faces-redirect=true";
}
public String moveToMainPage() {
return "mainPage?faces-redirect=true";
}
public String moveToProfilePage() {
return "profilPage?faces-redirect=true";
}
public String moveToSettingsPage() {
return "settingsPage?faces-redirect=true";
}
public String moveToWorkAndEducationPage() {
return "workAndEducationPage?faces-redirect=true";
}
public String moveToIntroduceYourselfPage() {
return "introduceYourselfPage?faces-redirect=true";
}
public String moveToUsersFavoritePage() {
return "usersFavoritePage?faces-redirect=true";
}
public String moveToSeeInformationPage() {
return "seeInformationPage?faces-redirect=true";
}
public String moveToChatPage() {
return "chatPage?faces-redirect=true";
}
public String moveToFollowingPage() {
return "followingPage?faces-redirect=true";
}
public String moveToFollowersPage() {
return "followersPage?faces-redirect=true";
}
public String moveToChangePasswordPage() {
return "changePasswordPage?faces-redirect=true";
}
public String moveToNotificationsPage() {
return "notificationsPage?faces-redirect=true";
}
}
|
// Sun Certified Java Programmer
// Chapter 6, P482
// Strings, I/O, Formatting, and Parsing
import java.util.*;
class Tester482 {
public static void main(String[] args) {
//Locale(String language)
//Locale(String language, String country);
Locale locPT = new Locale("it"); // Italian
Locale locBR = new Locale("it", "CH"); // Switzerland
}
}
|
package com.kingcar.rent.pro.base;
import rx.Subscription;
/**
* 基础presenter
* Created by cwj
*/
public abstract class BasePresenter<T extends IBaseView> {
protected Subscription subscription;
protected T iView;
public BasePresenter(T iView) {
this.iView = iView;
}
public void release(){
if(subscription!=null){
subscription.unsubscribe();
}
}
}
|
package com.komaxx.komaxx_gl.scenegraph.basic_nodes;
import android.opengl.Matrix;
import com.komaxx.komaxx_gl.ICameraInfoProvider;
import com.komaxx.komaxx_gl.RenderContext;
import com.komaxx.komaxx_gl.SceneGraphContext;
import com.komaxx.komaxx_gl.math.MatrixUtil;
import com.komaxx.komaxx_gl.math.Vector;
import com.komaxx.komaxx_gl.scenegraph.Node;
import com.komaxx.komaxx_gl.scenegraph.interaction.InteractionContext;
import com.komaxx.komaxx_gl.scenegraph.interaction.InteractionEvent;
import com.komaxx.komaxx_gl.scenegraph.interaction.MotionEventHistory;
import com.komaxx.komaxx_gl.scenegraph.interaction.Pointer;
import com.komaxx.komaxx_gl.util.Interpolators;
/**
* This is a special simplified CameraNode that is suitable for list
* views. It aligns itself in such a way that in the z0 one pixel
* corresponds to exactly one virtual unit.
*
* @author Matthias Schicker
*/
public class ListCameraNode extends Node implements ICameraInfoProvider {
private static final long CAMERA_CENTER_DURATION_NS = 500000000L;
/**
* When the movement delta is smaller than this, no flinging is executed.
* (worldX per NS)
*/
private static final float MIN_FLING_SPEED = 0.00000001f;
private static final long FLING_DURATION_NS = 2000000000L;
private float fovAngleX = 40f; // degrees
protected float[] projectionMatrix = new float[MatrixUtil.MATRIX_SIZE];
protected float[] viewMatrix = new float[MatrixUtil.MATRIX_SIZE];
protected float[] invertedViewMatrix = new float[MatrixUtil.MATRIX_SIZE];
private float[] modelMatrix = new float[MatrixUtil.MATRIX_SIZE];
protected float[] eyePoint = new float[]{ 0f, 0f, 1234f };
protected float[] lookingDirection = new float[]{ 0f, 0f, -1f };
protected float[] upVector = new float[]{ 0f, 1f, 0f };
protected boolean pvMatrixDirty = true;
/**
* Whenever the perspective of the camera changes, this is increased. This way, nodes further
* down in the graph know that they may recompute stuff based on the new perspective.
*/
protected int worldChangeId = 0;
protected boolean interacting = false;
protected long lastInteractionTime = 0;
private MotionEventHistory moveEventHistory = new MotionEventHistory(15);
private Interpolators.Interpolator flingInterpolatorY;
private float scrollTopLimit = 0;
private float scrollBottomLimit = Integer.MIN_VALUE;
/**
* Caches the current viewProjection matrix
*/
protected float[] tmpPvMatrix = new float[MatrixUtil.MATRIX_SIZE];
protected float[] tmpInteractionCoordsNow;
protected float[] tmpInteractionCoordsLast;
protected float[] downTiltXY = new float[2];
// ///////////////////////////////////////
// tmps, caches
protected float[] tmpTargetPoint = new float[3];
protected float surfaceWidth = 0;
protected float surfaceHeight = 0;
protected float surfaceRatio = 0;
public ListCameraNode(){
Matrix.setIdentityM(modelMatrix, 0);
// just start with something that makes almost sense, will be corrected with the first frame.
Matrix.orthoM(projectionMatrix, 0, -1, 1, -1, 1, 1, 50);
recomputeViewMatrix();
transforms = true;
handlesInteraction = true;
}
public void setScrollLimits(float topLimit, float bottomLimit){
scrollTopLimit = topLimit;
scrollBottomLimit = bottomLimit;
sanitizeScrollLimits();
}
/**
* Ensures that no erratic behavior appears due to too short content
* or an erroneous "bottom > top".
*/
private void sanitizeScrollLimits() {
if (scrollTopLimit - scrollBottomLimit < surfaceHeight){
scrollBottomLimit = scrollTopLimit - surfaceHeight;
}
}
protected void recomputeViewMatrix() {
tmpTargetPoint = Vector.aPlusB3(tmpTargetPoint, eyePoint, lookingDirection);
Matrix.setLookAtM(viewMatrix, 0,
eyePoint[0], eyePoint[1], eyePoint[2],
tmpTargetPoint[0], tmpTargetPoint[1], tmpTargetPoint[2],
upVector[0], upVector[1], upVector[2]);
Matrix.translateM(viewMatrix, 0, -surfaceWidth/2, +surfaceHeight/2, 0);
Matrix.invertM(invertedViewMatrix, 0, viewMatrix, 0);
}
@Override
public boolean onTransform(SceneGraphContext sgContext) {
sgContext.setCameraInfoProvider(this);
// this ensures that interacting is reset to false when the interactionEvents were
// consumed elsewhere
if (interacting && sgContext.frameNanoTime - lastInteractionTime > 100000000) interacting = false;
if (!interacting) executeFlinging(sgContext);
if (pvMatrixDirty){
recomputePvMatrix();
worldChangeId++;
sgContext.setNotIdle();
}
// when the cam is hidden while interacting, the 'cancel' will never reach this node
// fallback to do it here.
if (!visible || !sgContext.visibilityStack.peek().b) interacting = false;
if (interacting){
worldChangeId++; // this avoids that other nodes perceive the state as idle
sgContext.setNotIdle();
}
sgContext.worldIdStack.push().add(worldChangeId);
float[] sgEyePoint = sgContext.eyePointStack.push();
Vector.set3(sgEyePoint, eyePoint[0]+surfaceWidth/2, eyePoint[1]-surfaceHeight/2, eyePoint[2]);
sgEyePoint[3] = 1;
float[] stackViewMatrix = sgContext.projectionViewMatrixStack.push();
System.arraycopy(tmpPvMatrix, 0, stackViewMatrix, 0, MatrixUtil.MATRIX_SIZE);
sgContext.setMvpMatrixDirty();
return true;
}
protected void executeFlinging(SceneGraphContext sgContext) {
long frameTime = sgContext.frameNanoTime;
pvMatrixDirty |= executeFlingingY(frameTime);
}
private boolean executeFlingingY(long frameTime) {
if (flingInterpolatorY == null) return false;
eyePoint[1] = flingInterpolatorY.getValue(frameTime);
if (eyePoint[1] > scrollTopLimit && flingInterpolatorY.getEndY() > eyePoint[1]){
// moving outside of the bounds -> clamp
eyePoint[1] = scrollTopLimit;
flingInterpolatorY = null;
} else if (eyePoint[1]-surfaceHeight < scrollBottomLimit && flingInterpolatorY.getEndY() < eyePoint[1]){
eyePoint[1] = scrollBottomLimit+surfaceHeight;
flingInterpolatorY = null;
} else if (frameTime > flingInterpolatorY.getEndX()) flingInterpolatorY = null;
return true;
}
protected void recomputePvMatrix() {
recomputeViewMatrix();
Matrix.multiplyMM(tmpPvMatrix, 0, projectionMatrix, 0, viewMatrix, 0);
pvMatrixDirty = false;
}
@Override
public void onUnTransform(SceneGraphContext sgContext) {
sgContext.eyePointStack.pop();
sgContext.worldIdStack.pop();
sgContext.projectionViewMatrixStack.pop();
sgContext.setMvpMatrixDirty();
}
@Override
protected void onSurfaceCreated(RenderContext renderContext) {
pvMatrixDirty = true;
}
@Override
public void onSurfaceChanged(RenderContext renderContext) {
surfaceWidth = renderContext.surfaceWidth;
surfaceHeight = renderContext.surfaceHeight;
surfaceRatio = surfaceWidth / surfaceHeight;
setFovAngle(fovAngleX);
sanitizeScrollLimits();
}
/**
* Adjust the horizontal FOV of the camera. The focus plane will not be changed, it's still
* the z=0 plane, so the camera distance will change! </br>
* Think <i>Hitchcock effect ;)</i> </br>
* <b>NOTE:</b> GL thread only.
* @param nuFovAngle the new angle in degrees
*/
public void setFovAngle(float nuFovAngle){
fovAngleX = nuFovAngle;
if (surfaceWidth == 0) return; // would fuck up the frustum!
float cameraDistance = (float) ((surfaceWidth/2f) / Math.tan(Math.toRadians(fovAngleX)));
eyePoint[2] = cameraDistance;
float NEAR_PLANE_DISTANCE_FACTOR = 0.5f;
float FAR_PLANE_DISTANCE_FACTOR = 10f;
float nearPlaneDistance = cameraDistance * NEAR_PLANE_DISTANCE_FACTOR;
float farPlaneDistance = cameraDistance * FAR_PLANE_DISTANCE_FACTOR;
Matrix.frustumM(projectionMatrix, 0,
- surfaceWidth/2 * NEAR_PLANE_DISTANCE_FACTOR, surfaceWidth/2 * NEAR_PLANE_DISTANCE_FACTOR,
- surfaceHeight/2 * NEAR_PLANE_DISTANCE_FACTOR, surfaceHeight/2 * NEAR_PLANE_DISTANCE_FACTOR,
nearPlaneDistance, farPlaneDistance);
pvMatrixDirty = true;
}
@Override
public void onTransformInteraction(InteractionContext ic) {
if (pvMatrixDirty) recomputePvMatrix();
throw new RuntimeException("Not implemented yet");
// InteractionEvent event = ic.getCurrentInteractionEvent();
// tmpInteractionCoordsNow = ic.currentRayPointCoords.push();
// computeInteractionPoints(tmpInteractionCoordsNow, event);
//
// InteractionEvent lastEvent = ic.getLastInteractionEvent();
// if (lastEvent != null){
// tmpInteractionCoordsLast = ic.lastRayPointCoords.push();
// computeInteractionPoints(tmpInteractionCoordsLast, lastEvent);
// }
}
@Override
public void onUnTransformInteraction(InteractionContext ic) {
for (int i = 0; i < InteractionContext.MAX_POINTER_COUNT; i++){
Pointer pointer = ic.getPointers()[i];
if (pointer.isActive()) pointer.popRayPoint();
}
}
@Override
public boolean onInteraction(InteractionContext interactionContext) {
throw new RuntimeException("Not implemented yet");
// lastInteractionTime = interactionContext.frameNanoTime;
// if (pvMatrixDirty) recomputePvMatrix();
// InteractionEvent event = interactionContext.getCurrentInteractionEvent();
// InteractionEvent lastEvent = interactionContext.getLastInteractionEvent();
// int pointerCount = event.getPointerCount();
//
// boolean ret = false;
//
// if (lastEvent != null && pointerCount == 1){
// move(interactionContext);
// pvMatrixDirty = true;
// }
//
// flingInterpolatorY = null;
//
// if (pointerCount == 1){
// if (event.getAction() == MotionEvent.ACTION_UP){
// computeFlinging(interactionContext);
// moveEventHistory.clear();
// } else if (event.getAction() == MotionEvent.ACTION_CANCEL){
// moveEventHistory.clear();
// }
// }
//
// // snap back to allowed area
// if (event.isUpOrCancel() && eyePoint[1] > scrollTopLimit){
// centerOnY(interactionContext, scrollTopLimit -interactionContext.getZBoundingBox().height()/2);
// } else if (event.isUpOrCancel() && eyePoint[1]-surfaceHeight < scrollBottomLimit){
// centerOnY(interactionContext, scrollBottomLimit + interactionContext.getZBoundingBox().height()/2);
// }
//
// interacting = !event.isUpOrCancel();
//
// return ret;
}
private void computeFlinging(InteractionContext interactionContext) {
// not outside of any boundaries -> continue the current movement
// compute the fling speed
long historyTime = 0;
float historyDistanceX = 0;
float historyDistanceY = 0;
long frameTime = interactionContext.frameNanoTime;
MotionEventHistory.HistoryMotionEvent historyEvent;
int historyCount = 0;
for (; historyCount < moveEventHistory.size(); historyCount++){
historyEvent = moveEventHistory.get(historyCount);
historyTime = frameTime - historyEvent.time;
historyDistanceX += historyEvent.x;
historyDistanceY += historyEvent.y;
if (historyTime > 200000000) break;
}
if (moveEventHistory.size() >= 2 && historyTime > 0){
double xFlingSpeed = (double)historyDistanceX/(double)historyTime;
double yFlingSpeed = (double)historyDistanceY/(double)historyTime;
if (Math.abs(xFlingSpeed) > MIN_FLING_SPEED
|| Math.abs(yFlingSpeed) > MIN_FLING_SPEED){
flingInterpolatorY =
new Interpolators.AttenuationInterpolator(eyePoint[1], frameTime, frameTime + FLING_DURATION_NS, yFlingSpeed );
}
}
moveEventHistory.clear();
}
private void computeInteractionPoints(float[] coords, InteractionEvent event) {
int pointerCount = event.getPointerCount();
int offset = 0;
for (int i = 0; i < pointerCount; i++){
coords[offset] = event.getPointers()[i][0] + eyePoint[0];
coords[offset+1] = -event.getPointers()[i][1] + eyePoint[1];
offset += 3;
}
}
private float[] tmpMoveEyeDelta = new float[3];
private void move(InteractionContext ic){
tmpMoveEyeDelta = Vector.aToB3(tmpMoveEyeDelta, tmpInteractionCoordsNow, tmpInteractionCoordsLast);
tmpMoveEyeDelta[2] = 0;
moveEventHistory.add(ic.frameNanoTime, tmpMoveEyeDelta[0], tmpMoveEyeDelta[1]);
tmpMoveEyeDelta[0] = 0;
Vector.addBtoA3(eyePoint, tmpMoveEyeDelta);
}
@Override
public void pixel2ZeroPlaneCoord(float[] result, float[] pixelXY) {
result[0] = pixelXY[0];
result[1] = - (pixelXY[1] - eyePoint[1]);
}
public void centerOnY(SceneGraphContext sc, float y) {
long frameTime = sc.frameNanoTime;
flingInterpolatorY =
new Interpolators.HyperbelInterpolator(
eyePoint[1], y + surfaceHeight/2,
frameTime, frameTime + CAMERA_CENTER_DURATION_NS);
interacting = false;
}
}
|
package application.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class ServerController {
// Whether the Server is running or not
private boolean isRunning;
// Using HashMap<String, ClientHandler> to store each user and client
private HashMap<String, ClientHandler> clientHandlerMap = new HashMap<String, ClientHandler>();
private ServerSocket server;
@FXML
TextField ipAddr;
@FXML
TextField port;
@FXML
Button start;
@FXML
Button stop;
@FXML
TextArea log;
@FXML
ListView<String> list;
@FXML
public void unchange() {
log.setEditable(false);
}
@FXML
public void startServer() {
System.out.println("Server starting...");
// Create and Start the Server Conmmunication Thread.
//Thread serverThread = new Thread(new ServerThread());
Thread serverThread = new Thread(new ServerThread());
serverThread.start();
start.setDisable(true);
stop.setDisable(false);
ipAddr.setEditable(false);
port.setEditable(false);
System.out.println("Server start success.");
}
@FXML
public void stopServer() {
try {
System.out.println("Server stoping...");
isRunning = false;
// Close the Server socket and clean the Client Reference
server.close();
clientHandlerMap.clear();
start.setDisable(false);
stop.setDisable(true);
ipAddr.setEditable(true);
port.setEditable(true);
log.appendText("Server Stoped!" + "\n");
System.out.println("Server Stoped!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* ServerThread class creates the Server Thread
* @author Zetian Qin zxq876
*/
class ServerThread implements Runnable {
public void start(String serverIp, int serverPort) {
try {
// Create the socket address
SocketAddress socketAddress = new InetSocketAddress(serverIp, serverPort);
// Create the Server Socket to band with socket address
server = new ServerSocket();
server.bind(socketAddress);
// Whether Server is running
isRunning = true;
addMsg("Server start success!");
} catch (IOException e) {
// e.printStackTrace();
addMsg("Server failed to start. Please check the PortID.");
isRunning = false;
}
}
@Override
public void run() {
start(ipAddr.getText(), Integer.parseInt(port.getText()));
// When Server is running, watch the request from client
while (isRunning) {
try {
Socket socket = server.accept();
// Create the thread to interact with client
Thread thread = new Thread(new ClientHandler(socket));
thread.start();
} catch (IOException e) {
}
}
}
}
/**
* Inner class ClientHandler to interact with Client.
* @author Zetian Qin zxq876
*/
class ClientHandler implements Runnable {
private Socket socket;
private DataInputStream dis;
private DataOutputStream dos;
private boolean isConnected;
private String username;
public ClientHandler(Socket socket) {
this.socket = socket;
try {
this.dis = new DataInputStream(socket.getInputStream());
this.dos = new DataOutputStream(socket.getOutputStream());
isConnected = true;
} catch (IOException e) {
isConnected = false;
e.printStackTrace();
}
}
public Object getInetAddress() {
// TODO Auto-generated method stub
return null;
}
@Override
public void run() {
while (isRunning && isConnected) {
try {
// Read the report from Client
String msg = dis.readUTF();
String[] parts = msg.split("#");
switch (parts[0]) {
// Handle the login report
case "LOGIN":
String loginUsername = parts[1];
if (clientHandlerMap.containsKey(loginUsername)) {
dos.writeUTF("FAIL");
} else {
dos.writeUTF("SUCCESS");
addMsg("User "+loginUsername+" Login. Login Time: " + getTimeStr());
clientHandlerMap.put(loginUsername, this);
// Send the message to other users
StringBuffer msgUserList = new StringBuffer();
msgUserList.append("USERLIST#");
for (String username : clientHandlerMap.keySet()) {
msgUserList.append(username + "#");
System.out.println(username);
}
dos.writeUTF(msgUserList.toString());
// broadcast the new login user to others
String msgLogin = "LOGIN#" + loginUsername;
broadcastMsg(loginUsername, msgLogin);
// updateUserTbl();
// Store the username who is online
this.username = loginUsername;
updateUserTbl();
}
break;
// Handle the logout report.
case "LOGOUT":
clientHandlerMap.remove(username);
addMsg("User "+username+" logout. Logout time: " + getTimeStr());
String msgLogout = "LOGOUT#" + username;
broadcastMsg(username, msgLogout);
isConnected = false;
socket.close();
updateUserTbl();
break;
case "TALKTO_ALL":
String msgTalkToAll = "TALKTO_ALL#" + username + "#" + parts[1];
broadcastMsg(username, msgTalkToAll);
break;
case "TALKTO":
ClientHandler clientHandler = clientHandlerMap.get(parts[1]);
if (null != clientHandler) {
String msgTalkTo = "TALKTO#" + username + "#" + parts[2];
clientHandler.dos.writeUTF(msgTalkTo);
clientHandler.dos.flush();
}
break;
default:
break;
}
} catch (IOException e) {
isConnected = false;
e.printStackTrace();
}
}
}
/**
* To broadcast the message to other users.
* @param fromUsername the user who send the message.
* @param msg the messages.
* @throws IOException IO exception
*/
private void broadcastMsg(String fromUsername, String msg) throws IOException {
for (String toUserName : clientHandlerMap.keySet()) {
if (fromUsername.equals(toUserName) == false) {
DataOutputStream dos = clientHandlerMap.get(toUserName).dos;
dos.writeUTF(msg);
dos.flush();
}
}
}
}
/**
* Add messages to Text Box
* @param msg The message add to Text Box
*/
private void addMsg(String msg) {
// Add message in Text Box
log.appendText(msg + "\n");
// To last line of Text Box
log.positionCaret(log.getText().length());
}
public void updateUserTbl() {
// TODO Auto-generated method stub
}
public Object getInetAddress() {
// TODO Auto-generated method stub
return null;
}
/**
* Get current time as format String
* @return the current time
*/
public String getTimeStr() {
SimpleDateFormat fm = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
return fm.format(new Date());
}
}
|
package com.takshine.wxcrm.domain;
import com.takshine.wxcrm.model.AnalyticsModel;
/**
* 分析报表
* @author
*
*/
public class Analytics extends AnalyticsModel{
private String topic;
private String report;
private String param1;
private String param2;
private String param3;
private String param4;
private String param5;
private String param6;
private String param7;
private String param8;
private String param9;
private String param10;
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getReport() {
return report;
}
public void setReport(String report) {
this.report = report;
}
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
public String getParam3() {
return param3;
}
public void setParam3(String param3) {
this.param3 = param3;
}
public String getParam4() {
return param4;
}
public void setParam4(String param4) {
this.param4 = param4;
}
public String getParam5() {
return param5;
}
public void setParam5(String param5) {
this.param5 = param5;
}
public String getParam6() {
return param6;
}
public void setParam6(String param6) {
this.param6 = param6;
}
public String getParam7() {
return param7;
}
public void setParam7(String param7) {
this.param7 = param7;
}
public String getParam8() {
return param8;
}
public void setParam8(String param8) {
this.param8 = param8;
}
public String getParam9() {
return param9;
}
public void setParam9(String param9) {
this.param9 = param9;
}
public String getParam10() {
return param10;
}
public void setParam10(String param10) {
this.param10 = param10;
}
}
|
package com.ht.springboot_vue.service;
import com.ht.springboot_vue.bean.User;
import java.util.List;
/**
* @company 宏图
* @User Kodak
* @create 2019-03-11 -15:19
*/
public interface UserService {
public List<User> alluser();
User toupd(Integer id);
String del(Integer id);
boolean add(User user);
boolean upd(User user);
}
|
/**
* DNet eBusiness Suite
* Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.presenter.ext.system.service;
import seava.j4e.api.service.presenter.IDsService;
import seava.j4e.api.session.Session;
import seava.j4e.presenter.service.ds.AbstractEntityDsService;
import seava.ad.domain.impl.system.DateFormatMask;
import seava.ad.presenter.impl.system.model.DateFormatMask_Ds;
public class DateFormatMask_DsService
extends
AbstractEntityDsService<DateFormatMask_Ds, DateFormatMask_Ds, Object, DateFormatMask>
implements IDsService<DateFormatMask_Ds, DateFormatMask_Ds, Object> {
@Override
protected boolean canInsert() {
return this.canChange();
}
@Override
protected boolean canUpdate() {
return this.canChange();
}
@Override
protected boolean canDelete() {
return this.canChange();
}
private boolean canChange() {
return Session.user.get().isSystemUser();
}
}
|
package com.tencent.mm.plugin.sns.b;
import android.database.Cursor;
import java.util.ArrayList;
public interface g {
Cursor Lw(String str);
int Lx(String str);
ArrayList<Long> bwV();
void eB(long j);
int eC(long j);
boolean wi(int i);
}
|
package BillApplication;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
public class BillTop extends AnchorPane{
private Text clientNameTxt, clientIceTxt, clientCityTxt;
private Text billDateTxt, billIdTxt, billBcTxt, billBlTxt, billModeRglTxt;
// constructor
public BillTop() {
// Children nodes
//clientName
clientNameTxt = new Text("Nom");
//client ice
clientIceTxt = new Text("Ice");
//clientCity
clientCityTxt = new Text("Ville");
//billDate
billDateTxt = new Text("Date");
//BillIdTxt
billIdTxt = new Text("Facture N");
//bill BL
billBlTxt = new Text("Bl N");
//bill BC
billBcTxt = new Text("BC N");
//Mode de reglement
billModeRglTxt = new Text("Mode de réglement");
// containers
//client info container
VBox clientInfoContainer = new VBox(clientNameTxt, clientIceTxt, clientCityTxt);
//Style
clientInfoContainer.setSpacing(5);
//bill info container
VBox billInfoContainer = new VBox(billDateTxt, billIdTxt, billBlTxt, billBcTxt, billModeRglTxt);
//Style
billInfoContainer.setSpacing(5);
// Adding containers to layout
getChildren().addAll(clientInfoContainer, billInfoContainer);
// containers positions
AnchorPane.setLeftAnchor(clientInfoContainer, 0.0);
AnchorPane.setTopAnchor(clientInfoContainer, 0.0);
AnchorPane.setRightAnchor(billInfoContainer, 0.0);
AnchorPane.setTopAnchor(billInfoContainer, 0.0);
}
}
|
package com.uwetrottmann.trakt5;
import com.uwetrottmann.trakt5.entities.AccessToken;
import com.uwetrottmann.trakt5.entities.DeviceCode;
import org.junit.Test;
import retrofit2.Response;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* This test should NOT be run with the regular test suite. It requires a valid, temporary (!) auth code to be set.
*/
public class DeviceAuthTest extends BaseTestCase {
private static final String TEST_CLIENT_SECRET = "";
private static final String TEST_DEVICE_CODE = "";
// The Redirect URI is not used in OAuth device authentication.
// Set the default as the out-of-band URI used during standard OAuth.
private static final String TEST_REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
private static final TraktV2 trakt = new TestTraktV2(TEST_CLIENT_ID, TEST_CLIENT_SECRET, TEST_REDIRECT_URI);
@Override
protected TraktV2 getTrakt() {
return trakt;
}
@Test
public void test_generateDeviceCode() throws IOException {
if (TEST_CLIENT_ID.isEmpty()) {
System.out.print("Skipping test_generateDeviceCode test, no valid client id");
return;
}
Response<DeviceCode> codeResponse = getTrakt().generateDeviceCode();
assertSuccessfulResponse(codeResponse);
DeviceCode deviceCode = codeResponse.body();
assertThat(deviceCode.device_code).isNotEmpty();
assertThat(deviceCode.user_code).isNotEmpty();
assertThat(deviceCode.verification_url).isNotEmpty();
assertThat(deviceCode.expires_in).isPositive();
assertThat(deviceCode.interval).isPositive();
System.out.println("Device Code: " + deviceCode.device_code);
System.out.println("User Code: " + deviceCode.user_code);
System.out.println("Enter the user code at the following URI: " + deviceCode.verification_url);
System.out.println("Set the TEST_DEVICE_CODE variable to run the access token test");
}
@Test
public void test_getAccessToken() throws IOException {
if (TEST_CLIENT_SECRET.isEmpty() || TEST_DEVICE_CODE.isEmpty()) {
System.out.print("Skipping test_getAccessToken test, no valid auth data");
return;
}
Response<AccessToken> response = getTrakt().exchangeDeviceCodeForAccessToken(TEST_DEVICE_CODE);
assertAccessTokenResponse(response);
}
}
|
package com.ci.gui.button;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nonnull;
@SideOnly(Side.CLIENT)
public class GuiButtonDouble extends GuiButton {
private final ResourceLocation resourceLocation;
private int offsetX, offsetY, textureOffset;
public GuiButtonDouble(int buttonId, int offsetX, int offsetY, int x, int y, int width, int height, int textureOffset, ResourceLocation resource) {
super(buttonId, offsetX, offsetY, width, height, "");
this.resourceLocation = resource;
this.textureOffset = textureOffset;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
@Override
public void drawButton(@Nonnull Minecraft mc, int mouseX, int mouseY, float partialTicks) {
if (this.visible) {
GlStateManager.color(1.0F, 1.0F, 1.0F);
mc.getTextureManager().bindTexture(this.resourceLocation);
int i = this.x;
if (!this.enabled) {
i += this.textureOffset;
}else if (this.hovered){
i += this.textureOffset;
}
this.drawTexturedModalRect(this.offsetX, this.offsetY, i, this.y, this.width, this.height);
}
}
}
|
package cr.ulacit.serviceImpl;
import java.util.List;
import javax.jws.WebService;
import javax.transaction.Transactional;
import org.appfuse.service.impl.GenericManagerImpl;
import org.springframework.stereotype.Service;
import cr.ulacit.dao.DishIngredientsDao;
import cr.ulacit.model.DishIngredients;
import cr.ulacit.service.DishIngredientsManager;
/*Implementación de la interfaz del DishIngredientsManager
*@author: Gineth Salazar - Lourdes Sotomayor
*@version: 2, 2015
*/
@Transactional
@Service("dishIngredientsManager")
@WebService(serviceName="DishIngredientsService",endpointInterface ="cr.ulacit.service.DishIngredientsManager")
public class DishIngredientsImpl extends GenericManagerImpl<DishIngredients,Integer> implements DishIngredientsManager{
DishIngredientsDao dishIngreDao;
public DishIngredientsImpl(){
}
public DishIngredientsImpl(DishIngredientsDao dishIngreDao) {
super();
this.dishIngreDao = dishIngreDao;
}
/*Este método tiene como función retornar la lista de todos los ingredientes de los distintos platilos
*@Return: List<DishIngredients>
*/
@Override
public List<DishIngredients> getDishIngredients() {
return dishIngreDao.getAll();
}
@Override
public void getDishIngredients(Integer id_dishingredients) {
dishIngreDao.getDishIngredients(id_dishingredients);
}
}
|
/**
*
*/
package com.cnk.travelogix.common.facades.product.facet;
import java.util.List;
import com.cnk.travelogix.common.facades.product.data.BaseProductData;
import com.cnk.travelogix.common.facades.product.data.CnkFacetData;
import com.cnk.travelogix.common.facades.product.facet.impl.FacetToModelMapper;
/**
* @author i313879
*
*/
public interface CnkProductFacetHandler<RESULT extends BaseProductData>
{
public boolean handleFacet(RESULT resultData, List<CnkFacetData> facets, FacetToModelMapper facetToModelMapper);
}
|
package com.gmail.ivanytskyy.vitaliy.service;
import java.util.List;
import com.gmail.ivanytskyy.vitaliy.model.Student;
/*
* Service interface for controllers which need a point of entry to StudentRepository
* @author Vitaliy Ivanytskyy
*/
public interface StudentService {
Student create(Student student);
Student findById(long id);
List<Student> findByName(String name);
List<Student> findByGroupId(long groupId);
List<Student> findAll();
void deleteById(long id);
}
|
package com.zplay.playable.playableadsdemo;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Description:
* <p>
* Created by lgd on 2018/9/19.
*/
public class SplashActivity extends Activity {
private Handler mHandler;
@BindView(R.id.as_text)
TextView mTextView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ButterKnife.bind(this);
mTextView.setText(String.format("%s\n%s", mTextView.getText(), "2.4.1"));
mHandler = new Handler();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
startMainActivity();
}
}, 1500);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
mHandler.removeMessages(0);
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
createStatisticsTag();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int i = 0; i < permissions.length; i++) {
if (TextUtils.equals(permissions[i], Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
createStatisticsTag();
startMainActivity();
finish();
}
}
}
}
private void createStatisticsTag() {
File file = new File(Environment.getExternalStorageDirectory(), "zplay.statistics");
if (!file.exists()) {
try {
//noinspection ResultOfMethodCallIgnored
file.createNewFile();
} catch (IOException ignore) {
}
}
}
private void startMainActivity() {
MainActivity.launch(SplashActivity.this);
finish();
}
public void finishActivity(View view) {
mHandler.removeMessages(0);
startMainActivity();
}
}
|
package com.tencent.d.b.f;
import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.tencent.d.a.c.c;
import com.tencent.d.a.c.g$a;
import com.tencent.d.b.b.a;
class i$1 implements g$a {
final /* synthetic */ i vmY;
i$1(i iVar) {
this.vmY = iVar;
}
@SuppressLint({"ApplySharedPref"})
public final void cFM() {
c.w("Soter.TaskInit", "soter: on trigger OOM, using wrapper implement", new Object[0]);
SharedPreferences cFR = a.cFO().cFR();
if (cFR != null) {
Editor edit = cFR.edit();
edit.putBoolean(i.bO(), true);
edit.commit();
}
}
public final boolean cFL() {
SharedPreferences cFR = a.cFO().cFR();
if (cFR == null) {
return false;
}
c.i("Soter.TaskInit", "soter: is triggered OOM: %b", new Object[]{Boolean.valueOf(cFR.getBoolean(i.bO(), false))});
return cFR.getBoolean(i.bO(), false);
}
}
|
package com.shopping.DAO;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.shopping.models.Order;
import com.shopping.utils.JDBCUtils;
public class OrderDAO{
public List<Order> queryBySql(String sql, Object...params) throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
return queryRunner.query(sql, new BeanListHandler<Order>(Order.class), params);
}
public boolean insertOrder(Order order) throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql = "insert into [Order] " +
"(OrderNumber,userAccount,address,totalPrice,isCancel,status,Ordertime,Paytime,Sendtime,Receivetime,Seller) " +
"values(?,?,?,?,?,?,?,?,?,?,?)";
Object[] params = {order.getOrderNumber(), order.getUserAccount(), order.getAddress(),
order.getTotalPrice(), order.getIsCancel(), order.getStatus(), order.getOrdertime(),
order.getPaytime(), order.getSendtime(), order.getReceivetime(), order.getSeller()};
if(queryRunner.update(sql, params) == 1){
return true;
}
else{
return false;
}
}
public boolean recOrder(String Receivetime, String OrderNumber) throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql = "update [Order] set status = '待评价' , Receivetime = ? where OrderNumber = ? ";
Object[] params = {Receivetime, OrderNumber};
if(queryRunner.update(sql, params) == 1){
return true;
}
else{
return false;
}
}
public boolean sendOrder(String Sendtime, String OrderNumber) throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql = "update [Order] set status = '待收货' , Sendtime = ? where OrderNumber = ? ";
Object[] params = {Sendtime, OrderNumber};
if(queryRunner.update(sql, params) == 1){
return true;
}
else{
return false;
}
}
public boolean cancelOrder(String OrderNumber) throws SQLException{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql = "update [Order] set isCancel = 'YES' where OrderNumber = ?";
Object[] params = {OrderNumber};
if(queryRunner.update(sql, params) == 1){
return true;
}
else{
return false;
}
}
public Order queryByOrderNum(String OrderNumber) throws SQLException
{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql="select * from [Order] where OrderNumber = ?";
Object[] params = {OrderNumber};
return queryRunner.query(sql, new BeanHandler<Order>(Order.class), params);
}
public boolean updateByNum(String OrderNumber) throws SQLException
{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql="update [Order] set Status='待发货' where OrderNumber=?";
Object[] params = {OrderNumber};
if(queryRunner.update(sql, params) == 1){
return true;
}
else{
return false;
}
}
public List<Order> selectByNum(String OrderNumber) throws SQLException
{
QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());
String sql="select * from [Order] where OrderNumber=? and Status='待发货'";
Object[] params = {OrderNumber};
return queryRunner.query(sql, new BeanListHandler<Order>(Order.class), params);
}
}
|
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.junit.Test;
import java.nio.charset.Charset;
public class ByteBufTest {
@Test
public void testSlice() {
char a = '啊';
System.out.println(a);
Charset utf8 = Charset.forName("UTF-8");
ByteBuf buf = Unpooled.copiedBuffer("Netty啊 in Action rocks!", utf8); //← -- 创建一个用于保存给定字符串的字节的 ByteBuf
ByteBuf sliced = buf.slice(0, 15); //← -- 创建该 ByteBuf 从索引0 开始到索引15结束的一个新切片
System.out.println(sliced.toString(utf8)); // ← -- 将打印“Netty in Action”
buf.setByte(0, (byte) 'J'); // ← -- 更新索引0 处的字节
assert buf.getByte(0) == sliced.getByte(0); //← -- 将会成功,因为数据是共享的,对其中一个所做的更改对另外一个也是可见的
System.out.println(sliced.toString(utf8));
}
@Test
public void sss() throws Exception {
char c = '\uD87E';
System.out.printf("The value of char %c is %d.%n", c, (int) c);
String str = String.valueOf(c);
byte[] bys = str.getBytes("Unicode");
for (int i = 0; i < bys.length; i++) {
System.out.printf("%X ", bys[i]);
}
System.out.println();
int unicode = (bys[2] & 0xFF) << 8 | (bys[3 & 0xFF]);
System.out.printf("The unicode value of %c is %d.%n", c, unicode);
}
}
|
package zm.gov.moh.common.submodule.form.widget;
public class TextAreaWidget {
}
|
package com.company;
public class Main {
public static void main(String[] args) {
int hightScore = 50;
if(hightScore ==50){
System.out.println("this is an expression");
}
}
}
|
package garcia.juan.reto.qvision.questions;
import garcia.juan.reto.qvision.model.DatosReservaModel;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Question;
import net.serenitybdd.screenplay.questions.Text;
import java.util.List;
import static garcia.juan.reto.qvision.userinterface.ResumenReserva.TOTAL_TO_PAY_NOW;
public class ElValorCobrado implements Question<Boolean> {
private List<DatosReservaModel> datosReserva;
public ElValorCobrado(List<DatosReservaModel> datosReserva) {
this.datosReserva = datosReserva;
}
@Override
public Boolean answeredBy(Actor actor) {
return (Text.of(TOTAL_TO_PAY_NOW).viewedBy(actor).asString().replace("$","")
.equalsIgnoreCase(datosReserva.get(0).getTotalEsperado().replace("$","")));
}
public static ElValorCobrado esCorrecto(List<DatosReservaModel> datosReserva) {
return new ElValorCobrado(datosReserva);
}
}
|
/*
* Copyright 2011-2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.neo4j.integration.conversion_imperative;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.neo4j.driver.Driver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.neo4j.config.AbstractNeo4jConfig;
import org.springframework.data.neo4j.core.convert.Neo4jConversions;
import org.springframework.data.neo4j.integration.shared.conversion.CompositePropertiesITBase;
import org.springframework.data.neo4j.integration.shared.conversion.ThingWithCompositeProperties;
import org.springframework.data.neo4j.integration.shared.conversion.ThingWithCustomTypes;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.test.Neo4jExtension;
import org.springframework.data.neo4j.test.Neo4jIntegrationTest;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Collections;
/**
* @author Michael J. Simons
* @soundtrack Die Toten Hosen - Learning English, Lesson Two
*/
@Neo4jIntegrationTest
class ImperativeCompositePropertiesIT extends CompositePropertiesITBase {
protected static Neo4jExtension.Neo4jConnectionSupport neo4jConnectionSupport;
@Autowired ImperativeCompositePropertiesIT(Driver driver) {
super(driver);
}
@Test
void compositePropertiesOnRelationshipsShouldBeWritten(@Autowired Repository repository) {
ThingWithCompositeProperties t = repository.save(newEntityWithRelationshipWithCompositeProperties());
assertRelationshipPropertiesInGraph(t.getId());
}
@Test
void compositePropertiesOnRelationshipsShouldBeRead(@Autowired Repository repository) {
Long id = createRelationshipWithCompositeProperties();
assertThat(repository.findById(id)).isPresent().hasValueSatisfying(this::assertRelationshipPropertiesOn);
}
@Test
void compositePropertiesOnNodesShouldBeWritten(@Autowired Repository repository) {
ThingWithCompositeProperties t = repository.save(newEntityWithCompositeProperties());
assertNodePropertiesInGraph(t.getId());
}
@Test
void compositePropertiesOnNodesShouldBeRead(@Autowired Repository repository) {
Long id = createNodeWithCompositeProperties();
assertThat(repository.findById(id)).isPresent().hasValueSatisfying(this::assertNodePropertiesOn);
}
public interface Repository extends Neo4jRepository<ThingWithCompositeProperties, Long> {
}
@Configuration
@EnableNeo4jRepositories(considerNestedRepositories = true)
@EnableTransactionManagement
static class Config extends AbstractNeo4jConfig {
@Bean
public Driver driver() {
return neo4jConnectionSupport.getDriver();
}
@Override
public Neo4jConversions neo4jConversions() {
return new Neo4jConversions(Collections.singleton(new ThingWithCustomTypes.CustomTypeConverter()));
}
}
}
|
package ru.startandroid.places.events;
public class Events {
public static Event startSearch() {
return createEvent(EventType.SEARCH_STARTED);
}
public static Event finishSearch() {
return createEvent(EventType.SEARCH_FINISHED);
}
private static Event createEvent(int type) {
Event event = new Event();
event.setType(type);
return event;
}
}
|
package com.senon.leanstoragedemo.activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.TextView;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.GetCallback;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.senon.leanstoragedemo.util.AVUtil;
import com.senon.leanstoragedemo.dialog.DialogPopwin;
import com.senon.leanstoragedemo.dialog.DialogRecharge;
import com.senon.leanstoragedemo.R;
import com.senon.leanstoragedemo.adapter.RecycleHolder;
import com.senon.leanstoragedemo.adapter.RecyclerAdapter;
import com.senon.leanstoragedemo.base.BaseActivity;
import com.senon.leanstoragedemo.base.BaseResponse;
import com.senon.leanstoragedemo.contract.UserContract;
import com.senon.leanstoragedemo.entity.Student;
import com.senon.leanstoragedemo.entity.StudentDetails;
import com.senon.leanstoragedemo.presenter.UserPresenter;
import com.senon.leanstoragedemo.util.BaseEvent;
import com.senon.leanstoragedemo.util.ComUtil;
import com.senon.leanstoragedemo.util.ToastUtil;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
/**
* 学员详细 页面
*/
public class UserActivity extends BaseActivity<UserContract.View, UserContract.Presenter> implements UserContract.View{
@BindView(R.id.lrv)
LRecyclerView lrv;
@BindView(R.id.name_tv)
TextView name_tv;
@BindView(R.id.total_count_tv)
TextView total_count_tv;
@BindView(R.id.last_count_tv)
TextView last_count_tv;
@BindView(R.id.total_money_tv)
TextView total_money_tv;
@BindView(R.id.last_money_tv)
TextView last_money_tv;
private RecyclerAdapter<AVObject> adapter;
private LRecyclerViewAdapter mLRecyclerViewAdapter;
private boolean isLoadMore = false;//是否加载更多
private boolean isDownRefesh = false;//是否下拉刷新
private int currentPage = 0;//当前页数
private int pageLimit = 8;//每页条数
private List<AVObject> mData = new ArrayList<>();//原始数据
private List<AVObject> tempData = new ArrayList<>();//间接数据
private DialogRecharge dialogRecharge;
private Student student;
@Override
public int getLayoutId() {
return R.layout.activity_user;
}
@Override
public void init() {
EventBus.getDefault().register(this);
student = (Student) getIntent().getSerializableExtra("student");
name_tv.setText(student.getName()+"的历史记录");
initLrv();
setData();
}
private void getOrderList() {
AVQuery<StudentDetails> details = AVObject.getQuery(StudentDetails.class);
details.whereEqualTo(StudentDetails.OWNER, student);
details.addDescendingOrder("createdAt");//按照创建时间降序排列
details.limit(pageLimit);// 最多返回 10 条结果
details.skip(currentPage * pageLimit);// 跳过 10 * 当前页数 条结果
getAVManager().setOnAVUtilListener(details, new AVUtil.OnAVUtilListener() {
@Override
public void onSuccess(List<AVObject> list) {
result(list);
}
});
}
/**
* 获取第一页数据
*/
private void getFirstPageData() {
isDownRefesh = true;
currentPage = 0;
getOrderList();
}
private void getForceToRefresh(){
lrv.scrollToPosition(0);
currentPage = 0;
isLoadMore = false;
isDownRefesh = true;
lrv.forceToRefresh();
}
private void result(List<AVObject> data){
tempData.clear();
tempData.addAll(data);
if (tempData.size() == 0 && mData.size() > 0 && isLoadMore) {//最后一页时
lrv.setNoMore(true);
isLoadMore = false;
} else if (isDownRefesh) {//下拉刷新时
mData.clear();
mData.addAll(tempData);
refreshData();
} else {//加载更多时
mData.addAll(tempData);
refreshData();
}
}
private void setData(){
AVQuery<Student> avQuery = AVQuery.getQuery(Student.class);
avQuery.getInBackground(student.getObjectId(), new GetCallback<Student>() {
@Override
public void done(Student stu, AVException e) {
student = stu;
total_count_tv.setText(student.getTotalCount()+"");
last_count_tv.setText(student.getLastCount()+"");
total_money_tv.setText(student.getTotalMoney()+"");
last_money_tv.setText(student.getLastMoney()+"");
}
});
}
private void refreshData() {
if (lrv == null) {
return;
}
lrv.refreshComplete(currentPage);
mLRecyclerViewAdapter.notifyDataSetChanged();
isDownRefesh = false;
isLoadMore = false;
}
private void initLrv() {
LinearLayoutManager manager = new LinearLayoutManager(this);
lrv.setLayoutManager(manager);
lrv.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader); //设置下拉刷新Progress的样式
// lrv.setArrowImageView(R.mipmap.news_renovate); //设置下拉刷新箭头
lrv.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);
adapter = new RecyclerAdapter<AVObject>(this, mData, R.layout.item_user_lrv) {
@Override
public void convert(final RecycleHolder helper, final AVObject data, final int position) {
final StudentDetails item = (StudentDetails) data;
helper.setVisible(R.id.title_tv,position == 0);
helper.setText(R.id.time_tv,item.getTime());
if(item.getFlag() == 1){//签到
helper.setText(R.id.text2,"表现");
helper.setText(R.id.des_tv,"备注:"+item.getComments());
helper.setText(R.id.money_tv, ComUtil.getLevelStr(item.getLevel()));
helper.setText(R.id.type_tv,"签到");
helper.setTextColor(R.id.type_tv,R.color.txt_blue_color);
}else if(item.getFlag() == 2){//充值
helper.setText(R.id.text2,"充值");
helper.setText(R.id.des_tv,"备注:"+item.getContent());
helper.setText(R.id.money_tv,item.getMoney());
helper.setText(R.id.type_tv,"充值");
helper.setTextColor(R.id.type_tv,R.color.txt_green_color);
}
helper.setOnClickListener(R.id.lay, new View.OnClickListener() {
@Override
public void onClick(View v) {
if(item.getFlag() == 1) {
startActivity(new Intent(UserActivity.this,SignActivity.class)
.putExtra("name",item.getName())
.putExtra("state",0)
.putExtra("details", (Serializable) item));
}
}
});
helper.setOnLongClickListener(R.id.lay, new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
ArrayList<String> list = new ArrayList<>();
if(item.getFlag() == 1){
list.add("删除该次签到");
list.add("更改该次签到");
}else if(item.getFlag() == 2){
list.add("删除该次充值");
}
new DialogPopwin(UserActivity.this, list, new DialogPopwin.OnItemClickListener() {
@Override
public void onItemClick(int position) {
if(position == 0){
setSweetDialog(item, "确认删除?","删除记录之后将不能恢复!");
}else if(position == 1){
startActivity(new Intent(UserActivity.this,SignActivity.class)
.putExtra("name",item.getName())
.putExtra("state",2)
.putExtra("details",(Serializable)item));
}
}
}).show();
return false;
}
});
}
};
mLRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
lrv.setAdapter(mLRecyclerViewAdapter);
// lrv.setLoadMoreEnabled(false);
// lrv.setPullRefreshEnabled(false);
//设置底部加载颜色
lrv.setFooterViewColor(R.color.color_blue, R.color.text_gray, R.color.elegant_bg);
lrv.setHeaderViewColor(R.color.color_blue, R.color.text_gray, R.color.elegant_bg);
lrv.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
getFirstPageData();
}
});
lrv.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore() {
isLoadMore = true;
currentPage++;
getOrderList();
}
});
lrv.forceToRefresh();
}
private void setSweetDialog(final StudentDetails item, String title, String tip){
SweetAlertDialog sad = new SweetAlertDialog(UserActivity.this, SweetAlertDialog.WARNING_TYPE)
.setTitleText(title)
.setContentText(tip)
.setCancelText("取消")
.setConfirmText("确认")
.showCancelButton(true)
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.dismiss();
if(item.getFlag() == 1){//签到
int money = item.getMoney();
int count = item.getCount();
student.setLastMoney(student.getLastMoney() + money);
student.setLastCount(student.getLastCount() + count);
}else if(item.getFlag() == 2){//充值
int money = item.getMoney();
int count = item.getCount();
student.setTotalMoney(student.getTotalMoney() - money);
student.setLastMoney(student.getLastMoney() - money);
student.setTotalCount(student.getTotalCount() - count);
student.setLastCount(student.getLastCount() - count);
}
//学员概述
student.saveInBackground();
//历史记录
item.deleteInBackground(new DeleteCallback() {
@Override
public void done(AVException e) {
if(e == null){
//通知MainActivity刷新页面
BaseEvent event = new BaseEvent();
event.setCode(4);
EventBus.getDefault().post(event);
setData();
getForceToRefresh();
}
}
});
}
});
sad.show();
}
@OnClick({R.id.back_igv,R.id.recharge_btn,R.id.sign_btn})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.back_igv:
finish();
break;
case R.id.recharge_btn:
if(dialogRecharge == null){
dialogRecharge = new DialogRecharge(UserActivity.this,student.getName());
dialogRecharge.setConfirmClickListener(new DialogRecharge.OnClickListener() {
@Override
public void setConfirmClickListener(final String time, final String money, final String count, final String des) {
final AVQuery<StudentDetails> details = AVObject.getQuery(StudentDetails.class);
details.whereEqualTo(StudentDetails.OWNER, student);
details.whereEqualTo(StudentDetails.TIME, time);
details.whereEqualTo(StudentDetails.FLAG, 2);//每天只能充值一次
getAVManager().setOnAVUtilListener(details, new AVUtil.OnAVUtilListener() {
@Override
public void onSuccess(List<AVObject> list) {
if(list == null || list.size() == 0){
//更新学员概述次数与金额等
student.setTotalCount(student.getTotalCount()+Integer.parseInt(count));
student.setLastCount(student.getLastCount()+Integer.parseInt(count));
student.setTotalMoney(student.getTotalMoney()+Integer.parseInt(money));
student.setLastMoney(student.getLastMoney()+Integer.parseInt(money));
// student.saveInBackground();
//生成当前充值记录,并插入数据库中
StudentDetails studentDetails = new StudentDetails();
studentDetails.setName(student.getName());
studentDetails.setFlag(2);
studentDetails.setTime(time);
studentDetails.setMoney(Integer.parseInt(money));
studentDetails.setCount(Integer.parseInt(count));
studentDetails.setContent(des);
studentDetails.setOwner(student);
studentDetails.saveInBackground();
BaseEvent event = new BaseEvent();
event.setCode(3);
EventBus.getDefault().post(event);
setData();
getForceToRefresh();
dialogRecharge.dismiss();
ToastUtil.showShortToast("充值成功!");
}else{
ToastUtil.showShortToast("每天只能充值一次哦!");
}
}
});
}
});
}
dialogRecharge.show();
break;
case R.id.sign_btn:
startActivity(new Intent(UserActivity.this,SignActivity.class)
.putExtra("name",student.getName())
.putExtra("state",1)
.putExtra("student", (Serializable) student));
break;
}
}
@Override
public UserContract.Presenter createPresenter() {
return new UserPresenter(this);
}
@Override
public UserContract.View createView() {
return this;
}
@Override
public void result(BaseResponse data) {
}
@Override
public void setMsg(String msg) {
ToastUtil.showShortToast(msg);
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
@Subscribe(threadMode = ThreadMode.MAIN)//在ui线程执行
public void onDataSynEvent(BaseEvent event) {
int code = event.getCode();
if (code == 1 || code == 2) {//1签到 2签到修改
setData();
getForceToRefresh();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.