text stringlengths 10 2.72M |
|---|
package pl.odsoftware.userservice.test.setup;
import io.vavr.Tuple;
import io.vavr.Tuple2;
import pl.odsoftware.userservice.domain.Calculation;
import pl.odsoftware.userservice.domain.UserDetails;
import java.util.HashMap;
import java.util.Map;
public class UserDetailsFactory {
private static final Map<String, Tuple2<Calculation, UserDetails>> USERS = new HashMap<>();
static {
UserDetails userDetails1 = new UserDetails(1, "test_login", "test_name", "test_type", "test_avatar", "test_date", 3, 2);
Calculation calculation1 = userDetails1.doCalculations().getCalculations();
USERS.put("regular_user", Tuple.of(calculation1, userDetails1));
}
public static Tuple2<Calculation, UserDetails> get(String type){
return USERS.get(type);
}
}
|
package com.hanmi.user.serviceImpl;
import com.hanmi.user.dao.UserDao;
import com.hanmi.user.entity.User;
import com.hanmi.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
@Override
public User loginCheck(Map<String, String> paramsmap) {
return userDao.loginCheck(paramsmap);
}
@Override
public List<User> queryUser(Map<String, String> parammap) {
return userDao.queryUser(parammap);
}
@Override
public int regUser(Map<String, String> parammap) {
return userDao.regUser(parammap);
}
@Override
public int editUser(Map<String, String> parammap) {
return userDao.editUser(parammap);
}
@Override
public int delUser(List<Map<String, String>> paramslist) {
return userDao.delUser(paramslist);
}
}
|
package com.newlec.dao;
import java.util.List;
import com.newlec.domain.MemberVO;
public interface MemberDao {
String retrieveDate() throws Exception;
int findMemberId(String id) throws Exception;
List<MemberVO> getMemberList();
MemberVO getMemberLoginInfo(MemberVO member);
int insertMember(MemberVO member);
}
|
/*
* Origin of the benchmark:
* repo: https://github.com/diffblue/cbmc.git
* branch: develop
* directory: regression/cbmc-java/long1
* The benchmark was taken from the repo: 24 January 2018
*/
class Main
{
public static void main(String[] args)
{
java.util.Random random = new java.util.Random(42);
//long l=random.nextLong();
long l=4620693217682128896L;
// conversions
int i=(int)l;
char c=(char)l;
float f=l;
double d=l;
short s=(short)l;
if(i>=0)
assert (long)i==(l&0x7fffffff);
if(c>=0)
assert (long)c==(l&0x7fff);
if(s>=0)
assert (long)s==(l&0x7fff);
}
}
|
package org.elasticsearch.plugin.zentity;
import org.elasticsearch.common.Booleans;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.plugin.zentity.exceptions.BadRequestException;
import org.elasticsearch.rest.RestRequest;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
public class ParamsUtil {
/**
* Parse a string as a boolean, where empty values are interpreted as "true". Similar to
* {@link RestRequest#paramAsBoolean}.
*
* @param val The raw param value.
* @return The parsed bool.
*/
private static boolean asBoolean(String val) {
// Treat empty string as true because that allows the presence of the url parameter to mean "turn this on"
if (val != null && val.length() == 0) {
return true;
} else {
return Booleans.parseBoolean(val);
}
}
/**
* Get a parameter, which may or may not be present, from multiple sets of parameters.
*
* @param key The parameter key.
* @param params The primary set of parameters.
* @param defaultParams A backup set of parameters, if the parameter is not found in the primary.
* @return An optional string of the parameter's value.
*/
private static Optional<String> opt(String key, Map<String, String> params, Map<String, String> defaultParams) {
return Optional
.ofNullable(params.get(key))
.or(() -> Optional.ofNullable(defaultParams.get(key)));
}
private static <T> T opt(String key, T defaultValue, Function<String, T> mapper, Map<String, String> params, Map<String, String> defaultParams) {
return opt(key, params, defaultParams)
.map((val) -> {
try {
return mapper.apply(val);
} catch (Exception ex) {
throw new BadRequestException("Failed to parse parameter [" + key + "] with value [" + val + "]", ex);
}
})
.orElse(defaultValue);
}
public static String optString(String key, String defaultValue, Map<String, String> params, Map<String, String> defaultParams) {
return opt(key, params, defaultParams).orElse(defaultValue);
}
public static Boolean optBoolean(String key, Boolean defaultValue, Map<String, String> params, Map<String, String> defaultParams) {
return opt(key, defaultValue, ParamsUtil::asBoolean, params, defaultParams);
}
public static Integer optInteger(String key, Integer defaultValue, Map<String, String> params, Map<String, String> defaultParams) {
return opt(key, defaultValue, Integer::parseInt, params, defaultParams);
}
public static TimeValue optTimeValue(String key, TimeValue defaultValue, Map<String, String> params, Map<String, String> defaultParams) {
return opt(key, defaultValue, s -> TimeValue.parseTimeValue(s, key), params, defaultParams);
}
/**
* Read many parameters from a {@link RestRequest} into a {@link Map}. It is necessary to read all possible params
* in a {@link org.elasticsearch.rest.BaseRestHandler BaseRestHandler's} prepare method to avoid throwing
* a validation error.
*
* @param req A request.
* @param params All the parameters to read from the request.
* @return A map from the parameter name to the parameter value in the request.
*/
public static Map<String, String> readAll(RestRequest req, String ...params) {
Map<String, String> paramsMap = new TreeMap<>();
for (String param : params) {
paramsMap.put(param, req.param(param));
}
return paramsMap;
}
}
|
package hu.lamsoft.hms.customer.service.customer;
import java.util.Date;
import java.util.List;
import hu.lamsoft.hms.common.persistence.regimen.enums.Meal;
import hu.lamsoft.hms.customer.service.customer.dto.CustomerMealDTO;
public interface CustomerMealService {
List<Meal> getMeals();
CustomerMealDTO recordCustomerMeal(CustomerMealDTO customerMeal);
List<CustomerMealDTO> getCustomerMeal(String email, Date fromDate, Date toDate);
}
|
package com.atguigu.lgl;
/*(1)定义一个Circle类,
包含一个double型的radius属性代表圆的半径,一个findArea()方法返回圆的面积。
(2)定义一个类PassObject,在类中定义一个方法printAreas(),
该方法的定义如下:public void printAreas(Circle c, int time)
在printAreas方法中打印输出1到time之间的每个整数半径值,以及对应的面积。
例如,times为5,则输出半径1,2,3,4,5,以及对应的圆面积。*/
public class PassObject_Luo2 {
public static void main(String[] args) {
PassObject_Luo3 luo1 = new PassObject_Luo3();
luo1.printAreas(new Circle(), 5);
}
}
class Circle2{
private double radius;
public void setRadius(double r){
radius = r;
}
public double getRadius(){
return radius;
}
public double findArea(){
return Math.PI * radius * radius;
}
}
class PassObject_Luo3{
public void printAreas(Circle c, int time){
System.out.println("Radius\tArea");
int i = 1;
for (; i <= time; i++) {
c.setRadius(i);
System.out.println(c.getRadius() + "\t" + c.findArea());
}
c.setRadius(i);
System.out.println("now Radius = " + c.getRadius());
}
} |
package de.cuuky.varo.bot.discord.register;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Random;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import de.cuuky.varo.Main;
import de.cuuky.varo.config.config.ConfigEntry;
import de.cuuky.varo.config.messages.ConfigMessages;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.User;
public class BotRegister {
/*
* OLD CODE
*/
private static ArrayList<BotRegister> register;
static {
register = new ArrayList<>();
loadAll();
}
private String uuid;
private long userId = -1;
private int code = -1;
private boolean bypass = false;
private String name;
public BotRegister(String uuid, boolean start) {
this.uuid = uuid;
if(start)
if(code == -1)
this.code = generateCode();
register.add(this);
}
public int generateCode() {
int code = new Random().nextInt(1000000) + 1;
for(BotRegister br : register)
if(!br.equals(this))
if(br.getCode() == code)
return generateCode();
return code;
}
public void delete() {
if(getPlayer() != null)
getPlayer().kickPlayer("§cBotRegister §7unregistered");
register.remove(this);
}
public int getCode() {
return this.code;
}
public String getPlayerName() {
return this.name;
}
public void setCode(int code) {
this.code = code;
}
public void setBypass(boolean bypass) {
this.bypass = bypass;
}
public void setPlayerName(String name) {
this.name = name;
}
public Member getMember() {
try {
JDA jda = Main.getDiscordBot().getJda();
return jda.getGuildById(ConfigEntry.DISCORDBOT_SERVERID.getValueAsLong()).getMemberById(this.userId);
} catch(Exception e) {
return null;
}
}
public boolean isBypass() {
return bypass;
}
public boolean isActive() {
if(bypass)
return true;
return userId > 0;
}
public void setUserId(long user) {
this.userId = user;
}
public long getUserId() {
return this.userId;
}
public String getUUID() {
return this.uuid;
}
public String getKickMessage() {
return ConfigMessages.DISCORD_NOT_REGISTERED_DISCORD.getValue().replace("%code%", String.valueOf(getCode()));
}
public static ArrayList<BotRegister> getBotRegister() {
return register;
}
public Player getPlayer() {
return Bukkit.getPlayer(UUID.fromString(uuid));
}
public static BotRegister getRegister(String uuid) {
for(BotRegister br : register)
if(br.getUUID().equals(uuid))
return br;
return null;
}
public static BotRegister getBotRegisterByPlayerName(String name) {
for(BotRegister br : register)
if(br.getPlayerName() != null)
if(br.getPlayerName().equals(name))
return br;
return null;
}
public static BotRegister getRegister(User user) {
for(BotRegister br : register)
if(br.getUserId() == user.getIdLong())
return br;
return null;
}
public static void saveAll() {
if(!ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean())
return;
if(ConfigEntry.DISCORDBOT_USE_VERIFYSTSTEM_MYSQL.getValueAsBoolean()) {
if(!Main.getDataManager().getMysql().isConnected())
return;
Main.getDataManager().getMysql().update("TRUNCATE TABLE verify;");
for(final BotRegister reg : register) {
Main.getDataManager().getMysql().update("INSERT INTO verify (uuid, userid, code, bypass, name) VALUES ('" + reg.getUUID() + "', " + (reg.getUserId() != -1 ? reg.getUserId() : "null") + ", " + reg.getCode() + ", " + reg.isBypass() + ", '" + (reg.getPlayerName() == null ? "null" : reg.getPlayerName()) + "');");
}
} else {
File file = new File("plugins/Varo", "registrations.yml");
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
for(String s : cfg.getKeys(true))
cfg.set(s, null);
for(final BotRegister reg : register) {
cfg.set(reg.getUUID() + ".userId", reg.getUserId() != -1 ? reg.getUserId() : "null");
cfg.set(reg.getUUID() + ".code", reg.getCode());
cfg.set(reg.getUUID() + ".bypass", reg.isBypass());
cfg.set(reg.getUUID() + ".name", reg.getPlayerName() == null ? "null" : reg.getPlayerName());
}
try {
cfg.save(file);
} catch(IOException e) {
e.printStackTrace();
}
}
}
private static void loadAll() {
if(!ConfigEntry.DISCORDBOT_VERIFYSYSTEM.getValueAsBoolean())
return;
if(ConfigEntry.DISCORDBOT_USE_VERIFYSTSTEM_MYSQL.getValueAsBoolean()) {
if(!Main.getDataManager().getMysql().isConnected()) {
System.err.println(Main.getConsolePrefix() + "Failed to load BotRegister!");
return;
}
ResultSet rs = Main.getDataManager().getMysql().getQuery("SELECT * FROM verify");
try {
while(rs.next()) {
String uuid = rs.getString("uuid");
BotRegister reg = new BotRegister(uuid, false);
try {
reg.setUserId(rs.getLong("userid"));
} catch(Exception e) {
reg.setUserId(-1);
}
reg.setCode(rs.getInt("code"));
reg.setBypass(rs.getBoolean("bypass"));
reg.setPlayerName(rs.getString("name"));
if(Bukkit.getPlayer(UUID.fromString(uuid)) != null && !reg.isActive())
Bukkit.getPlayer(UUID.fromString(uuid)).kickPlayer(reg.getKickMessage());
}
} catch(SQLException e) {
e.printStackTrace();
}
} else {
File file = new File("plugins/Varo", "registrations.yml");
YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
for(String key : cfg.getKeys(true)) {
if(!key.contains(".userId"))
continue;
String uuid = key.replace(".userId", "");
BotRegister reg = new BotRegister(uuid, false);
try {
reg.setUserId(cfg.getLong(uuid + ".userId"));
} catch(Exception e) {
reg.setUserId(-1);
}
reg.setBypass(cfg.getBoolean(uuid + ".bypass"));
reg.setCode(cfg.getInt(uuid + ".code"));
reg.setPlayerName(cfg.getString(uuid + ".name"));
if(Bukkit.getPlayer(UUID.fromString(uuid)) != null && !reg.isActive())
Bukkit.getPlayer(UUID.fromString(uuid)).kickPlayer(reg.getKickMessage());
}
}
}
}
|
package com.april;
//All animals can move, breathe, reproduce
public interface AllAnimals
{
String move();
String breathe();
String reproduce();
String eat();
} |
package Generador;
public class Persona {
String nombre;
int edad;
String telefono;
String email;
String apellido;
public Persona(String nombre,String apellido,int edad,String telefono,String email){
this.nombre=nombre;
this.apellido=apellido;
this.edad=edad;
this.telefono=telefono;
this.email=email;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getEdad() {
return edad;
}
public void setEdad(int edad) {
this.edad = edad;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} |
/*
* Created by Sajid Hussain
*/
package bb.java.developer.test.dao;
/**
* The Interface Dao.
*
* @param <T> the generic type
*/
public interface Dao<T> {
/**
* Gets the.
*
* @param id the id
* @return the t
*/
public T get(String id);
/**
* Save.
*
* @param t the t
*/
public void save(T t);
}
|
package com.learn.diagrammultithreading.guardedSuspension;
public class UnsafeRequestQueue implements RequestQueue {
@Override
public Request getRequest() {
return null;
}
@Override
public void putRequest(Request request) {
}
}
|
/*
* 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.danilocarreiro.carros.entities;
/**
*
* @author DANILODOSSANTOSCARRE
*/
public class ModelEntityFields {
public static String table= "models";
public static String modelCode = "MODEL_CODE";
public static String modelName = "MODEL_NAME";
}
|
package com.own.hibernate;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
//OneToOne Mapping
@Entity
@Table(name="STUDENT_INFORMATION")
public class Student_Info {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int rollNo;
//@Transient
@Column(name="STUDENT_NAME", nullable=false)
private String studentName;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="rollNo")
private StudentDetails studentDetails;
public StudentDetails getStudentDetails() {
return studentDetails;
}
public void setStudentDetails(StudentDetails studentDetails) {
this.studentDetails = studentDetails;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
// @Temporal(TemporalType.DATE)
// private Date birthDate;
// public Date getBirthDate() {
// return birthDate;
// }
// public void setBirthDate(Date birthDate) {
// this.birthDate = birthDate;
// }
}
|
package com.brichri.howTiredAmI.ui;
import android.content.ContentUris;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.brichri.howTiredAmI.R;
import com.brichri.howTiredAmI.adapters.ResultProviderAdapter;
import com.brichri.howTiredAmI.pvt.Level;
import com.brichri.howTiredAmI.pvt.Result;
import com.brichri.howTiredAmI.pvt.Runner;
import com.brichri.howTiredAmI.pvt.Runner.PvtRunListener;
public class PvtActivity extends FragmentActivity implements PvtRunListener{
private static final String TAG = "PvtActivity";
private ImageView mCountdownView;
private TextView mInstructionsTv;
private TextView mClockTv;
private TextView mDurationUnitsTv;
private TextView mTickerTv;
private RelativeLayout mScreenLayout;
private ImageView mResultImgVw;
private Runner mTestRunner;
private AnimationDrawable mCountdownAnimation; // TODO is this really the best option?
private Handler mHandler;
private Result mInterruptedResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO move this into a theme
// the test is run in full screen to minimize distractions
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.layout_test);
Level level = (Level) getIntent().getExtras().getSerializable(Level.TAG);
// get a handle on the views that will change throughout the test
mCountdownView = (ImageView) findViewById(R.id.countdown_view);
mInstructionsTv = (TextView) findViewById(R.id.instructions_view);
mClockTv = (TextView) findViewById(R.id.clock);
mDurationUnitsTv = (TextView) findViewById(R.id.units);
mTickerTv = (TextView) findViewById(R.id.ticker);
mScreenLayout = (RelativeLayout) findViewById(R.id.test_layout);
mResultImgVw = (ImageView) findViewById(R.id.result_image);
setDurationUnitsAndClockText(level.getLabelDigits(this), level.getLabelUnits(this));
mScreenLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mTestRunner.userResponds();
mScreenLayout.setEnabled(false);
return false;
}
});
mScreenLayout.setEnabled(false);
// TODO simplify this, and probably move out of xml or keep with animation or something
long beginMillis = getResources().getInteger(R.integer.countdown_begins);
long countDownMillis = getResources().getInteger(R.integer.countdown_rate) * 4;
long introMillis = beginMillis + countDownMillis;
// TODO implement restarting interrupted result
if (savedInstanceState != null){
mInterruptedResult = (Result) savedInstanceState.getSerializable(Result.TAG);
mTestRunner = new Runner(mInterruptedResult, this, introMillis);
} else {
mTestRunner = new Runner(this, level, introMillis);
}
// TODO can get rid of this once intro is fixed
mHandler = new Handler();
}
private void showInterruptedDialog(Level level, long startTime) {
InterruptionDialog newFragment = InterruptionDialog.newInstance(level, startTime);
newFragment.show(getSupportFragmentManager(), "interruption");
}
@Override
protected void onResume() {
super.onResume();
if (mInterruptedResult != null){
showInterruptedDialog(mInterruptedResult.getLevel(), mInterruptedResult.getStartDate());
} else {
mTestRunner.start();
}
}
@Override
protected void onPause() {
super.onPause();
mInterruptedResult = mTestRunner.pause();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(Result.TAG, mInterruptedResult);
}
@Override
public void onStartIntro() {
Log.d(TAG, "onStartIntro");
// TODO this is probably not the best way to do this intro stuff
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mCountdownAnimation = (AnimationDrawable) mCountdownView.getBackground();
mCountdownView.setVisibility(View.VISIBLE);
mCountdownAnimation.start();
}
}, getResources().getInteger(R.integer.countdown_begins));
}
@Override
public void onEndIntro() {
mInstructionsTv.setVisibility(View.INVISIBLE);
mCountdownView.setVisibility(View.GONE);
mDurationUnitsTv.setVisibility(View.INVISIBLE);
mClockTv.setVisibility(View.GONE);
}
@Override
public void onStartPvtInterval() {
mScreenLayout.setEnabled(true);
mTickerTv.setVisibility(View.INVISIBLE);
mInstructionsTv.setVisibility(View.INVISIBLE);
mResultImgVw.setVisibility(View.INVISIBLE);
}
@Override
public void onEarlyTap() {
mInstructionsTv.setText(R.string.early_instructions);
mInstructionsTv.setVisibility(View.VISIBLE);
}
@Override
public void onStartStimulus() {
mTickerTv.setText(getResources().getString(R.string.ticker_string));
mTickerTv.setVisibility(View.VISIBLE);
}
@Override
public void onGoodTap(int reactionTime) {
mResultImgVw.setImageDrawable(getResources().getDrawable(R.drawable.good_circle));
mResultImgVw.setVisibility(View.VISIBLE);
mTickerTv.setText(Integer.toString(reactionTime));
mTickerTv.setVisibility(View.VISIBLE);
}
@Override
public void onLapse() {
mScreenLayout.setEnabled(false);
mResultImgVw.setImageDrawable(getResources().getDrawable(R.drawable.bad_image));
mResultImgVw.setVisibility(View.VISIBLE);
mTickerTv.setText(getResources().getString(R.string.lapse_result));
mTickerTv.setVisibility(View.VISIBLE);
}
@Override
public void onEndOfTest(final Result result) {
// disable the screen and inform the user that the test has ended
mScreenLayout.setEnabled(false);
mTickerTv.setVisibility(View.INVISIBLE);
mResultImgVw.setVisibility(View.INVISIBLE);
mDurationUnitsTv.setText(R.string.end_of_test);
mDurationUnitsTv.setVisibility(View.VISIBLE);
mInstructionsTv.setText(R.string.preparing_results);
mInstructionsTv.setVisibility(View.VISIBLE);
new Thread (new Runnable(){
@Override
public void run() {
Uri resultUri = ResultProviderAdapter.insertResult(PvtActivity.this, result);
result.setId(ContentUris.parseId(resultUri));
}
}).start();
}
@Override
public void onEndOfOutro() {
startResultActivity();
}
private void startResultActivity(){
Result result = mTestRunner.getResult();
Intent i = new Intent(getApplicationContext(), PvtResultActivity.class);
i.putExtra(Result.TAG, result);
startActivity(i);
finish();
}
/**
* Sets the number inside the clock and duration units, shown during the intro.
*/
private void setDurationUnitsAndClockText(String digits, String unit) {
mClockTv.setText(digits);
mClockTv.requestLayout();
mDurationUnitsTv.setText(unit);
mDurationUnitsTv.requestLayout();
}
}
|
package src;
import java.io.FileNotFoundException;
public class MainMix {
public static void main(String[] args) {
Mix mx=new Mix();
System.out.println();
mx.comandsEjecution();
}
}
|
package com.example.bigdata.pojo;
public class AirIndex {
private String cityName;
private float co;
private int no2;
private int so2;
private int o3;
public AirIndex() {}
public AirIndex(String cityName, float co, int no2, int so2, int o3) {
this.cityName = cityName;
this.co = co;
this.no2 = no2;
this.so2 = so2;
this.o3 = o3;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public float getCo() {
return co;
}
public void setCo(float co) {
this.co = co;
}
public int getNo2() {
return no2;
}
public void setNo2(int no2) {
this.no2 = no2;
}
public int getSo2() {
return so2;
}
public void setSo2(int so2) {
this.so2 = so2;
}
public int getO3() {
return o3;
}
public void setO3(int o3) {
this.o3 = o3;
}
}
|
package net.networksaremadeofstring.droidsift.curator;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class Tutorial_1_2 extends Fragment
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.tutorial_1_2, container, false);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
((TextView) getView().findViewById(R.id.TitleText)).setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/league_gothic.otf"));
((TextView) getView().findViewById(R.id.InfrastructureTitle)).setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/league_gothic.otf"));
((TextView) getView().findViewById(R.id.AnalyticsTitle)).setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/league_gothic.otf"));
((TextView) getView().findViewById(R.id.FireHoseTitle)).setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/league_gothic.otf"));
((ImageView) getView().findViewById(R.id.NextTabImage)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
v.performHapticFeedback(3);
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
Tutorial_2 fragment = new Tutorial_2();
fragmentTransaction.replace(R.id.TutorialFragmentContainer, fragment);
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentTransaction.commit();
((ImageView) getActivity().findViewById(R.id.WhatIsDataSiftTab)).setImageResource(R.drawable.tutorial_what_is_datasift_inactive);
((ImageView) getActivity().findViewById(R.id.WhatIsAStreamTab)).setImageResource(R.drawable.tutorial_what_is_a_stream);
((ImageView) getActivity().findViewById(R.id.WhatIsCSDLTab)).setImageResource(R.drawable.tutorial_what_is_csdl_inactive);
((ImageView) getActivity().findViewById(R.id.CreateAStreamTab)).setImageResource(R.drawable.tutorial_how_to_create_inactive);
}
});
}
}
|
package com.example.sys.job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
public class ScheduledTask {
private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class);
// @Scheduled(fixedRate = 5000)
public void rate() {
logger.info("com.example.sys.job.ScheduledTasks.rate()");
}
// @Scheduled(cron = "0/10 * * * * ?")
public void cron() {
logger.info("com.example.sys.job.ScheduledTasks.cron()");
}
}
|
package com.github.tobby48.java.scene1;
/**
* <pre>
* com.github.tobby48.java.scene1
* OperatorIncrement.java
*
* 설명 : 증감연산자 테스트
* </pre>
*
* @since : 2017. 6. 28.
* @author : tobby48
* @version : v1.0
*/
public class OperatorIncrement {
public static void main(String args[]) {
int i = 0, b;
b = i++;
// b = i;
// i = i + 1;
System.out.println("(i++) b = " + b);
System.out.println("(i++) i = " + i);
i = 0;
b = ++i;
// i = i + 1;
// b = i;
System.out.println("(++i) b = " + b);
System.out.println("(++i) i = " + i);
char c = 'A';
System.out.println("c++ = " + c++);
System.out.println("++c = " + ++c);
}
} |
package different;
public class Diff_34 {
final static double PI = 3.14;
public static int Proizv(int a, int b, int c) {
System.out.println(a * b * c);
return a * b * c;
}
static void Del(int a, int b) {
System.out.println("Целое частное " + a / b + " Остаток " + a % b);
}
double AreaCircle(double radius) {
return PI * radius * radius;
}
static double Circumference(double radius) {
return 2 * PI * radius;
}
void Res(double radius) {
System.out.println("Дано: радиус " + radius);
System.out.println("Площадь круга равна: " + AreaCircle(radius));
System.out.println("Длина окружности равна: " + Circumference(radius));
}
}
class Diff_34Test{
public static void main(String[] args) {
Diff_34.Proizv(2, 3, 1);
Diff_34 d1 = new Diff_34();
d1.Proizv(2, 3, 1);
Diff_34.Del(26, 4);
d1.Del(7, 4);
d1.AreaCircle(5);
Diff_34.Circumference(5);
d1.Res(5);
}
}
|
/**
* Copyright (C) Alibaba Cloud Computing, 2012
* All rights reserved.
*
* 版权所有 (C)阿里巴巴云计算,2012
*/
package com.aliyun.oss.model;
import java.util.ArrayList;
import java.util.List;
public class SetBucketLifecycleRequest extends WebServiceRequest {
private String bucketName;
private List<LifecycleRule> lifecycleRules = new ArrayList<LifecycleRule>();
private static final int LifecycleRuleLimit = 1000;
public SetBucketLifecycleRequest(String bucketName) {
this.bucketName = bucketName;
}
public String getBucketName() {
return bucketName;
}
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
public List<LifecycleRule> getLifecycleRules() {
return lifecycleRules;
}
public void setLifecycleRules(List<LifecycleRule> lifecycleRules) {
if (lifecycleRules.size() > LifecycleRuleLimit) {
throw new IllegalArgumentException("One bucket not allow exceed one thousand items of LifecycleRules.");
}
this.lifecycleRules = lifecycleRules;
}
public void AddLifecycleRule(LifecycleRule lifecycleRule)
{
if (lifecycleRule == null) {
throw new IllegalArgumentException("lifecycleRule should not be null or empty.");
}
if (this.lifecycleRules.size() >= LifecycleRuleLimit) {
throw new IllegalArgumentException("One bucket not allow exceed one thousand items of LifecycleRules.");
}
boolean hasSetExpirationTime = (lifecycleRule.getExpirationTime() != null);
boolean hasSetExpirationDays =(lifecycleRule.getExpriationDays() != 0);
if ((!hasSetExpirationTime && !hasSetExpirationDays)
|| (hasSetExpirationTime && hasSetExpirationDays)) {
throw new IllegalArgumentException("Only one expiration property should be specified.");
}
if (lifecycleRule.getStatus() == LifecycleRule.RuleStatus.Unknown) {
throw new IllegalArgumentException("RuleStatus property should be specified with 'Enabled' or 'Disabled'.");
}
this.lifecycleRules.add(lifecycleRule);
}
}
|
package ru.timxmur.test.tochka.controller;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import ru.timxmur.test.tochka.domain.UserCreateForm;
import ru.timxmur.test.tochka.domain.validator.UserCreateFormValidator;
import ru.timxmur.test.tochka.service.UserService;
import javax.validation.Valid;
import java.util.NoSuchElementException;
@Controller
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
private final UserCreateFormValidator userCreateFormValidator;
@InitBinder("form")
public void initBinder(WebDataBinder binder) {
binder.addValidators(userCreateFormValidator);
}
@PreAuthorize("@currentUserServiceImpl.canAccessUser(principal, #id)")
@RequestMapping("/user/{id}")
public ModelAndView getUserPage(@PathVariable Long id) {
return new ModelAndView("user", "user", userService.getUserById(id)
.orElseThrow(() -> new NoSuchElementException(String.format("User=%s not found", id))));
}
@PreAuthorize("hasAnyAuthority('ADMIN')")
@RequestMapping(value = "/user/update", method = RequestMethod.GET)
public ModelAndView getUserCreatePage() {
return new ModelAndView("user_create", "form", new UserCreateForm());
}
@PreAuthorize("hasAnyAuthority('ADMIN')")
@RequestMapping(value = "/user/update", method = RequestMethod.POST)
public String handleUserCreateForm(@Valid @ModelAttribute("form") UserCreateForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "user_create";
}
try {
userService.create(form);
} catch (DataIntegrityViolationException e) {
bindingResult.reject("email.exists", "Email already exists");
return "user_create";
}
return "redirect:/users";
}
}
|
package com.touchtrip.Allplanner.map.model.service;
import java.sql.Connection;
import java.util.ArrayList;
import com.touchtrip.Allplanner.map.model.dao.PlannerDAO;
import com.touchtrip.Allplanner.map.model.vo.MapData;
import static com.touchtrip.Allplanner.common.JDBCTemplate.*;
public class MapService {
private Connection con;
private PlannerDAO dao = new PlannerDAO();
public ArrayList<MapData> searchDate(String type, String keyword) {
con = getConnection();
ArrayList<MapData> mapList = dao.searchData(con, type, keyword);
close(con);
return mapList;
}
}
|
package com.oleksii.arrmy.CrewPortal.service;
import com.oleksii.arrmy.CrewPortal.dao.WorkerDaoImpl;
import com.oleksii.arrmy.CrewPortal.model.Worker;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
/**
* Checking whether WorkerService invokes WorkerDAO
*/
@RunWith(MockitoJUnitRunner.class)
public class WorkerServiceImpMockTest {
@Mock
WorkerDaoImpl workerDao;
@InjectMocks
WorkerServiceImp workerService;
@Test
public void save() {
Worker workerExample = new Worker();
workerExample.setId(119);
workerExample.setName("workerName");
workerService.save(workerExample);
verify(workerDao, times(1)).save(workerExample);
}
@Test
public void get() {
workerService.get(Mockito.anyInt());
verify(workerDao, times(1)).get(Mockito.anyInt());
}
@Test
public void list() {
workerService.list();
verify(workerDao, times(1)).list();
}
@Test
public void update() {
Worker worker = new Worker();
worker.setId(1);
workerService.update(1, worker);
verify(workerDao, times(1)).update(1, worker);
}
@Test
public void delete() {
workerService.delete(Mockito.anyInt());
verify(workerDao, times(1)).delete(Mockito.anyInt());
}
}
|
package com.juancrud.logllamadas;
import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CallLog;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView tvLlamadas;
private static final int CODIGO_SOLICITUD_PERMISO = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvLlamadas = (TextView) findViewById(R.id.tvLlamadas);
}
public void mostrarLlamadas(View view) {
if (checkStatusPermiso()) {
consularCPLlamadas();
} else {
solicitarPermiso();
}
}
/* Consulta al content provider */
public void consularCPLlamadas() {
tvLlamadas.setText("");
Uri direccionUriLlamadas = CallLog.Calls.CONTENT_URI;
String[] campos = {
CallLog.Calls.NUMBER, //Numero
CallLog.Calls.DATE, //Fecha
CallLog.Calls.TYPE, //Tipo de llamadas (perdida, espera, etc)
CallLog.Calls.DURATION //Duracion
};
ContentResolver contentResolver = getContentResolver();
Cursor registros = contentResolver.query(direccionUriLlamadas, campos, null, null, CallLog.Calls.DATE + " DESC");
while(registros.moveToNext()){
String numero = registros.getString(registros.getColumnIndex(campos[0]));
long fecha = registros.getLong(registros.getColumnIndex(campos[1]));
int tipo = registros.getInt(registros.getColumnIndex(campos[2]));
String duracion = registros.getString(registros.getColumnIndex(campos[3]));
String tipoLlamada;
switch (tipo){
case CallLog.Calls.INCOMING_TYPE:
tipoLlamada = getString(R.string.entrada);
break;
case CallLog.Calls.MISSED_TYPE:
tipoLlamada = getString(R.string.perdida);
break;
case CallLog.Calls.OUTGOING_TYPE:
tipoLlamada = getString(R.string.salida);
break;
default:
tipoLlamada = getString(R.string.desconocida);
}
String detalle = getString(R.string.lblNumero) + numero + "\n" +
getString(R.string.lblFecha) + DateFormat.format("dd/MM/yy k:mm", fecha) + "\n" +
getString(R.string.lblTipo) + tipoLlamada + "\n" +
getString(R.string.lblDuracion) + duracion +" segs."+ "\n\n";
tvLlamadas.append(detalle);
}
}
/* Permisos */
public void solicitarPermiso() {
//ReadCallLog
boolean solicitarPermisoRCL = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CALL_LOG);
//WriteCallLog
boolean solicitarPermisoWCL = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_CALL_LOG);
if(solicitarPermisoRCL && solicitarPermisoWCL){
Toast.makeText(this, "Los permisos fueron otorgados", Toast.LENGTH_SHORT).show();
}
else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG}, CODIGO_SOLICITUD_PERMISO);
}
}
public boolean checkStatusPermiso() {
boolean permisoRCL = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED;
boolean permisoWCL = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALL_LOG) == PackageManager.PERMISSION_GRANTED;
return permisoRCL && permisoWCL;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch(requestCode){
case CODIGO_SOLICITUD_PERMISO:
if(checkStatusPermiso()){
Toast.makeText(this, "Ya esta activo el permiso", Toast.LENGTH_SHORT).show();
consularCPLlamadas();
}
else{
Toast.makeText(this, "No se activo el permiso", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
|
package com.example.course;
public class ListProvider {
private String week,lecture,lab,lecturetopic,labtopic;
public ListProvider (String week,String lecture,String lab,String lecturetopic,String labtopic,String lectureassess,String labassess){
this.setWeek(week);
this.setLab(lab);
this.setLecture(lecture);
this.setLabtopic(labtopic);
this.setLecturetopic(lecturetopic);
}
public String getWeek() {
return week;
}
public void setWeek(String week) {
this.week = week;
}
public String getLecture() {
return lecture;
}
public void setLecture(String lecture) {
this.lecture = lecture;
}
public String getLab() {
return lab;
}
public void setLab(String lab) {
this.lab = lab;
}
public String getLecturetopic() {
return lecturetopic;
}
public void setLecturetopic(String lecturetopic) {
this.lecturetopic = lecturetopic;
}
public String getLabtopic() {
return labtopic;
}
public void setLabtopic(String labtopic) {
this.labtopic = labtopic;
}
}
|
package sonar.minimodem;
/** Modo de transmisión para el ejecutable de minimodem. */
public enum BaudMode {
BELL202,
BELL103,
RTTY,
TDD,
SAME,
}
|
package com.train.amm;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class OpenClothActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_cloth);
Bitmap bitmapSrc = BitmapFactory.decodeResource(getResources(),R.drawable.awaiyi);
final Bitmap bitmapCopy = Bitmap.createBitmap(bitmapSrc.getWidth(),bitmapSrc.getHeight(),bitmapSrc.getConfig());
Paint paint = new Paint();
Canvas canvas = new Canvas(bitmapCopy);
canvas.drawBitmap(bitmapSrc,new Matrix(),paint);
final ImageView imageView = findViewById(R.id.iv_waiyi);
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_MOVE :
int x = (int) event.getX();
int y = (int) event.getY();
for(int i = -25; i <= 25; i++){
for(int j = -25; j <= 25; j++){
//把用户划过的坐标置为透明色
//改变指定的像素颜色
if(Math.sqrt(i*i + j*j) <= 25){
if(x + i < bitmapCopy.getWidth() && y + j < bitmapCopy.getHeight() && x + i >= 0 && y + j >= 0){
bitmapCopy.setPixel(x + i, y + j, Color.TRANSPARENT);
imageView.setImageBitmap(bitmapCopy);
}
}
}
}
break;
}
return true;
}
});
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.network.filter;
import xyz.noark.core.lang.ByteArray;
import xyz.noark.core.network.NetworkPacket;
import xyz.noark.network.IncodeSession;
/**
* 一种默认的封包检测过滤实现.
*
* @author 小流氓[176543888@qq.com]
* @since 3.1
*/
public class DefaultPacketCheckFilter extends AbstractPacketCheckFilter {
@Override
protected boolean checkPacketIncode(IncodeSession session, NetworkPacket packet) {
boolean result = packet.getIncode() > session.getIncode() || session.getIncode() == 0xFFFF;
if (result) {
session.setIncode(packet.getIncode());
}
return result;
}
@Override
protected boolean checkPacketChecksum(NetworkPacket packet) {
final ByteArray data = packet.getByteArray();
// 一种简单的计算方案....
int sum = 0;
for (int i = 0, len = data.length(); i < len; i++) {
sum += (data.getByte(i) & 0xFF);
}
return sum == packet.getChecksum();
}
} |
package com.tw.bean;
import com.tw.GradeReporter;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ReportTest {
@Test
public void getTotalAverageTest() {
GradeReporter mockGradeReporter1 = mock(GradeReporter.class);
when(mockGradeReporter1.reportTotal()).thenReturn(1.2);
GradeReporter mockGradeReporter2 = mock(GradeReporter.class);
when(mockGradeReporter2.reportTotal()).thenReturn(1.3);
Report report = new Report();
report.setPickedStudent(Arrays.asList(mockGradeReporter1, mockGradeReporter2));
Assert.assertEquals(1.25, report.getTotalAverage(), 0.001);
}
@Test
public void getTotalMedian() {
GradeReporter mockGradeReporter1 = mock(GradeReporter.class);
when(mockGradeReporter1.reportTotal()).thenReturn(1.2);
GradeReporter mockGradeReporter2 = mock(GradeReporter.class);
when(mockGradeReporter2.reportTotal()).thenReturn(1.3);
Report report = new Report();
report.setPickedStudent(Arrays.asList(mockGradeReporter1, mockGradeReporter2));
Assert.assertEquals(1.25, report.getTotalMedian(), 0.001);
report.setPickedStudent(Arrays.asList(mockGradeReporter1));
Assert.assertEquals(1.2, report.getTotalMedian(), 0.001);
}
}
|
package com.expriceit.maserven.activities;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Layout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.expriceit.maserven.MaservenApplication;
import com.expriceit.maserven.R;
import com.expriceit.maserven.entities.ValidaPinAcceso;
import com.expriceit.maserven.utils.SharedPreferencesManager;
import com.expriceit.maserven.utils.Utils;
import mehdi.sakout.fancybuttons.FancyButton;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by stalyn on 21/11/2017.
*/
public class ValidaPin extends Activity implements View.OnKeyListener {
EditText pin,edtPin2,edtPin1;
String PREFERENCIA_INICIO = "maservenapp";
String KEY_PIN = "pin_acceso";
String KEY_USER = "usuario";
LinearLayout layout1,layout2,layout3;
FancyButton btn_Registra_PIN;
ProgressBar load_progreesbar;
private Call<ValidaPinAcceso.getPinAcceso> CallPin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_valida_pin);
pin = (EditText) findViewById(R.id.editContrasenia);
edtPin1 = (EditText) findViewById(R.id.editPin1);
edtPin2 = (EditText) findViewById(R.id.editPin2);
load_progreesbar = (ProgressBar) findViewById(R.id.progressBar2);
btn_Registra_PIN = (FancyButton) findViewById(R.id.btnRegistraPIN);
layout1 = (LinearLayout) findViewById(R.id.lytpin1);
layout2 = (LinearLayout) findViewById(R.id.lytpin2);
layout3 = (LinearLayout) findViewById(R.id.lytpin3);
layout1.setVisibility(View.GONE);
layout2.setVisibility(View.GONE);
layout3.setVisibility(View.GONE);
btn_Registra_PIN.setVisibility(View.GONE);
if(SharedPreferencesManager.getValorEsperado(getApplicationContext(),PREFERENCIA_INICIO,KEY_PIN)!= null ){
layout3.setVisibility(View.VISIBLE);
pin.setOnKeyListener(this);
}else{
layout1.setVisibility(View.VISIBLE);
layout2.setVisibility(View.VISIBLE);
btn_Registra_PIN.setVisibility(View.VISIBLE);
btn_Registra_PIN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(edtPin1.getText().toString().length()<4){
Utils.generarAlerta(ValidaPin.this, "ALERTA!", "El pin debe contener 4 digitos numéricos");
return;
}
if(edtPin1.getText().toString()== ""){
Utils.generarAlerta(ValidaPin.this, "ALERTA!", "Existe Campos Vacios");
return;
}
if(edtPin2.getText().toString()== ""){
Utils.generarAlerta(ValidaPin.this, "ALERTA!", "Existe Campos Vacios");
return;
}
if(edtPin1.getText().toString().equals(edtPin2.getText().toString())){
save_pin(edtPin1.getText().toString());
Intent intent = new Intent(ValidaPin.this, MainActivity.class);
startActivity(intent);
finish();
}else {
Utils.generarAlerta(ValidaPin.this, "ALERTA!", "Deben de ser iguales los valores del PIN.");
}
}
});
}
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
pin = (EditText) findViewById(R.id.editContrasenia);
Log.w("Acceso_pin >>> ", pin.getText().toString());
if(pin.getText().toString().length()==4){
String pinlocal="";
String pintmp="";
if(SharedPreferencesManager.getValorEsperado(getApplicationContext(),PREFERENCIA_INICIO,KEY_PIN)!= null ){
pinlocal=SharedPreferencesManager.getValorEsperado(getApplicationContext(),PREFERENCIA_INICIO,KEY_PIN);
pinlocal=pinlocal.trim();
Log.w("Acceso_pin >>> ", "pinlocal: "+pinlocal);
pintmp= pin.getText().toString();
pintmp =pintmp.trim();
Log.w("Acceso_pin >>> ", "pintemp: "+pintmp);
Log.w("Acceso_pin", "Validando preferencias PIN"+SharedPreferencesManager.getValorEsperado(getApplicationContext(),PREFERENCIA_INICIO,KEY_PIN));
if(pintmp.toString().compareTo(pinlocal.toString())==0){
Intent intent = new Intent(ValidaPin.this, MainActivity.class);
startActivity(intent);
finish();
}else{
Utils.generarAlerta(ValidaPin.this, "ALERTA!", "El Pin es incorrecto");
Log.w("Acceso_pin >>> ", "El Pin regitrado es incorrecto");
pin.setText("");
// return true;
}
}else {
load_progreesbar.setVisibility(View.VISIBLE);
Log.w("Acceso_pin", "pin:"+pin.getText().toString());
Acceso_pin(SharedPreferencesManager.getValorEsperado(getApplicationContext(),PREFERENCIA_INICIO,KEY_USER),pin.getText().toString());
}
return true;
}else{
return false;
}
}
private void Acceso_pin(String Usuario, String clave_pin){
//load_progreesbar.setVisibility(View.VISIBLE);
Log.w("Acceso_pin", "ValidaPinAcceso acceso_pin");
ValidaPinAcceso acceso_pin = MaservenApplication.getApplication().getRestAdapter().create(ValidaPinAcceso.class);
Log.w("Acceso_pin", "CallPin acceso_pin");
try{
CallPin = acceso_pin.validaPinWS(Usuario,clave_pin);
Log.w("Acceso_pin", "Usuario: "+Usuario+" clave_pin:"+clave_pin);
} catch (IllegalArgumentException e1) {
//Toast.makeText(getApplicationContext(),"No se puede conectar con la radio.",Toast.LENGTH_LONG).show();
Log.w("Acceso_pin", "Exception: "+e1.getMessage()+"-- msg"+e1.getStackTrace());
e1.printStackTrace();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.w("Acceso_pin", "CallPin");
CallPin.enqueue(new Callback<ValidaPinAcceso.getPinAcceso>() {
@Override
public void onResponse(Call<ValidaPinAcceso.getPinAcceso> call, Response<ValidaPinAcceso.getPinAcceso> response) {
String err = "";
try {
// err = response.errorBody().toString();
Log.w("Acceso_pin", "Consultando respuesta" +err );
if (err.equalsIgnoreCase("")) {
if (response.body() != null) {
if (response.isSuccess()) {
ValidaPinAcceso.getPinAcceso otp = response.body();
Log.w("Acceso_pin", "response -> "+otp.getMensaje() + "");
Log.w("Acceso_pin", "codigo -> "+otp.getCodigo() + "");
// Log.w("Acceso_usuario", "idusuario -> "+Usuario+ "");
if (otp.getCodigo().equals("1")){
save_pin(pin.getText().toString());
Log.w("Valida PIN >>", "ConsultaWS PIN:"+pin.getText().toString());
Intent intent = new Intent(ValidaPin.this, MainActivity.class);
startActivity(intent);
finish();
load_progreesbar.setVisibility(View.INVISIBLE);
}else{
Utils.generarAlerta(ValidaPin.this, "ALERTA!", otp.getMensaje());
load_progreesbar.setVisibility(View.INVISIBLE);
pin.setText("");
}
} else {
Log.e("Acceso_pin", "Error en el webservice, success false");
load_progreesbar.setVisibility(View.INVISIBLE);
}
} else {
Log.e("Acceso_pin", "Error de web service, no viene json");
load_progreesbar.setVisibility(View.INVISIBLE);
}
} else {
Log.e("Acceso_pin", "Error en el webservice " + err);
load_progreesbar.setVisibility(View.INVISIBLE);
}
// Log.w("Acceso_usuario", "ERROR: "+err);
} catch (Exception e) {
// err = "";
Log.w("Acceso_pin", "Exception: "+e.getMessage()+"-- msg"+e.getStackTrace());
load_progreesbar.setVisibility(View.INVISIBLE);
}
}
@Override
public void onFailure(Call<ValidaPinAcceso.getPinAcceso> call, Throwable t) {
//Log.w("111111", t.getMessage());
Log.w("Acceso_pin", "onFailure - "+t.getMessage());
load_progreesbar.setVisibility(View.INVISIBLE);
}
});
Log.w("Acceso_pin", "Fin CallUser");
}
private void save_pin(String pin) {
Log.w("Acceso_pin", "Registrando PIN ->"+pin);
SharedPreferencesManager.setValor(this,PREFERENCIA_INICIO, pin, KEY_PIN);
Log.w("Acceso_pin", "PIN Registrado ->"+SharedPreferencesManager.getValorEsperado(this,PREFERENCIA_INICIO,KEY_PIN));
Log.w("Acceso_pin", "Mostrar Pin: ->"+SharedPreferencesManager.getValorEsperado(this,PREFERENCIA_INICIO,KEY_PIN));
}
}
|
package Study2;
import java.util.*;
public class S3 {
public static void main(String args[]){
LinkedList<String> sites = new LinkedList<>();
sites.add("Ohh");
sites.add("whh");
sites.add("chh");
sites.add("ahh");
sites.addFirst("haha");
sites.addAll(2,sites);
System.out.println(sites);
}
}
|
package org.reactome.web.nursa.client.details.tabs.dataset.widgets;
import org.reactome.web.nursa.client.details.tabs.dataset.BinomialCompletedHandler;
import org.reactome.web.nursa.client.details.tabs.dataset.ComparisonAnalysisCompletedHandler;
import org.reactome.web.nursa.client.details.tabs.dataset.GseaCompletedHandler;
import org.reactome.web.nursa.client.details.tabs.dataset.NursaPathwaySelectedHandler;
import org.reactome.web.nursa.client.details.tabs.dataset.PathwayLoader;
import org.reactome.web.nursa.client.search.DataPointsLoadedEvent;
import org.reactome.web.nursa.client.search.ExperimentLoadedHandler;
import org.reactome.web.pwp.client.common.handlers.AnalysisResetHandler;
import org.reactome.web.pwp.client.details.tabs.DetailsTab;
import org.reactome.web.pwp.client.details.tabs.analysis.widgets.results.handlers.PathwayHoveredResetHandler;
import org.reactome.nursa.model.DataSet;
import org.reactome.nursa.model.Experiment;
/**
* @author Fred Loney <loneyf@ohsu.edu>
*/
public interface DataSetTab {
interface Presenter extends DetailsTab.Presenter, ExperimentLoadedHandler,
GseaCompletedHandler, BinomialCompletedHandler, ComparisonAnalysisCompletedHandler,
NursaPathwaySelectedHandler, PathwayHoveredResetHandler, AnalysisResetHandler {
}
interface Display extends DetailsTab.Display<Presenter> {
void showDetails(DataPointsLoadedEvent event);
}
}
|
package org.dajlab.mondialrelayapi.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Classe Java pour anonymous complex type.
*
* <p>
* Le fragment de schéma suivant indique le contenu attendu figurant dans cette
* classe.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Enseigne" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Pays" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="NumPointRelais" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Ville" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="CP" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Latitude" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Longitude" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Taille" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Poids" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Action" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="DelaiEnvoi" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="RayonRecherche" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="TypeActivite" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="NACE" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Security" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "enseigne", "pays", "numPointRelais", "ville", "cp", "latitude", "longitude",
"taille", "poids", "action", "delaiEnvoi", "rayonRecherche", "typeActivite", "nace", "security" })
@XmlRootElement(name = "WSI3_PointRelais_Recherche")
public class WSI3PointRelaisRecherche {
@XmlElement(name = "Enseigne")
protected String enseigne;
@XmlElement(name = "Pays")
protected String pays;
@XmlElement(name = "NumPointRelais")
protected String numPointRelais;
@XmlElement(name = "Ville")
protected String ville;
@XmlElement(name = "CP")
protected String cp;
@XmlElement(name = "Latitude")
protected String latitude;
@XmlElement(name = "Longitude")
protected String longitude;
@XmlElement(name = "Taille")
protected String taille;
@XmlElement(name = "Poids")
protected String poids;
@XmlElement(name = "Action")
protected String action;
@XmlElement(name = "DelaiEnvoi")
protected String delaiEnvoi;
@XmlElement(name = "RayonRecherche")
protected String rayonRecherche;
@XmlElement(name = "TypeActivite")
protected String typeActivite;
@XmlElement(name = "NACE")
protected String nace;
@XmlElement(name = "Security")
protected String security;
/**
* Obtient la valeur de la propriété enseigne.
*
* @return possible object is {@link String }
*
*/
public String getEnseigne() {
return enseigne;
}
/**
* Définit la valeur de la propriété enseigne.
*
* @param value
* allowed object is {@link String }
*
*/
public void setEnseigne(String value) {
this.enseigne = value;
}
/**
* Obtient la valeur de la propriété pays.
*
* @return possible object is {@link String }
*
*/
public String getPays() {
return pays;
}
/**
* Définit la valeur de la propriété pays.
*
* @param value
* allowed object is {@link String }
*
*/
public void setPays(String value) {
this.pays = value;
}
/**
* Obtient la valeur de la propriété numPointRelais.
*
* @return possible object is {@link String }
*
*/
public String getNumPointRelais() {
return numPointRelais;
}
/**
* Définit la valeur de la propriété numPointRelais.
*
* @param value
* allowed object is {@link String }
*
*/
public void setNumPointRelais(String value) {
this.numPointRelais = value;
}
/**
* Obtient la valeur de la propriété ville.
*
* @return possible object is {@link String }
*
*/
public String getVille() {
return ville;
}
/**
* Définit la valeur de la propriété ville.
*
* @param value
* allowed object is {@link String }
*
*/
public void setVille(String value) {
this.ville = value;
}
/**
* Obtient la valeur de la propriété cp.
*
* @return possible object is {@link String }
*
*/
public String getCP() {
return cp;
}
/**
* Définit la valeur de la propriété cp.
*
* @param value
* allowed object is {@link String }
*
*/
public void setCP(String value) {
this.cp = value;
}
/**
* Obtient la valeur de la propriété latitude.
*
* @return possible object is {@link String }
*
*/
public String getLatitude() {
return latitude;
}
/**
* Définit la valeur de la propriété latitude.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLatitude(String value) {
this.latitude = value;
}
/**
* Obtient la valeur de la propriété longitude.
*
* @return possible object is {@link String }
*
*/
public String getLongitude() {
return longitude;
}
/**
* Définit la valeur de la propriété longitude.
*
* @param value
* allowed object is {@link String }
*
*/
public void setLongitude(String value) {
this.longitude = value;
}
/**
* Obtient la valeur de la propriété taille.
*
* @return possible object is {@link String }
*
*/
public String getTaille() {
return taille;
}
/**
* Définit la valeur de la propriété taille.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTaille(String value) {
this.taille = value;
}
/**
* Obtient la valeur de la propriété poids.
*
* @return possible object is {@link String }
*
*/
public String getPoids() {
return poids;
}
/**
* Définit la valeur de la propriété poids.
*
* @param value
* allowed object is {@link String }
*
*/
public void setPoids(String value) {
this.poids = value;
}
/**
* Obtient la valeur de la propriété action.
*
* @return possible object is {@link String }
*
*/
public String getAction() {
return action;
}
/**
* Définit la valeur de la propriété action.
*
* @param value
* allowed object is {@link String }
*
*/
public void setAction(String value) {
this.action = value;
}
/**
* Obtient la valeur de la propriété delaiEnvoi.
*
* @return possible object is {@link String }
*
*/
public String getDelaiEnvoi() {
return delaiEnvoi;
}
/**
* Définit la valeur de la propriété delaiEnvoi.
*
* @param value
* allowed object is {@link String }
*
*/
public void setDelaiEnvoi(String value) {
this.delaiEnvoi = value;
}
/**
* Obtient la valeur de la propriété rayonRecherche.
*
* @return possible object is {@link String }
*
*/
public String getRayonRecherche() {
return rayonRecherche;
}
/**
* Définit la valeur de la propriété rayonRecherche.
*
* @param value
* allowed object is {@link String }
*
*/
public void setRayonRecherche(String value) {
this.rayonRecherche = value;
}
/**
* Obtient la valeur de la propriété typeActivite.
*
* @return possible object is {@link String }
*
*/
public String getTypeActivite() {
return typeActivite;
}
/**
* Définit la valeur de la propriété typeActivite.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTypeActivite(String value) {
this.typeActivite = value;
}
/**
* Obtient la valeur de la propriété nace.
*
* @return possible object is {@link String }
*
*/
public String getNACE() {
return nace;
}
/**
* Définit la valeur de la propriété nace.
*
* @param value
* allowed object is {@link String }
*
*/
public void setNACE(String value) {
this.nace = value;
}
/**
* Obtient la valeur de la propriété security.
*
* @return possible object is {@link String }
*
*/
public String getSecurity() {
return security;
}
/**
* Définit la valeur de la propriété security.
*
* @param value
* allowed object is {@link String }
*
*/
public void setSecurity(String value) {
this.security = value;
}
}
|
package com.alex.eat;
public interface Wet {
void dry();
void namochit();
boolean isWet();
}
|
package Utils;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.io.*;
import java.util.Map;
import java.util.Properties;
import static Utils.ConstantsUtils.CONFIG_FILE;
import static Utils.ConstantsUtils.CONFIG_PATH;
public class ConfigReader {
public static String URL;
public static String ENV;
public static String BROWSER;
public static boolean WEBDRIVER_MANAGER;
public static void readConfigFile() {
try(InputStream input = new FileInputStream( CONFIG_PATH + CONFIG_FILE)) {
Properties props = new Properties();
props.load(input);
String port = props.getProperty("URL_PORT", "80");
String hostname = props.getProperty("URL_HOSTNAME", "localhost");
String proto = props.getProperty("URL_PROTOCOL", "http");
URL = proto + "://" + hostname + ":" + port + "/";
ENV = props.getProperty("CURRENT_ENV");
BROWSER = props.getProperty("RUN_BROWSER");
WEBDRIVER_MANAGER = Boolean.parseBoolean(props.getProperty("WEB_DRIVER_MANAGER"));
//Log.info(URL);
}
catch(FileNotFoundException fnf){
Log.error("File not found: "+ CONFIG_PATH + CONFIG_FILE);
Log.fatal(GeneralUtils.stackTraceConvert(fnf.getStackTrace()));
}
catch (IOException ioex){
Log.error(ioex.getMessage());
Log.fatal(GeneralUtils.stackTraceConvert((ioex.getStackTrace())));
}
}
public static void writeConfigFIle(Map<String, String> configs){
try(OutputStream output = new FileOutputStream( CONFIG_PATH + CONFIG_FILE)) {
Properties props = new Properties();
for (String key: configs.keySet()){
props.setProperty(key, configs.get(key));
}
props.store(output, null);
}
catch(FileNotFoundException fnf){
Log.error("File not found: "+ CONFIG_PATH + CONFIG_FILE);
Log.fatal(GeneralUtils.stackTraceConvert(fnf.getStackTrace()));
}
catch (IOException ioex){
Log.error(ioex.getMessage());
Log.fatal(GeneralUtils.stackTraceConvert((ioex.getStackTrace())));
}
}
}
|
package application.client.ui.login;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
public class LoginView extends Composite {
interface LoginViewUiBinder extends UiBinder<HTMLPanel, LoginView> {
}
@UiField
Button loginBtn;
@UiField
TextBox emailTxtBox;
@UiField
PasswordTextBox passwordTxtBox;
@UiField
Label forgotPassword;
private static LoginViewUiBinder ourUiBinder = GWT.create(LoginViewUiBinder.class);
public LoginView() {
initWidget(ourUiBinder.createAndBindUi(this));
emailTxtBox.getElement().setPropertyString("placeholder", "Email");
passwordTxtBox.getElement().setPropertyString("placeholder", "adgangskode");
}
/**
* Metode, der tilføjer en click handler på login-knappen
*
* @param clickHandler
*/
public void addClickHandlers(ClickHandler clickHandler) {
loginBtn.addClickHandler(clickHandler);
forgotPassword.addClickHandler(clickHandler);
}
/**
*
*/
public void clearTextBoxFields() {
emailTxtBox.setText("");
passwordTxtBox.setText("");
}
/**
* Getter metoder
*/
public Button getLoginBtn() {
return loginBtn;
}
public Label getForgotPassword() {
return forgotPassword;
}
public TextBox getEmailTxtBox() {
return emailTxtBox;
}
public PasswordTextBox getPasswordTxtBox() {
return passwordTxtBox;
}
} |
package com.zantong.mobilecttx.api;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
public abstract class CallBack<T> implements Handler.Callback {
protected static final int SUCCESS = 0;
protected static final int FAIL = 1;
protected static final int START = 2;
protected static final int FINISH = 3;
private Handler mHandler;
public CallBack() {
if (Looper.myLooper() != null)
mHandler = new Handler(this);
}
public void onStart() {
}
public void onFinish() {
}
public abstract void onSuccess(T result);
public void onError(String errorCode, String msg) {
}
protected void sendSuccessMessage(T result) {
sendMessage(obtainMessage(SUCCESS, new Object[] { result }));
}
protected void sendFailMessage(String errorCode, String msg) {
sendMessage(obtainMessage(FAIL, new Object[] { errorCode, msg }));
}
protected void sendStartMessage() {
sendMessage(obtainMessage(START, null));
}
protected void sendEndMessage() {
sendMessage(obtainMessage(FINISH, null));
}
protected void handleSuccessMessage(T result) {
onSuccess(result);
}
protected void handleFailMessage(String errorCode, String msg) {
onError(errorCode, msg);
}
@Override
public boolean handleMessage(Message message) {
switch (message.what) {
case START:
onStart();
return true;
case FINISH:
onFinish();
return true;
case SUCCESS:
Object[] successResponse = (Object[]) message.obj;
handleSuccessMessage(((T) successResponse[0]));
return true;
case FAIL:
Object[] failResponse = (Object[]) message.obj;
handleFailMessage((failResponse[0].toString()),
failResponse[1].toString());
return true;
}
return false;
}
protected void sendMessage(Message message) {
if (mHandler != null) {
mHandler.sendMessage(message);
} else {
handleMessage(message);
}
}
protected Message obtainMessage(int responseMessage, Object response) {
Message message = null;
if (mHandler != null) {
message = mHandler.obtainMessage(responseMessage, response);
} else {
message = Message.obtain();
message.what = responseMessage;
message.obj = response;
}
return message;
}
} |
package com.Login_Fuctionality_OHRM;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class OrangeHRM_LoginFuncitonality_ExcelOperations {
public static void main(String[] args) throws IOException {
System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe");
WebDriver driver = null;
driver=new ChromeDriver();
String url="https://opensource-demo.orangehrmlive.com/";
driver.get(url);
driver.manage().window().maximize();
FileInputStream file=new FileInputStream("C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\src\\com\\ExcelFiles\\MultipleTestData_ORHM11.xlsx");
XSSFWorkbook Workbook=new XSSFWorkbook(file);
XSSFSheet Sheet=Workbook.getSheet("Sheet1");
Row r=Sheet.getRow(1);
Cell usernamecell=r.getCell(0);
Cell passwordcell=r.getCell(1);
String Username=usernamecell.getStringCellValue();
String Password=passwordcell.getStringCellValue();
//String url="https://opensource-demo.orangehrmlive.com/";
//driver.get(url);
WebElement UsernameElement=driver.findElement(By.id("txtUsername"));
UsernameElement.sendKeys(Username);
WebElement PasswordElement=driver.findElement(By.id("txtPassword"));
PasswordElement.sendKeys(Password);
WebElement LOGIN=driver.findElement(By.id("btnLogin"));
LOGIN.click();
String expected_LOGINText="Welcome";
System.out.println("The expected text after Login Successful is:"+expected_LOGINText);
//<a href="#" id="welcome" class="panelTrigger">Welcome Admin</a>
WebElement WelcomeAdminElement=driver.findElement(By.linkText("Welcome Admin"));
String actual_LOGINText=WelcomeAdminElement.getText();
System.out.println("The actual text after Login Successful is:"+actual_LOGINText);
XSSFSheet Sheeto=Workbook.getSheet("Sheet1");
Row r2=Sheeto.getRow(1);
Cell cell=r2.createCell(2);
FileOutputStream file1=new FileOutputStream("C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\src\\com\\ExcelFiles\\MultipleTestData_ORHM11.xlsx");
if(actual_LOGINText.contains(expected_LOGINText))
{
cell.setCellValue("OrangeHRM Page successfully loged in-PASS");
Workbook.write(file1);
file1.close();
//System.out.println("OrangeHRM Page successfully loged in-PASS");
}
else
{
cell.setCellValue("OrangeHRM Page login unsuccessful-FAIL ");
Workbook.write(file1);
file1.close();
// System.out.println("OrangeHRM Page login unsuccessful-FAIL ");
}
driver.close();
}
}
|
package com.pitang.business;
public enum TagColor {
DES("DES", "D9182D"), QA("QA", "FFCF01"), UAT("UAT", "00B2EF"), PRD("PRD", "17AF4B"), APP("APP", "AB1A86"), POOL("POOL", "404041");
private String type;
private String hex;
private TagColor(final String type, final String hex) {
this.type = type;
this.hex = hex;
}
public String getType() {
return this.type;
}
public String getHex() {
return this.hex;
}
public static TagColor fromType(final String type) {
TagColor result = null;
for(final TagColor value : TagColor.values()) {
if(value.getType().equals(type)) {
result = value;
}
}
return result;
}
}
|
package eu.javaspecialists.teacher;
import java.awt.*;
import java.io.*;
public interface RobotAction extends Serializable
{
Object execute(Robot robot) throws IOException;
} |
/*
* Created on Mar 1, 2007
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package com.citibank.ods.entity.pl;
import java.util.Date;
import com.citibank.ods.entity.pl.valueobject.TplProductFamilyPrvtEntityVO;
import com.citibank.ods.entity.pl.valueobject.TplProductFamilyPrvtHistEntityVO;
/**
* @author fernando.salgado
*
* TODO To change the template for this generated type comment go to Window -
* Preferences - Java - Code Style - Code Templates
* @generated "UML to Java
* (com.ibm.xtools.transform.uml2.java.internal.UML2JavaTransform)"
*/
public class TplProductFamilyPrvtHistEntity extends
BaseTplProductFamilyPrvtEntity
{
/**
* Construtor padrão - sem argumentos
*/
public TplProductFamilyPrvtHistEntity()
{
m_data = new TplProductFamilyPrvtHistEntityVO();
}
/**
* Construtor - Carrega os atributos de instancia com os atributos de Current
*/
public TplProductFamilyPrvtHistEntity(
TplProductFamilyPrvtEntity tplProductFamilyPrvtEntity_,
Date prodFamlPrvtRefDate_ )
{
m_data = new TplProductFamilyPrvtHistEntityVO();
m_data.setProdFamlCode( tplProductFamilyPrvtEntity_.getData().getProdFamlCode() );
m_data.setProdFamlName( tplProductFamilyPrvtEntity_.getData().getProdFamlName() );
m_data.setProdFamlText( tplProductFamilyPrvtEntity_.getData().getProdFamlText() );
m_data.setLastUpdUserId( tplProductFamilyPrvtEntity_.getData().getLastUpdUserId() );
m_data.setLastUpdDate( tplProductFamilyPrvtEntity_.getData().getLastUpdDate() );
( ( TplProductFamilyPrvtHistEntityVO ) m_data ).setLastAuthDate( ( ( TplProductFamilyPrvtEntityVO ) tplProductFamilyPrvtEntity_.getData() ).getLastAuthDate() );
( ( TplProductFamilyPrvtHistEntityVO ) m_data ).setLastAuthUserId( ( ( TplProductFamilyPrvtEntityVO ) tplProductFamilyPrvtEntity_.getData() ).getLastAuthUserId() );
( ( TplProductFamilyPrvtHistEntityVO ) m_data ).setRecStatCode( ( ( TplProductFamilyPrvtEntityVO ) tplProductFamilyPrvtEntity_.getData() ).getRecStatCode() );
( ( TplProductFamilyPrvtHistEntityVO ) m_data ).setProdFamlRefDate( prodFamlPrvtRefDate_ );
}
} |
package problem04;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> problemList = new ArrayList<String>();
ArrayList<Integer> answerList = new ArrayList<Integer>();
int correctCount = 0;
int startTime = 0;
int endTime = 0;
int answer = 0;
int randomNumber = 0;
int randomIndex = 0;
int problemNumber = 1;
for (int i = 0; i < 2; i++) {
for (int j = 1; j < 10; j++) {
randomNumber = (int) (Math.random() * 9) + 1;
problemList.add(j + "x" + randomNumber);
answerList.add(j * randomNumber);
}
}
startTime = (int) (System.currentTimeMillis() / 1000);
while (problemList.size() != 0) {
randomIndex = (int) (Math.random() * problemList.size());
System.out.println(problemNumber++ + ". " + problemList.get(randomIndex) + " ?");
answer = sc.nextInt();
if (answerList.get(randomIndex) == answer) {
correctCount++;
}
problemList.remove(randomIndex);
answerList.remove(randomIndex);
}
endTime = (int) (System.currentTimeMillis() / 1000);
System.out.println(correctCount);
System.out.println(endTime - startTime);
ArrayList<Recode> recodeList = new ArrayList<Recode>();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("object.dat");
ois = new ObjectInputStream(fis);
while (ois.readObject() != null) {
recodeList.add((Recode) ois.readObject());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException e) {
}
if (ois != null)
try {
ois.close();
} catch (IOException e) {
}
}
Recode recode = new Recode(correctCount, endTime - startTime);
recodeList.add(recode);
Recode r = new Recode();
Collections.sort(recodeList, r);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream("object.dat");
oos = new ObjectOutputStream(fos);
for (int i = 0; i < recodeList.size(); i++) {
oos.writeObject(recodeList.get(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
}
if (oos != null)
try {
oos.close();
} catch (IOException e) {
}
}
}
}
|
package com.androidexperiments.meter;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Point;
import android.os.Handler;
import android.view.Display;
import android.view.WindowManager;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.apache.commons.math3.util.Pair;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.List;
/**
* Created by zachmathews on 12/22/15.
*/
public class HUDManager {
private static HUDManager instance;
private long refreshIntervalSeconds;
private Handler handler;
private Context context;
private Point screenSize;
private Pair<Integer, String> url_1;
private Pair<Integer, String> url_2;
private String[] results;
private SharedPreferences pref;
public HUDManager() {
handler = new Handler();
}
public static HUDManager instance() {
if (instance == null) {
instance = new HUDManager();
}
return instance;
}
public String[] getData() {
if (results == null) { //hardcode 2 params for now. Add more later.
results = new String[2];
results[0] = "";
results[1] = "";
}
return results;
}
Runnable getParams = new Runnable() {
@Override
public void run() {
if (context != null) {
pref = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
url_1 = new Pair(0, pref.getString("url_1", ""));
url_2 = new Pair(1, pref.getString("url_2", ""));
refreshIntervalSeconds = pref.getLong("refresh_interval", 5);
if (!url_1.getValue().equals("")) {
getHUDParametersFromURL(context, url_1);
}
if (!url_2.getValue().equals("")) {
getHUDParametersFromURL(context, url_2);
}
handler.postDelayed(getParams, refreshIntervalSeconds * 1000);
}
}
};
private RequestQueue queue;
public void start(Context context) {
this.context = context;
queue = Volley.newRequestQueue(context);
queue.start();
handler = new Handler();
handler.postDelayed(getParams, refreshIntervalSeconds * 1000);
}
public void stop(Context context){
handler.removeCallbacks(getParams);
if(queue != null) {
queue.stop();
queue.getCache().clear();
queue = null;
}
}
public void getHUDParametersFromURL(Context context, final Pair url) {
// Instantiate the RequestQueue.
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
screenSize = new Point();
display.getSize(screenSize);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, (String) url.getValue(),
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String temp = "";
int tempIndex;
for (int i = (screenSize.x / 8); i < response.length(); i += (screenSize.x / 8)) {
tempIndex = response.indexOf(" ", i);
if (tempIndex == -1) {
tempIndex = i;
} else {
i = tempIndex;
}
temp = response.substring(tempIndex);
response = response.substring(0, tempIndex) + "\n" + temp;
}
results[(int) url.getKey()] = response;
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
if(queue != null) {
queue.add(stringRequest);
}
}
}
|
package com.j1902.shopping.pojo;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class CountOrder {
private Integer countId;
private Integer countUserid;
private String countRemarks;
@Override
public String toString() {
return "CountOrder{" +
"countId=" + countId +
", countUserid=" + countUserid +
", countRemarks='" + countRemarks + '\'' +
", countCreatetime=" + countCreatetime +
", countMethod='" + countMethod + '\'' +
", countMoney=" + countMoney +
", countSat='" + countSat + '\'' +
", countUsername='" + countUsername + '\'' +
", countPhone='" + countPhone + '\'' +
", countAddress='" + countAddress + '\'' +
'}';
}
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date countCreatetime;
private String countMethod;
private Double countMoney;
private String countSat;
private String countUsername;
private String countPhone;
private String countAddress;
public Integer getCountId() {
return countId;
}
public void setCountId(Integer countId) {
this.countId = countId;
}
public Integer getCountUserid() {
return countUserid;
}
public void setCountUserid(Integer countUserid) {
this.countUserid = countUserid;
}
public String getCountRemarks() {
return countRemarks;
}
public void setCountRemarks(String countRemarks) {
this.countRemarks = countRemarks == null ? null : countRemarks.trim();
}
public Date getCountCreatetime() {
return countCreatetime;
}
public void setCountCreatetime(Date countCreatetime) {
this.countCreatetime = countCreatetime;
}
public String getCountMethod() {
return countMethod;
}
public void setCountMethod(String countMethod) {
this.countMethod = countMethod == null ? null : countMethod.trim();
}
public Double getCountMoney() {
return countMoney;
}
public void setCountMoney(Double countMoney) {
this.countMoney = countMoney;
}
public String getCountSat() {
return countSat;
}
public void setCountSat(String countSat) {
this.countSat = countSat == null ? null : countSat.trim();
}
public String getCountUsername() {
return countUsername;
}
public void setCountUsername(String countUsername) {
this.countUsername = countUsername == null ? null : countUsername.trim();
}
public String getCountPhone() {
return countPhone;
}
public void setCountPhone(String countPhone) {
this.countPhone = countPhone == null ? null : countPhone.trim();
}
public String getCountAddress() {
return countAddress;
}
public void setCountAddress(String countAddress) {
this.countAddress = countAddress == null ? null : countAddress.trim();
}
} |
package org.yxt.learn.week2;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @ClassName Phone
* @Description TODO
* @Author 余欣婷
* @Date 2020/10/12
**/
@AllArgsConstructor
@Getter
@Setter
@ToString
public class Phone {
private String brand;
private String model;
private String number;
}
|
package com.gonzajf.spring.masteringSpring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import com.gonzajf.spring.masteringSpring.config.PicturesUploadProperties;
@SpringBootApplication
@EnableConfigurationProperties({PicturesUploadProperties.class})
public class MasteringSpringApplication {
public static void main(String[] args) {
SpringApplication.run(MasteringSpringApplication.class, args);
}
}
|
package com.example.springmvc.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.springmvc.repository.RoomRepository;
import org.springframework.stereotype.Service;
@Service
public class RoomService{
@Autowired
private RoomRepository roomRepository;
//Требование А.а.7
//public int changePrice(Date date){}
}
|
package com.wise.pint.pintwise;
public class Place {
private String mName;
private String mRate;
private String mStar;
public String getmRate() {
return mRate;
}
public void setmRate(String mRate) {
this.mRate = mRate;
}
public String getmStar() {
return mStar;
}
public void setmStar(String mStar) {
this.mStar = mStar;
}
public String getName() {
return mName;
}
public void setName(String name) {
this.mName = name;
}
}
|
package com.web.common.order;
import com.web.framework.util.StringUtil;
public class OrderDTO {
protected int loginSeq;
//sp º¯°æ
protected String chUserID;
protected String FrDate;
protected String ToDate;
protected String GroupID;
protected String vSearchType;
protected String vSearch;
protected int nRow;
protected int nPage;
protected String JobGb;
protected String OrderCode;
protected String CompanyCode;
protected String OrderDateTime;
protected String OrderUserID;
protected String FAXKey;
protected String SMSKey;
protected String EmailKey;
protected String mobilephone;
protected String emailaddr;
protected String faxnum;
protected String OrderEtc;
protected String OrderAdress;
protected int ToTalOrderPrice;
protected String IngYN;
protected String ProductCode;
protected int OrderCnt;
protected String Etc;
protected int StockCnt;
protected int SafeStock;
protected int LossCnt;
protected int AddCnt;
protected String Memo;
protected int OrderResultCnt;
protected int OrderResultPrice;
protected String OrderCheck;
protected String BuyResult;
protected String DeliveryDate;
protected String DeliveryEtc;
protected String DeliveryMethod;
protected String DeliveryCharge;
protected String VatRate;
protected String OrderMemo;
protected String logid;
public int getLoginSeq() {
return loginSeq;
}
public void setLoginSeq(int loginSeq) {
this.loginSeq = loginSeq;
}
public String getChUserID() {
return chUserID;
}
public void setChUserID(String chUserID) {
this.chUserID = chUserID;
}
public String getFrDate() {
return FrDate;
}
public void setFrDate(String frDate) {
FrDate = frDate;
}
public String getToDate() {
return ToDate;
}
public void setToDate(String toDate) {
ToDate = toDate;
}
public String getGroupID() {
return GroupID;
}
public void setGroupID(String groupID) {
GroupID = groupID;
}
public String getvSearchType() {
return vSearchType;
}
public void setvSearchType(String vSearchType) {
this.vSearchType = vSearchType;
}
public String getvSearch() {
return vSearch;
}
public void setvSearch(String vSearch) {
this.vSearch = vSearch;
}
public int getnRow() {
return nRow;
}
public void setnRow(int nRow) {
this.nRow = nRow;
}
public int getnPage() {
return nPage;
}
public void setnPage(int nPage) {
this.nPage = nPage;
}
public String getJobGb() {
return JobGb;
}
public void setJobGb(String jobGb) {
JobGb = jobGb;
}
public String getCompanyCode() {
return CompanyCode;
}
public void setCompanyCode(String companyCode) {
CompanyCode = companyCode;
}
public String getOrderDateTime() {
return OrderDateTime;
}
public void setOrderDateTime(String orderDateTime) {
OrderDateTime = orderDateTime;
}
public String getOrderUserID() {
return OrderUserID;
}
public void setOrderUserID(String orderUserID) {
OrderUserID = orderUserID;
}
public String getFAXKey() {
return FAXKey;
}
public void setFAXKey(String fAXKey) {
FAXKey = fAXKey;
}
public String getSMSKey() {
return SMSKey;
}
public void setSMSKey(String sMSKey) {
SMSKey = sMSKey;
}
public String getEmailKey() {
return EmailKey;
}
public void setEmailKey(String emailKey) {
EmailKey = emailKey;
}
public int getToTalOrderPrice() {
return ToTalOrderPrice;
}
public void setToTalOrderPrice(int toTalOrderPrice) {
ToTalOrderPrice = toTalOrderPrice;
}
public String getIngYN() {
return IngYN;
}
public void setIngYN(String ingYN) {
IngYN = ingYN;
}
public String getProductCode() {
return ProductCode;
}
public void setProductCode(String productCode) {
ProductCode = productCode;
}
public int getOrderCnt() {
return OrderCnt;
}
public void setOrderCnt(int orderCnt) {
OrderCnt = orderCnt;
}
public String getEtc() {
return Etc;
}
public void setEtc(String etc) {
Etc = etc;
}
public int getStockCnt() {
return StockCnt;
}
public void setStockCnt(int stockCnt) {
StockCnt = stockCnt;
}
public int getSafeStock() {
return SafeStock;
}
public void setSafeStock(int safeStock) {
SafeStock = safeStock;
}
public int getLossCnt() {
return LossCnt;
}
public void setLossCnt(int lossCnt) {
LossCnt = lossCnt;
}
public int getAddCnt() {
return AddCnt;
}
public void setAddCnt(int addCnt) {
AddCnt = addCnt;
}
public String getMemo() {
return Memo;
}
public void setMemo(String memo) {
Memo = memo;
}
public int getOrderResultCnt() {
return OrderResultCnt;
}
public void setOrderResultCnt(int orderResultCnt) {
OrderResultCnt = orderResultCnt;
}
public int getOrderResultPrice() {
return OrderResultPrice;
}
public void setOrderResultPrice(int orderResultPrice) {
OrderResultPrice = orderResultPrice;
}
public String getOrderCheck() {
return OrderCheck;
}
public void setOrderCheck(String orderCheck) {
OrderCheck = orderCheck;
}
public String getLogid() {
return logid;
}
public void setLogid(String logid) {
this.logid = logid;
}
public String getOrderCode() {
return OrderCode;
}
public void setOrderCode(String orderCode) {
OrderCode = orderCode;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getEmailaddr() {
return emailaddr;
}
public void setEmailaddr(String emailaddr) {
this.emailaddr = emailaddr;
}
public String getFaxnum() {
return faxnum;
}
public void setFaxnum(String faxnum) {
this.faxnum = faxnum;
}
public String getOrderEtc() {
return OrderEtc;
}
public void setOrderEtc(String orderEtc) {
OrderEtc = orderEtc;
}
public String getOrderAdress() {
return OrderAdress;
}
public void setOrderAdress(String orderAdress) {
OrderAdress = orderAdress;
}
public String getBuyResult() {
return BuyResult;
}
public void setBuyResult(String buyResult) {
BuyResult = buyResult;
}
public String getDeliveryDate() {
return DeliveryDate;
}
public void setDeliveryDate(String deliveryDate) {
DeliveryDate = deliveryDate;
}
public String getDeliveryEtc() {
return DeliveryEtc;
}
public void setDeliveryEtc(String deliveryEtc) {
DeliveryEtc = deliveryEtc;
}
public String getDeliveryMethod() {
return DeliveryMethod;
}
public void setDeliveryMethod(String deliveryMethod) {
DeliveryMethod = deliveryMethod;
}
public String getDeliveryCharge() {
return DeliveryCharge;
}
public void setDeliveryCharge(String deliveryCharge) {
DeliveryCharge = deliveryCharge;
}
public String getVatRate() {
return VatRate;
}
public void setVatRate(String vatRate) {
VatRate = vatRate;
}
public String getOrderMemo() {
return OrderMemo;
}
public void setOrderMemo(String orderMemo) {
OrderMemo = orderMemo;
}
}
|
package com.mansur.rest.model;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class User {
private int id;
private String name;
private Message userMessage;
private List<Link> links;
public List<Link> getLinks() {
return links;
}
public void setLink(List<Link> links) {
this.links = links;
}
public Message getUserMessage() {
return userMessage;
}
public void setUserMessage(Message userMessage) {
this.userMessage = userMessage;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public User(User user) {
this.id = user.id;
this.name = user.name;
}
public User() {
}
}
|
package by.herzhot;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Test {
public static <T extends String & Serializable & Runnable> void main(String[] args) {
Map<String, String> m = new HashMap<String, String>() {{
put("1", "2");
}};
Map<?, ?> objectMap = m;
// objectMap.put("k", "v");
System.out.println(objectMap.get("1"));
}
}
|
package com.fanfte.algorithm.map;
/**
* Created by tianen on 2018/11/15
*
* @author fanfte
* @date 2018/11/15
**/
public class BSTMap<K extends Comparable<K>, V> implements Map<K, V> {
class Node {
public Node left;
public Node right;
public K key;
public V value;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public Node() {
}
}
private Node root;
private int size;
public BSTMap() {
this.root = null;
size = 0;
}
private Node getNode(K k) {
return getNode(root, k);
}
private Node getNode(Node node, K k) {
if(node == null) {
return null;
}
if(k.compareTo(node.key) < 0) {
return getNode(node.left, k);
} else if(k.compareTo(node.key) > 0) {
return getNode(node.right, k);
} else {
return node;
}
}
@Override
public void add(K k, V v) {
root = add(root, k, v);
}
/**
* 往node为根节点的树中添加元素,返回添加完元素的节点
*/
private Node add(Node node, K k, V v) {
if(node == null) {
size ++;
node = new Node(k, v);
}
if(k.compareTo(node.key) < 0) {
node.left = add(node.left, k, v);
} else if(k.compareTo(node.key) > 0) {
node.right = add(node.right, k, v);
} else {
node.value = v;
}
return node;
}
public Node getMin(K k) {
return getMin(root, k);
}
private Node getMin(Node node, K k) {
if(node == null) {
return null;
}
while(node != null) {
if(node.left.key.equals(k)) {
return node.left;
}
node = node.left;
}
return null;
}
@Override
public V remove(K k) {
Node node = getNode(k);
if(node == null) {
return null;
} else {
root = remove(root, k);
}
return node.value;
}
private Node remove(Node node, K k) {
if(node == null) {
return null;
}
if(k.compareTo(node.key) < 0) {
node.left = remove(node.left, k);
return node;
} else if(k.compareTo(node.key) > 0) {
node.right = remove(node.right, k);
return node;
} else {
if(node.left == null) {
Node rightNode = node.right;
node.right = null;
size --;
return rightNode;
}
if(node.right == null) {
Node leftNode = node.left;
node.left = null;
size --;
return leftNode;
}
Node successor = minum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
/**
* 查找以node为根节点的二叉树的最小节点
*/
private Node minum(Node node) {
if(node.left == null) {
return node;
}
return minum(node.left);
}
/**
* 删除以node为根节点的最小节点
*/
private Node removeMin(Node node) {
if(node.left == null) {
Node rightNode = node.right;
node.right = null;
size --;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
@Override
public void set(K k, V v) {
Node node = getNode(k);
if(node == null) {
throw new IllegalArgumentException(k + " doesn`t exist!");
}
node.value = v;
}
@Override
public V get(K k) {
Node node = getNode(k);
return node == null ? null : node.value;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public boolean contains(K k) {
return false;
}
}
|
// Problem URL : http://www.spoj.com/problems/CANDY/
import java.util.Scanner;
class Candy_I
{
public static void main(String [] args)
{
int r=0,t,x;
Scanner s=new Scanner(System.in);
t=s.nextInt();
while(t!=-1)
{ int a[]=new int[t];
int sum=0,i;
for( i=0;i<t;i++)
{ a[i]=s.nextInt();
sum+=a[i];
}
if(sum%t!=0)
{
System.out.println("-1");
}
else
{ x=sum/t; r=0;
for(i=0;i<t;i++)
{
if(a[i]<x)
{
r+=x-a[i];
}
}
System.out.println(r);
}
t=s.nextInt();
}
}
} |
package com.example.isufdeliu;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
SQLiteDatabase mDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
mDb = openOrCreateDatabase("registration.db", MODE_PRIVATE, null);
String createQUERY = "CREATE TABLE IF NOT EXISTS"
+ " tblUsers(ID INTEGER PRIMARY KEY,Password Varchar not null,RepeatPassword Varchar not null)";
mDb.execSQL(createQUERY);
} catch (Exception ex) {
showAlertMessage("Database error:" + ex.getMessage());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// onClick handler
public void SignIn(View v) {
EditText editID = (EditText) findViewById(R.id.eID);
EditText editPassword = (EditText) findViewById(R.id.ePassword);
try {
int ID = Integer.parseInt(editID.getText().toString());
String Password = editPassword.getText().toString();
String authenticateQUERY = "SELECT ID,Password"
+ " FROM tblUsers WHERE ID=" + ID + " AND Password='"
+ Password + "'";
Cursor cursor = mDb.rawQuery(authenticateQUERY, null);
int countResultRows = cursor.getCount();
if (countResultRows != 0) {
Intent goToReg = new Intent(MainActivity.this,
DataRegister.class);
goToReg.putExtra("ID", ID);
startActivity(goToReg);
} else {
showAlertMessage("Please register or type your password correctly");
}
}
catch (Exception ex) {
showAlertMessage(ex.getMessage());
}
finally {
editID.setText("");
editPassword.setText("");
}
}
public void freeSignUp(View v) {
Intent nextActivity = new Intent(MainActivity.this, SignUp.class);
startActivity(nextActivity);
}
public void showAlertMessage(String msg) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(msg);
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
}
|
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class 날짜계산 {
public static void main(String[] args) throws ParseException {
String timeStamp = new SimpleDateFormat().format(Calendar.getInstance().getTime());
System.out.println("1) " + timeStamp);
System.out.println("2) " + Calendar.getInstance().getTime());
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf1.parse("2020-10-01");
Calendar cal1 = sdf1.getCalendar();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
Date date2 = sdf2.parse("2020-11-21");
Calendar cal2 = sdf2.getCalendar();
System.out.println("3) " + cal1.getTime());
System.out.println("4) " + cal2.getTime());
long time1 = cal1.getTimeInMillis();
long time2 = cal2.getTimeInMillis();
long diffTime = time1 - time2;
long days = diffTime / 1000 / 60 / 60 / 24;
System.out.println("5) " + days);
}
} |
package br.edu.ifg.proi.servlet;
import java.io.IOException;
import java.sql.SQLException;
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 br.edu.ifg.proi.dao.ClienteDAO;
import br.edu.ifg.proi.modelo.Cliente;
import br.edu.ifg.proi.modelo.Endereco;
/**
* Servlet implementation class AlterarClienteServlet
*/
@WebServlet("/AlterarClienteServlet")
public class AlterarClienteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AlterarClienteServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String usuario = request.getParameter("usuario");
String senha = request.getParameter("senha");
String sconf = request.getParameter("confirma_senha");
String nome = request.getParameter("nome");
String cpf = request.getParameter("cpf");
String contato = request.getParameter("contato");
String email = request.getParameter("email");
String logadouro = request.getParameter("logadouro");
String CEP = request.getParameter("CEP");
String cidade = request.getParameter("cidade");
String bairro = request.getParameter("bairro");
String UF = request.getParameter("UF");
if (senha.equals(sconf)) {
Cliente novo = new Cliente();
novo.setNome(nome);
novo.setCpf(cpf);
novo.setSenha(senha);
novo.setUsuario(usuario);
novo.setContato(contato);
novo.setEmail(email);
Endereco endereco = new Endereco();
endereco.setBairro(bairro);
endereco.setCEP(CEP);
endereco.setCidade(cidade);
endereco.setLogradouro(logadouro);
endereco.setUF(UF);
novo.setEndereco(endereco);
try {
ClienteDAO dao = new ClienteDAO();
dao.update(novo);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("menu_cliente.jsp").forward(request, response);
} else {
System.out.println("Senhas não conferem");
request.getRequestDispatcher("PaginaCadastro.html").forward(request, response);
}
}
}
|
package xyz.lateralus;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import xyz.lateralus.app.R;
import xyz.lateralus.components.LateralusPreferences;
import xyz.lateralus.components.Utils;
import xyz.lateralus.components.gcm.RegistrationIntentService;
import xyz.lateralus.components.network.LateralusAuth;
import xyz.lateralus.fragments.RegisterFragment;
import xyz.lateralus.fragments.SettingsFragment;
public class SignInActivity extends AppCompatActivity implements View.OnClickListener, CheckBox.OnCheckedChangeListener{
private static final String TAG = "SignInActivity";
private EditText _emailField;
private EditText _passwordField;
private TextView _messageTextView;
private ActionBar _actionBar;
private Menu _menu;
private LateralusAuth _auth;
private LateralusPreferences _prefs;
private BroadcastReceiver _registrationBroadcastReceiver;
private static final long ONE_DAY_MILLIS = 1000 * 60 * 60 * 24;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
_auth = new LateralusAuth(this, new AuthDelegate());
_prefs = new LateralusPreferences(this);
_actionBar = getSupportActionBar();
//_actionBar.setTitle(R.string.title_activity_sign_in);
if(_prefs.isUserSignedIn() && !signInTimedOut()){
switchToMainActivity();
}
_emailField = (EditText) findViewById(R.id.edit_text_sign_in_email);
_emailField.setText((_prefs.rememberEmail()) ? _prefs.getEmail() : "");
_passwordField = (EditText) findViewById(R.id.edit_text_sign_in_password);
_messageTextView = (TextView) findViewById(R.id.text_view_sign_in_message);
findViewById(R.id.button_sign_in).setOnClickListener(this);
findViewById(R.id.text_view_register_account).setOnClickListener(this);
((CheckBox) findViewById(R.id.check_box_remember_email)).setChecked(_prefs.rememberEmail());
((CheckBox) findViewById(R.id.check_box_remember_email)).setOnCheckedChangeListener(this);
if(!Utils.checkPlayServices(this)) {
setText(_messageTextView, "Google Play Services is required for this app.", R.color.lateralus_red);
findViewById(R.id.text_view_register_account).setVisibility(View.INVISIBLE);
findViewById(R.id.button_sign_in).setVisibility(View.INVISIBLE);
_emailField.setVisibility(View.INVISIBLE);
_passwordField.setVisibility(View.INVISIBLE);
findViewById(R.id.check_box_remember_email).setVisibility(View.INVISIBLE);
}
else {
setBroadcastReceiver();
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(findViewById(R.id.button_sign_in).getVisibility() == View.VISIBLE) {
getMenuInflater().inflate(R.menu.sign_in_menu, menu);
_menu = menu;
return true;
}
return false;
}
@Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(_registrationBroadcastReceiver, new IntentFilter(RegistrationIntentService.REGISTRATION_COMPLETE));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(_registrationBroadcastReceiver);
super.onPause();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id){
case R.id.home:
case android.R.id.home:
getFragmentManager().popBackStack();
showRegisterActionBar(false);
return true;
case R.id.action_settings:
loadSettingsFragment();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if(getFragmentManager().getBackStackEntryCount() != 0) {
getFragmentManager().popBackStack();
showRegisterActionBar(false);
showSettingsActionBar(false);
}
else {
super.onBackPressed();
}
}
/* -------- AUTHENTICATION -------- */
private void authenticate(){
String email = _emailField.getText().toString();
String pass = _passwordField.getText().toString();
if(inputIsValid(email, pass)){
if(_prefs.getGcmToken().isEmpty() || !_prefs.wasGcmTokenSentToServer()) {
setText(_messageTextView, "Error with GCM. Try again in 1 min", R.color.lateralus_red);
// TODO: send error to server
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
return;
}
else if(Utils.internetActive(this)){
setText(_messageTextView, "Signing in...", R.color.lateralus_gray_med);
_auth.signIn(email, pass);
}
else {
setText(_messageTextView, "You need to be connected to the internet to authenticate your account.", R.color.lateralus_red);
}
}
}
private class AuthDelegate implements LateralusAuth.LateralusAuthDelegate{
@Override
public void authFinished(final Boolean success, final String msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if(success){
_prefs.setLastSignInMillis(Utils.getTimestampMillis());
switchToMainActivity();
}
else {
setText(_messageTextView, msg, R.color.lateralus_red);
}
}
});
}
}
private void switchToMainActivity(){
Intent app = new Intent(this, MainActivity.class);
startActivity(app);
finish();
}
/* -------- GCM -------- */
private void setBroadcastReceiver(){
_registrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean sentToken = _prefs.wasGcmTokenSentToServer();
String token = _prefs.getGcmToken();
if(sentToken && !token.isEmpty()){
// YAY! GCM SUCCESS, now we can login into lateralus
}
}
};
}
/* -------- Helpers -------- */
private Boolean inputIsValid(String email, String pass){
if(!Utils.isValidEmail(email)){
setText(_messageTextView, "Please enter a valid email", R.color.lateralus_red);
return false;
}
else if(!Utils.passwordHasCorrectLength(pass)){
setText(_messageTextView, "Password must be at least 6 characters.", R.color.lateralus_red);
return false;
}
return true;
}
private void setText(TextView tv, String text, int colorId){
tv.setText(text);
tv.setTextColor(getResources().getColor(colorId));
}
private void loadRegisterFragment(){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(
R.anim.slide_in_right,
R.anim.slide_out_right,
R.anim.slide_in_right,
R.anim.slide_out_right
);
transaction.replace(R.id.activity_sign_in_container, new RegisterFragment());
transaction.addToBackStack(null);
transaction.commit();
showRegisterActionBar(true);
}
private void showRegisterActionBar(Boolean show){
_menu.findItem(R.id.action_settings).setVisible(!show);
if(show){
_actionBar.setTitle(R.string.title_fragment_register);
_actionBar.setDisplayHomeAsUpEnabled(true);
}
else{
_actionBar.setTitle(R.string.title_activity_sign_in);
_actionBar.setDisplayHomeAsUpEnabled(false);
}
}
private void loadSettingsFragment(){
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(
R.anim.slide_in_right,
R.anim.slide_out_right,
R.anim.slide_in_right,
R.anim.slide_out_right
);
transaction.replace(R.id.activity_sign_in_container, new SettingsFragment());
transaction.addToBackStack(null);
transaction.commit();
showSettingsActionBar(true);
}
private void showSettingsActionBar(Boolean show){
_menu.findItem(R.id.action_settings).setVisible(!show);
if(show){
_actionBar.setTitle(R.string.title_fragment_settings);
_actionBar.setDisplayHomeAsUpEnabled(true);
}
else{
_actionBar.setTitle(R.string.title_activity_main);
_actionBar.setDisplayHomeAsUpEnabled(false);
}
}
private Boolean signInTimedOut() {
long last = _prefs.getLastSignInMillis();
return last <= 0 || (last + ONE_DAY_MILLIS) < Utils.getTimestampMillis();
}
/* -------- View Listeners -------- */
@Override
public void onCheckedChanged(CompoundButton button, boolean checked) {
int id = button.getId();
switch(id){
case R.id.check_box_remember_email:
_prefs.shouldRememberEmail(checked);
break;
}
}
@Override
public void onClick(View view) {
setText(_messageTextView, "", R.color.lateralus_gray_med);
int id = view.getId();
switch(id){
case R.id.button_sign_in:
authenticate();
break;
case R.id.text_view_register_account:
loadRegisterFragment();
break;
}
}
}
|
package com.cg.osce.apibuilder.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"delete"
})
public class GetDeleteObj {
@JsonProperty("delete")
private Delete delete;
@JsonProperty("delete")
public Delete getDelete() {
return delete;
}
@JsonProperty("delete")
public void setDelete(Delete delete) {
this.delete = delete;
}
}
|
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
******************************************************************************/
package dk.sidereal.lumm.architecture.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import dk.sidereal.lumm.architecture.Lumm;
import dk.sidereal.lumm.architecture.LummConfiguration;
import dk.sidereal.lumm.architecture.LummModule;
/**
* Class used for object serialization and saving in a path relative to the
* preferences set by {@link LummConfiguration#preferExternalStorage} and
* availability of the storage based on platform.
* <p>
* Instance is found in {@link Lumm#data}
*
* @author Claudiu Bele
*/
public class AppData extends LummModule {
// region external
/**
* Type of storage. {@link AppData#storageType} is assigned a value in
* {@link AppData#DataSerializer(boolean)}
*
* @see StorageType#External
* @see StorageType#Local
* @see StorageType#None
* @author Claudiu Bele
*/
enum StorageType {
/**
* External is prioritised and available / Internal is prioritised and
* unavailable
*
* @see StorageType#Local
*/
External,
/**
* Internal is prioritised and available / External is prioritised and
* unavailable
*
* @see StorageType#External
*/
Local,
/** Neither external or local storage are available */
None
}
public static final class ParticleSettings {
public static final int NONE = 0;
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
public static final int MAX = 4;
public static String toString(int no) {
switch (no) {
case 0:
return Settings.PARTICLE_SETTINGS_NONE;
case 1:
return Settings.PARTICLE_SETTINGS_LOW;
case 2:
return Settings.PARTICLE_SETTINGS_MEDIUM;
case 3:
return Settings.PARTICLE_SETTINGS_HIGH;
case 4:
return Settings.PARTICLE_SETTINGS_MAX;
default:
return Settings.PARTICLE_SETTINGS_NONE;
}
}
}
public static final class Settings {
/**
* Specifies the setting number for the particle settings.
* <p>
* Value is of type {@link IntWrapper}.
*/
public static final String PARTICLE_SETTINGS = "Particle settings";
/**
* Whether or not to use linear filtering for the loaded textures
* <p>
* Set to false by default in {@link AppData#onCreate()}, and retrieved
* or added to the settings file based on whether or not it exists.
* <p>
* Value is of type {@link BooleanWrapper}.
*/
public static final String LINEAR_FILTERING = "Linear filtering";
/**
* Specifies whether or not to use shaders. Set to true by default.
* <p>
* Value is of type {@link BooleanWrapper}.
*/
public static final String USE_SHADERS = "Use shaders";
/**
* Music volume modifier, from 0 to 1.
* <p>
* Value is of type {@link FloatWrapper}.
*/
public static final String MUSIC_VOLUME = "Music volume";
/**
* Sound volume modifier, from 0 to 1.
* <p>
* Value is of type {@link FloatWrapper}.
*/
public static final String SOUND_VOLUME = "Sound volume";
/**
* Whether to run multithreaded or not.
* <p>
* Value is of type {@link BooleanWrapper}.
*/
public static final String MULTI_THREADED = "Multi threaded";
public static final String PARTICLE_SETTINGS_NONE = "NONE";
public static final String PARTICLE_SETTINGS_LOW = "LOW";
public static final String PARTICLE_SETTINGS_MEDIUM = "MEDIUM";
public static final String PARTICLE_SETTINGS_HIGH = "HIGH";
public static final String PARTICLE_SETTINGS_MAX = "MAX";
}
// endregion
// region fields
public static final String GRAPHICS_SETTINGS_PATH = "GameData/Graphics";
public static final String AUDIO_SETTINGS_PATH = "GameData/Audio";
public static final String LOAD_ON_STARTUP_PATH = "GameData/LoadOnStartup";
/** The graphical preferences, used for retrieval from files */
public HashMap<String, Object> graphicSettings;
/**
* Audio preferences of the app, containing audio channel volume settings
*/
public HashMap<String, Object> audioSettings;
/**
* List containing whether files have to be loaded on startup. When using
* {@link #saveData(String, Object, boolean)}
*/
private HashMap<String, Boolean> loadOnStartup;
/**
* Whether to prioritise external storage when saving data or not, if the
* device allows.
*/
private boolean prioritiseExternalStorage;
/** The root path to all data related to the app. */
private String rootDataPath;
/** The {@link File} object created at the {@link #rootDataPath} path. */
private FileHandle rootDataFolder;
/**
* Serialized data with the {@link String} key resembling the path and the
* value being the deserialized data which can be casted as the class it was
* initially passed for serialization.
*/
private ObjectMap<String, Object> data;
/** Paths to all of the files. Created in {@link #onCreate()} */
private ArrayList<String> filePaths;
/**
* The type of storage. Set in {@link #DataSerializer(boolean)} which sets
* it based on {@link LummConfiguration#preferExternalStorage} and
* {@link Gdx#files#isExternalStorageAvailable()}
*/
private StorageType storageType;
// endregion fields
// region constructors
public AppData(LummConfiguration cfg) {
super(cfg);
setUpdateFrequency(-1);
this.rootDataPath = cfg.rootDataPath;
this.prioritiseExternalStorage = cfg.prioritiseExternalStorage;
}
@Override
@SuppressWarnings("unchecked")
public void onCreate() {
Lumm.debug.log("Is local storage available? " + Gdx.files.isLocalStorageAvailable(), null);
Lumm.debug.log("Is external storage available? " + Gdx.files.isExternalStorageAvailable(), null);
// region handle root path
if (Gdx.files.isExternalStorageAvailable() == Gdx.files.isLocalStorageAvailable() == false) {
storageType = StorageType.None;
Lumm.debug.logDebug("Device does not allow internal or external storage", null);
return;
}
// check if external storage is available.
if (prioritiseExternalStorage) {
if (Gdx.files.isExternalStorageAvailable())
storageType = StorageType.External;
else if (Gdx.files.isLocalStorageAvailable())
storageType = StorageType.Local;
} else {
// prioritising local storage
if (Gdx.files.isLocalStorageAvailable())
storageType = StorageType.Local;
else if (Gdx.files.isExternalStorageAvailable())
storageType = StorageType.External;
}
if (storageType == StorageType.Local)
Lumm.debug.log("Storage type set to local", null);
else
Lumm.debug.log("Storage type set to external", null);
rootDataPath = rootDataPath.replace('*', ' ').replace('?', ' ');
if (rootDataPath.charAt(rootDataPath.length() - 1) != '/') {
rootDataPath += "/";
Lumm.debug.log("Storage root folder set to \"" + rootDataPath + "\"", null);
}
// endregion
filePaths = new ArrayList<String>();
data = new ObjectMap<String, Object>();
// creates folders
getFileHandle(rootDataPath.substring(0, rootDataPath.lastIndexOf("/"))).mkdirs();
/**
* Deserialises the data from all of the files found in the Data folder(
* including subfolders of Data). Gets called only if the storageType is
* not null so no need to check
*/
getDataFromFolder(getRootDataFolder(), "");
if (exists(LOAD_ON_STARTUP_PATH)) {
loadOnStartup = (HashMap<String, Boolean>) load(LOAD_ON_STARTUP_PATH);
} else {
loadOnStartup = new HashMap<String, Boolean>();
loadOnStartup.put(GRAPHICS_SETTINGS_PATH, new Boolean(true));
loadOnStartup.put(AUDIO_SETTINGS_PATH, new Boolean(true));
save(LOAD_ON_STARTUP_PATH, loadOnStartup, true, true);
}
for (java.util.Map.Entry<String, Boolean> entry : loadOnStartup.entrySet()) {
if (exists(entry.getKey()) && entry.getValue())
load(entry.getKey());
}
// handle retrieving or setting the preferences
if (contains(GRAPHICS_SETTINGS_PATH)) {
graphicSettings = (HashMap<String, Object>) get(GRAPHICS_SETTINGS_PATH);
} else {
graphicSettings = new HashMap<String, Object>();
graphicSettings.put(Settings.PARTICLE_SETTINGS, new Integer(ParticleSettings.MAX));
graphicSettings.put(Settings.LINEAR_FILTERING, new Boolean(false));
graphicSettings.put(Settings.USE_SHADERS, new Boolean(true));
graphicSettings.put(Settings.MULTI_THREADED, new Boolean(false));
save(GRAPHICS_SETTINGS_PATH, graphicSettings, true, true);
}
if (contains(AUDIO_SETTINGS_PATH)) {
audioSettings = (HashMap<String, Object>) get(AUDIO_SETTINGS_PATH);
} else {
audioSettings = new HashMap<String, Object>();
audioSettings.put(Audio.MASTER_VOLUME_KEY, new Float(1));
audioSettings.put(Audio.MUSIC_VOLUME_KEY, new Float(1));
audioSettings.put(Audio.VOICE_VOLUME_KEY, new Float(1));
audioSettings.put(Audio.EFFECTS_VOLUME_KEY, new Float(1));
audioSettings.put(Audio.ENVIRONMENT_VOLUME_KEY, new Float(1));
audioSettings.put(Audio.UI_VOLUME_KEY, new Float(1));
save(AUDIO_SETTINGS_PATH, audioSettings, true, true);
}
}
@Override
public void onUpdate() {
}
// endregion constructor
// region methods
// region settings
/**
* Retrieves a setting from {@link #graphicSettings}. Use {@link Settings}
* variables as a parameter for easy access.
*
* @param settingName
* @return
*/
public Object getSettings(String settingName) {
if (graphicSettings != null) {
if (graphicSettings.containsKey(settingName)) {
return graphicSettings.get(settingName);
}
}
return null;
}
public void updateSettings() {
if (graphicSettings != null) {
save(GRAPHICS_SETTINGS_PATH, graphicSettings, true, true);
}
}
// endregion settings
// region API
// region checks
/**
* Returns whether or not data with the given parameter has been loaded.
*
* @param dataName
* The path excluding the root folder, it is the same one used
* for saving data.
* @return whether or not the parameter can be found as a key.
*/
public boolean contains(String dataName) {
return data.containsKey(dataName);
}
public boolean exists(String dataName) {
for (int i = 0; i < filePaths.size(); i++) {
if (filePaths.get(i).equals(dataName))
return true;
}
return false;
}
// endregion checks
// region save
/**
* Saves the object as a file at root/dataName by serialising it
*
* @param dataName
* The name of the file path relative to the Data Folder, as well
* as the key used for {@link #data}
* @param obj
* The value of the object. WIll be the data in the file, as well
* as the value of the entry that the object takes in
* {@link #data}
* <p>
* Passing a null object as a parameter will only make the
* folders
*/
public final void save(String dataName, Object obj, boolean loadOnStartup, boolean storeInMemory) {
if (storageType.equals(StorageType.None))
return;
String path = rootDataPath + "/" + dataName;
getFileHandle(path.substring(0, path.lastIndexOf("/"))).mkdirs();
if (obj == null)
return;
// we are done with creating nested files.
try {
FileHandle file = getFileHandle(rootDataPath + dataName + ".dd");
file.writeBytes(serialize(obj), false);
Lumm.debug.log("Saved object to file at path \"" + rootDataPath + dataName + ".dd" + "\"", null);
if (storeInMemory) {
data.put(dataName, obj);
}
// not in the list of files in the system, add it there.
if (!exists(dataName))
filePaths.add(dataName);
// load on startup won't update itself with its' own startup
// information, we return.
if (dataName.equals(LOAD_ON_STARTUP_PATH))
return;
if (!this.loadOnStartup.containsKey(dataName) || this.loadOnStartup.get(dataName) != loadOnStartup) {
this.loadOnStartup.put(dataName, new Boolean(loadOnStartup));
save(LOAD_ON_STARTUP_PATH, this.loadOnStartup, false, true);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/** Saves all data in their filePath. */
public final void saveAll() {
for (Entry<String, Object> entry : data.entries()) {
save(entry.key, entry.value, loadOnStartup.get(entry.key), false);
}
}
// endregion save
// region delete
/**
* Removes a file from the map if it the key can be found, and removes the
* file from the disk.
* <p>
* {@link #filePaths}, {@link #loadOnStartup} and {@link #data} will be
* updated to reflect the changes.
*
* @param dataName
* The key to the data
*/
public final void delete(String dataName) {
if (storageType.equals(StorageType.None))
return;
Lumm.debug.log("Deleting file from disk at location: " + dataName, null);
if (contains(dataName)) {
FileHandle file = getFileHandle(rootDataPath + dataName + ".dd");
if (file.exists()) {
file.delete();
}
data.remove(dataName);
filePaths.remove(dataName);
loadOnStartup.remove(dataName);
save(LOAD_ON_STARTUP_PATH, this.loadOnStartup, false, true);
}
}
/**
* Deletes all of the files ( excluding {@link #graphicSettings} and
* {@link #filePaths} ) from the disk.
* <p>
* {@link #filePaths}, {@link #loadOnStartup} and {@link #data} will be
* updated to reflect the changes.
*/
public final void deleteAll() {
for (int i = 0; i < filePaths.size(); i++) {
// keep special files
if (filePaths.get(i).equals(GRAPHICS_SETTINGS_PATH) || filePaths.get(i).equals(LOAD_ON_STARTUP_PATH))
continue;
// remove ordinary files
getFileHandle(rootDataPath + "/" + filePaths.get(i)).delete();
data.clear();
loadOnStartup.clear();
data.put(GRAPHICS_SETTINGS_PATH, graphicSettings);
data.clear();
filePaths.clear();
save(LOAD_ON_STARTUP_PATH, loadOnStartup, true, true);
save(GRAPHICS_SETTINGS_PATH, graphicSettings, true, true);
}
}
// endregion delete
// region get
/**
* Returns the entry in the {@link #data} with the specificied key parameter
*
* @param dataName
* The key to be used for retrieval of the value tied to it from
* {@link #data}
* @return The value for the specified key or null, based on whether or not
* it exists in the Dictionary
*/
public final Object get(String dataName) {
return (data.containsKey(dataName)) ? data.get(dataName) : null;
}
public final ArrayList<Object> getAllFromFolder(String folderName) {
ArrayList<Object> objects = new ArrayList<Object>();
for (Entry<String, Object> entry : data.entries()) {
if (entry.key.startsWith(folderName)) {
objects.add(entry.value);
}
}
return objects;
}
// endregion get
// region loadData
/**
* Loads a file in memory. This method has to be call in order to load data
* that had the <code>loadOnstartup</code> parameter passed in
* {@link #saveData(String, Object, boolean)} set to false, otherwise the
* asset will already be loaded at startup.
* <p>
* If the data is already in memory, the request is ignored.
*
* @param filepath
* the path to the file to load. It is the path relative to the
* root file path.
*/
public Object load(String filepath) {
// already loaded, return
if (contains(filepath))
return null;
if (exists(filepath)) {
Object obj;
try {
obj = deserialize(getFileHandle(rootDataPath + "/" + filepath + ".dd").readBytes());
data.put(filepath, obj);
Lumm.debug.log("Deserialized file at path \"" + filepath + "\"", null);
return obj;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Uncloads a file from memory. For an asset to be loaded, upon saving the
* data using {@link #saveData(String, Object, boolean)}, the
* <code>loadOnStartup</code> parameter has to be true, or
* {@link #load(String)} has to be called.
* <p>
* If the data is not in memory anymore, the request is ignored
*
* @param filepath
* the path to the file to unload. It is the path relative to the
* root file path.
*/
public final void unload(String filepath) {
// not loaded, return;
if (!contains(filepath))
return;
data.remove(filepath);
}
/**
* Releases the references to files. File paths will not be removed, so you
* would still know where all the files are using {@link #exists(String)}.
* <p>
* . For an asset to be loaded, upon saving the data using
* {@link #saveData(String, Object, boolean)}, the
* <code>loadOnStartup</code> parameter has to be true, or
* {@link #load(String)} has to be called.
* <p>
* If the data is not in memory anymore, the request is ignored
*/
public final void unloadAll() {
data.clear();
}
// endregion loadData
// endregion API
// region internal
private byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
private Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
private FileHandle getFileHandle(String path) {
if (storageType.equals(StorageType.None))
return null;
if (storageType.equals(StorageType.External))
return Gdx.files.external(path);
return Gdx.files.local(path);
}
/**
* Returns the Data folder.
* <p>
* It will be created if it doesn't exists.
*
* @return The Data folder
*/
private final FileHandle getRootDataFolder() {
FileHandle file = getFileHandle(rootDataPath.substring(0, rootDataPath.length() - 1));
// there is no root data folder
if (!file.exists() || !file.isDirectory()) {
// making files if they don't exist
if (!file.exists() && rootDataFolder != null) {
file.mkdirs();
saveAll();
} else {
file.mkdirs();
}
rootDataFolder = file;
}
return file;
}
/**
* Method for recursively accessing files.
* <p>
* Goes over all the files in a folder( keeping in mind the name of the path
* so far from Data until the current file) if it is a folder, if not, tries
* to deserialise it and add it to {@link #data} with the key being the path
* from Data to the file ( excluding Data/) and the value being the
* deserialised object.
* <p>
* No need to check for storageType to be {@link StorageType#None} as this
* is called from all files.
*
* @param folder
* current file to search through
* @param currentPathString
* the path so far.
*/
private void getDataFromFolder(FileHandle folder, String currentPathString) {
// get a list of all files
FileHandle[] filesInFolder = folder.list();
if (filesInFolder == null)
return;
for (int i = 0; i < filesInFolder.length; i++) {
// // can't read, don't bother handling it.
// if (!filesInFolder[i].)
// continue;
if (filesInFolder[i].isDirectory()) {
getDataFromFolder(filesInFolder[i], currentPathString + filesInFolder[i].name() + "/");
} else
// object is file
{
// remove the .dd from it
String filepath = currentPathString
+ filesInFolder[i].name().substring(0, filesInFolder[i].name().length() - 3);
Lumm.debug.log("Found file at path \"" + filepath + "\"", null);
if (!exists(filepath))
filePaths.add(filepath);
}
}
}
@Override
public List<Class<? extends LummModule>> getDependencies() {
List<Class<? extends LummModule>> modules = new ArrayList<Class<? extends LummModule>>();
modules.add(Debug.class);
return modules;
}
// endregion internal
// endregion methods
}
|
package com.git.cloud.resmgt.common.dao.impl;
import java.util.List;
import org.springframework.stereotype.Service;
import com.git.cloud.common.dao.CommonDAOImpl;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.resmgt.common.dao.IRmDatacenterDAO;
import com.git.cloud.resmgt.common.model.po.CmDatastorePo;
import com.git.cloud.resmgt.common.model.po.RmDatacenterPo;
import com.git.cloud.resmgt.compute.model.po.ScanHmcHostPo;
@Service
public class RmDatacenterDAO extends CommonDAOImpl implements IRmDatacenterDAO {
@Override
public RmDatacenterPo getDataCenterById(String dcId)
throws RollbackableBizException {
return super.findObjectByID("selectDataCenterById", dcId);
}
public ScanHmcHostPo findHmcHostInfoById(String hostId) throws RollbackableBizException{
return super.findObjectByID("selectHmcHostInfoById", hostId);
}
@Override
public RmDatacenterPo getDataCenterByHostId(String hostId)
throws RollbackableBizException {
return super.findObjectByID("selectDataCenterByHostId", hostId);
}
@Override
public List<RmDatacenterPo> getDataCenters()
throws RollbackableBizException {
return super.findAll("selectDataCenter");
}
@Override
public List<RmDatacenterPo> getDataCenterByLikeForName(String dataCenterName)
throws RollbackableBizException {
return super.findByID("selectDataCenterByLike", dataCenterName);
}
@Override
public RmDatacenterPo getStorageTreeSpecified(String clusterId) throws RollbackableBizException {
return super.findObjectByID("getStorageTreeSpecified", clusterId);
}
@Override
public List<CmDatastorePo> queryStorageDataStoresPagination(String storage_id) throws RollbackableBizException {
return super.findByID("queryStorageDataStoresPagination", storage_id);
}
@Override
public void saveRmDatacenter(RmDatacenterPo rmDatacenterPo) throws RollbackableBizException {
super.save("insertRmDatacenter", rmDatacenterPo);
}
@Override
public void updateRmDatacenter(RmDatacenterPo rmDatacenterPo) throws RollbackableBizException {
super.update("updateRmDatacenter", rmDatacenterPo);
}
@Override
public String selectPoolByDatacenterId(String dataCenterId) throws RollbackableBizException {
int count = (Integer)getSqlMapClientTemplate().queryForObject("selectPoolByDatacenterId", dataCenterId);
return count+"";
}
@Override
public void deleteDatacenter(String[] split) throws RollbackableBizException {
for (int i = 0; i < split.length; i++) {
super.deleteForIsActive("deleteDatacenter", split[i]);
}
}
@Override
public RmDatacenterPo selectQueueIdenfortrim(String queueIden) throws RollbackableBizException {
return super.findObjectByID("selectQueueIdenfortrim", queueIden);
}
@Override
public RmDatacenterPo selectDCenamefortrim(String ename) throws RollbackableBizException {
return super.findObjectByID("selectDCenamefortrim", ename);
}
@Override
public List<RmDatacenterPo> getDataCenterAccessData() throws RollbackableBizException {
return super.findAll("selectVCenterAccessData");
}
}
|
/*
* Header
* @Author: Aaron Lack, alack
* Last edited: 3/11/20
* In this class, I am using the shapeDriver instance variable of type JPanel to create a window
* I am then going to use the typical JFrame stuff but use this.____ instead.
* Then, I'm going implement the timer class to run this code and produce shapes for a given time.
* I will do this by using a try/catch, similar to if/else, for running this program.
*/
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionListener;
/*
* Main application for random shape generator app
* NOTE: You are encouraged to experiment and try out various approaches
* The comments given here are just guidelines to get you started
* Possibly, this problem can be completed in many ways.
*/
public class ShapeWindow extends JFrame {
JPanel shapeDriver;
public ShapeWindow() {
//An empty super takes in everything
super();
// TO-DO: set up the frame
/*
Create a ShapeDriver object here (which is a JPanel)
and add it to ShapeWindow (which is a JFrame). Don't forget to setSize,
setVisible and any other required attributes (you might want to add the ShapeDriver
object to the ContentPane (using this.getContentPane()) instead of directly adding
to ShapeWindow.
You can initialize a Timer here (with appropriate milliseconds and your
ShapeDriver obj created above as params). Use the timer.start() method to start Timer.
However, you would also want to do Thread.sleep(<Appropriate milliseconds here>) afterwards
It should be within a try-catch block. You can leave the catch block empty or provide some sysout msg
You can stop your timer object after the try-catch block
*/
JPanel shapeDriver = new ShapeDriver();
this.add(shapeDriver);
this.setSize(600,600);
this.setTitle("Shape Window");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(shapeDriver);
this.setVisible(true);
Timer timer = new Timer(1000/60, (ActionListener) shapeDriver);
timer.start();
//Try catch for the timer.
try {
Thread.sleep(1000/60);
}
catch(Exception i) {
System.out.println("");
}
timer.stop();
}
public static void main(String[] args) {
// Create a JFrame and invoke the constructor
JFrame shapeWindow = new ShapeWindow();
}
}
|
package com.zhicai.byteera.commonutil;
import android.content.Context;
import android.view.View;
import me.drakeet.materialdialog.MaterialDialog;
/** Created by bing on 2015/4/14. */
public class DialogUtil {
private static boolean isShow;
public interface DialogPositiveButtonClickListener {
void positiveClick();
}
public static void showDialog(Context context, int title, int message, int positiveBtn, final DialogPositiveButtonClickListener listener) {
if (!isShow) {
final MaterialDialog materialDialog;
try {
materialDialog = new MaterialDialog(context);
if(title != -1){
materialDialog.setTitle(title);
}
materialDialog.setMessage(message);
materialDialog.setPositiveButton(positiveBtn, new View.OnClickListener() {
@Override public void onClick(View v) {
materialDialog.dismiss();
isShow = false;
if(listener != null){
listener.positiveClick();
}
}
});
materialDialog.show();
isShow = true;
} catch (Exception e) {
SDLog.e("DialogError:", "---------color userRemovedBuilder error" + e.getMessage());
}
}
}
}
|
package com.geoblink.clientStore.pojo;
import java.math.BigDecimal;
import com.vividsolutions.jts.geom.Point;
public class ClientStore {
private Integer idStore;
private String name;
private String telephone;
private BigDecimal sales;
private String city;
private Integer idBrand;
private Integer idCompany;
private Point latitude;
private Point longitude;
public Integer getIdStore() {
return idStore;
}
public void setIdStore(Integer idStore) {
this.idStore = idStore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public BigDecimal getSales() {
return sales;
}
public void setSales(BigDecimal sales) {
this.sales = sales;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Integer getIdBrand() {
return idBrand;
}
public void setIdBrand(Integer idBrand) {
this.idBrand = idBrand;
}
public Integer getIdCompany() {
return idCompany;
}
public void setIdCompany(Integer idCompany) {
this.idCompany = idCompany;
}
public Point getLatitude() {
return latitude;
}
public void setLatitude(Point latitude) {
this.latitude = latitude;
}
public Point getLongitude() {
return longitude;
}
public void setLongitude(Point longitude) {
this.longitude = longitude;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((idStore == null) ? 0 : idStore.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClientStore other = (ClientStore) obj;
if (idStore == null) {
if (other.idStore != null)
return false;
} else if (!idStore.equals(other.idStore))
return false;
return true;
}
}
|
package com.anton.kth_laboration_1;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.xml.sax.Parser;
import java.io.File;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
public class MainActivity extends AppCompatActivity {
private CurrencyManager currencyManager;
private Currency selectedFrom;
private Currency selectedTo;
//public static final String currency_url = "http://maceo.sth.kth.se/Home/eurofxref";
public static final String currency_url = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner_from = (Spinner) findViewById(R.id.spinner_rate_from);
Spinner spinner_to = (Spinner) findViewById(R.id.spinner_cur_to);
final EditText value_from = (EditText) findViewById(R.id.value_from);
//Handler event for when an item is selected from the spinner.
spinner_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedFrom = (Currency)parent.getSelectedItem();
updateConversion();
((TextView)findViewById(R.id.text_rate_from)).setText("Rate: " + selectedFrom.getRate());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
//Handler event for when an item is selected from the spinner.
spinner_to.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedTo = (Currency)parent.getSelectedItem();
updateConversion();
((TextView)findViewById(R.id.text_rate_to)).setText("Rate: " + selectedTo.getRate());
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//Handler event for when a new FROM value has been set by the user.
value_from.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId == EditorInfo.IME_ACTION_DONE){
updateConversion();
return true;
}
return false;
}
});
}
@Override
protected void onStart(){
super.onStart();
ParserTask tsk = new ParserTask(this);
tsk.execute(currency_url);
}
/**
* This method converts the input value to the target currency.
*/
private void updateConversion(){
if(selectedTo != null && selectedFrom != null){
EditText value_from = (EditText)findViewById(R.id.value_from);
TextView result = (TextView)findViewById(R.id.value_to);
if(value_from.getText().length() < 1){
value_from.setText("1");
showToast("Input field must not be empty!");
}
//Convert to euro.
Double inEuro = Double.parseDouble(value_from.getText().toString())/selectedFrom.getRate();
//Convert to target currency.
Double resultConversion = inEuro * selectedTo.getRate();
//display result
result.setText("" + resultConversion);
}
}
/**
*
*/
private class ParserTask extends AsyncTask<String, Void, CurrencyManager>{
private MainActivity activity;
public ParserTask(MainActivity activity){
this.activity = activity;
}
@Override
protected CurrencyManager doInBackground(String... params){
//android.os.Debug.waitForDebugger();
try{
URL url = new URL(params[0]);
CurrencyManager mngr = new CurrencyManager(activity);
//attempt to load currencies from existing file.
mngr.loadCurrenciesFromFile();
if(!mngr.isLoadedFromFile()){
//file was not loaded. Get from web
mngr.loadCurrencies(url);
}else{
//data was loaded from file. compare dates
Calendar today = Calendar.getInstance();
mngr.getLoadDate().compareTo(today);
long diff = today.getTime().getTime() - mngr.getLoadDate().getTime().getTime();
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if(days > 1){
//we should refresh data
mngr.loadCurrencies(url);
}
}
return mngr;
}catch(Exception e){
this.cancel(true);
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(CurrencyManager currencyMngr){
currencyManager = null;
currencyManager = currencyMngr;
if(currencyManager.isLoadedFromFile()){
showToast("Using currencies from " + currencyMngr.getLoadDate().getTime().toString());
}else{
showToast("Downloaded " + currencyManager.getCurrencies().size() + " items.");
}
Spinner spinner_from = (Spinner) findViewById(R.id.spinner_rate_from);
Spinner spinner_to = (Spinner) findViewById(R.id.spinner_cur_to);
ArrayAdapter<Currency> adapter = new ArrayAdapter(activity, R.layout.support_simple_spinner_dropdown_item, currencyMngr.getCurrencies());
spinner_from.setAdapter(adapter);
spinner_to.setAdapter(adapter);
}
@Override
protected void onCancelled(CurrencyManager manager){showToast("Could not load list with currencies.");}
}
private void showToast(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}
|
class home_work
{
public static void main(String args[])
{
byte a=80,b=-20,c=15,d=-5;
int i=-10;
a=(byte)(a>>4);//right shift
System.out.println("Right shifted Value of var a:-"+a);
b=(byte)(b>>2);//right shift
System.out.println("Right shifted Value of var b:-"+b);
i=i>>>24;
System.out.println("Right shifted Value of var i:-"+i);
d=(byte)(d<<1);//left shift
System.out.println("left shifted Value of var d:-"+d);
}
} |
package com.ws.bean;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSON;
/**
* 测试 gt-grid组件 实体类 student
* @author whn
* @date 2014-03-13
*/
public class Student {
private int no; //学生学号
private String name; //学生姓名
private int age; //学生年龄
private String gender; //性别
private double english; //英语成绩
private double math; //数学成绩
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public double getEnglish() {
return english;
}
public void setEnglish(double english) {
this.english = english;
}
public double getMath() {
return math;
}
public void setMath(double math) {
this.math = math;
}
public Student(int no, String name, int age, String gender, double english,
double math) {
super();
this.no = no;
this.name = name;
this.age = age;
this.gender = gender;
this.english = english;
this.math = math;
}
public Student() {
super();
}
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
for (int i=0;i<100;i++){
Student stu = new Student();
stu.setAge((int)(Math.random()*80));
stu.setEnglish(Math.random()*120+10);
stu.setMath(Math.random()*120+10);
stu.setNo(i);
stu.setGender(-1*i+"");
stu.setName("stu"+i);
list.add(stu);
}
String s = JSON.toJSONString(list.get(0));
System.out.println(s);
}
}
|
package HibFiles;
// Generated Jun 15, 2016 6:41:39 PM by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
/**
* Unit generated by hbm2java
*/
public class Unit implements java.io.Serializable {
private Integer idunit;
private String name;
private Set<RecipeHasIngredient> recipeHasIngredients = new HashSet<RecipeHasIngredient>(0);
public Unit() {
}
public Unit(String name, Set<RecipeHasIngredient> recipeHasIngredients) {
this.name = name;
this.recipeHasIngredients = recipeHasIngredients;
}
public Integer getIdunit() {
return this.idunit;
}
public void setIdunit(Integer idunit) {
this.idunit = idunit;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<RecipeHasIngredient> getRecipeHasIngredients() {
return this.recipeHasIngredients;
}
public void setRecipeHasIngredients(Set<RecipeHasIngredient> recipeHasIngredients) {
this.recipeHasIngredients = recipeHasIngredients;
}
}
|
package org.firstinspires.ftc.teamcode.control.constants;
/**
* Class that stores constants for drivetrain control
* Created by Ronnie on 1/21/2019
*/
public class DriveConstants {
//Encoder values per revolution and per inch calculated
public final static double TICKS_PER_REVOLUTION = 537.6;
public final static int WHEEL_DIAMETER = 4;
public final static double WHEEL_CIRCUMFERENCE = WHEEL_DIAMETER*Math.PI;
public final static double TICKS_PER_INCH = TICKS_PER_REVOLUTION/WHEEL_CIRCUMFERENCE;
public final static double EXPERIMENTAL_TICKS_PER_INCH = 3000/22;
public final static double TICKS_PER_DEGREE = (5000/166)*(537.6/1680);
public final static double VELOCITY = 32;
}
|
package awt;
import java.awt.*;
import java.awt.event.*;
public class WindowAdapterDemo extends Frame implements WindowFocusListener, WindowListener, WindowStateListener {
public WindowAdapterDemo() {
addWindowListener(this);
addWindowFocusListener(this);
addWindowStateListener(this);
setBounds(30, 30, 400, 200);
setVisible(true);
}
public static void main(String[] args) {
new WindowAdapterDemo();
}
public void windowActivated(WindowEvent e) {
System.out.println("Activated");
}
public void windowClosed(WindowEvent e) {
System.out.println("Closed");
}
public void windowClosing(WindowEvent e) {
System.out.println("Closing");
}
public void windowDeactivated(WindowEvent e) {
System.out.println("Deactivated");
}
public void windowDeiconified(WindowEvent e) {
System.out.println("Deiconified");
}
public void windowGainedFocus(WindowEvent e) {
System.out.println("GainedFocus");
}
public void windowIconified(WindowEvent e) {
System.out.println("Iconified");
}
public void windowLostFocus(WindowEvent e) {
System.out.println("LostFocus");
}
public void windowOpened(WindowEvent e) {
System.out.println("Opened");
}
public void windowStateChanged(WindowEvent e) {
System.out.println("StateChanged");
}
} |
package lambdaprimitives;
import java.util.ArrayList;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.stream.Collectors;
public class SportGadgetStore {
private final List<Product> products;
public SportGadgetStore(List<Product> products) {
this.products = new ArrayList<>(products);
}
public long getNumberOfProducts() {
return products.stream().mapToInt(Product::getCount).sum();
}
public String getExpensiveProductStatistics(double value) {
List<Product> tmp = products.stream().filter(o -> o.getPrice() > value).collect(Collectors.toList());
if (tmp.size() > 0) {
IntSummaryStatistics stat = tmp.stream().mapToInt(Product::getCount).summaryStatistics();
return "Összesen " + stat.getCount() + " féle termék, amelyekből minimum " + stat.getMin() + " db, maximum " + stat.getMax() + " db, összesen " + stat.getSum() + " db van.";
}
return "Nincs ilyen termék.";
}
public double getAveragePrice() {
return products.stream().mapToDouble(Product::getPrice).average().orElse(0);
}
}
|
package com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip;
import android.os.Parcel;
import android.os.Parcelable;
import com.uit.huydaoduc.hieu.chi.hhapp.Define;
import com.uit.huydaoduc.hieu.chi.hhapp.DefineString;
import com.uit.huydaoduc.hieu.chi.hhapp.Framework.TimeUtils;
import com.uit.huydaoduc.hieu.chi.hhapp.Main.CalculateFare;
import com.uit.huydaoduc.hieu.chi.hhapp.Model.Car.CarType;
import java.text.DecimalFormat;
import java.util.Date;
public class TripFareInfo implements Parcelable {
private CarType carType;
private Float estimateFare;
private Float duration;
private Float distance;
private String startTime;
// Note: This for Null Exception
public TripFareInfo() {
estimateFare = 0f;
duration = 0f;
distance = 0f;
carType = Define.DEFAULT_CAR_TYPE;
startTime = TimeUtils.getCurrentTimeAsString();
}
public String func_getCarTypeText() {
return DefineString.CAR_TYPE_MAP.get(carType);
}
public String func_getEstimateFareText() {
DecimalFormat decimalFormat = new DecimalFormat("#,##0");
String s = decimalFormat.format(estimateFare);
return "VND " + s + "K";
}
public void func_RecalculateEstimateFare() {
this.estimateFare = CalculateFare.getEstimateFare(carType,func_getStartTimeAsDate(),distance,duration)/1000;
}
public Date func_getStartTimeAsDate() {
return TimeUtils.strToDate(startTime);
}
public String func_getDurationText() {
return Integer.toString((int) (duration/60)) + " min";
}
public TripFareInfo(CarType carType, Date startTime, Float duration, Float distance) {
this.carType = carType;
this.startTime = TimeUtils.dateToStr(startTime);
this.estimateFare = CalculateFare.getEstimateFare(carType,startTime,distance,duration)/1000;
this.duration = duration;
this.distance = distance;
}
public CarType getCarType() {
return carType;
}
public void setCarType(CarType carType) {
this.carType = carType;
}
public Float getEstimateFare() {
return estimateFare;
}
public void setEstimateFare(Float estimateFare) {
this.estimateFare = estimateFare;
}
public Float getDuration() {
return duration;
}
public void setDuration(Float duration) {
this.duration = duration;
}
public Float getDistance() {
return distance;
}
public void setDistance(Float distance) {
this.distance = distance;
}
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.carType == null ? -1 : this.carType.ordinal());
dest.writeValue(this.estimateFare);
dest.writeValue(this.duration);
dest.writeValue(this.distance);
dest.writeString(this.startTime);
}
protected TripFareInfo(Parcel in) {
int tmpCarType = in.readInt();
this.carType = tmpCarType == -1 ? null : CarType.values()[tmpCarType];
this.estimateFare = (Float) in.readValue(Float.class.getClassLoader());
this.duration = (Float) in.readValue(Float.class.getClassLoader());
this.distance = (Float) in.readValue(Float.class.getClassLoader());
this.startTime = in.readString();
}
public static final Creator<TripFareInfo> CREATOR = new Creator<TripFareInfo>() {
@Override
public TripFareInfo createFromParcel(Parcel source) {
return new TripFareInfo(source);
}
@Override
public TripFareInfo[] newArray(int size) {
return new TripFareInfo[size];
}
};
}
|
package ur.ur_flow.coupon;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.Api.CommonParameters;
import com.ambit.city_guide.R;
import com.gtambit.gt.app.member.MemberWebActivity;
import com.gtambit.gt.app.mission.api.TaskSharedPreferences;
import com.gtambit.gt.app.mission.obj.ProfileType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import lib.hyxen.ui.ListPager;
import lib.hyxen.ui.SimpleDialog;
import ur.api_ur.api_data_obj.poi.URPoiObj;
import ur.api_ur.api_data_obj.store.URCouponObj;
import ur.api_ur.api_data_obj.sys.URApiSysResponseObj;
import ur.ga.URBigData;
import ur.ga.URGAManager;
import ur.ui_component.URCateListFragment;
import ur.ur_flow.coupon.obj.CateObj;
import ur.ur_flow.coupon.obj.OnNextListener;
import ur.ur_flow.managers.URCouponManager;
import ur.ur_item_ctr.CouponListItemCtrl;
/**
* This fragment don't have ability to navigate.
* <p>
* Because don't won't to re-write function so extend HxNavigationFragment.
* <p>
* TODO: sort by cate, animation to expend cate list.
* <p>
* Created by redjack on 15/9/23.
*/
public class CouponListFragment extends URCateListFragment<URCouponObj> implements CouponDetailFragment.OnCouponStateChangeListener,
URCouponManager.CouponLoadedListener,
ListPager.ListPagerListener, android.location.LocationListener {
ListPager<URCouponObj> adapter;
ListPager.ListPagerTask task;
URPoiObj assignedPoi;
URCouponManager couponManager;
OnNextListener onNextListener;
private LocationManager locationMgr;
private Double Longitude, Latitude;
public static CouponListFragment initial(URPoiObj assignedPoi, OnNextListener onNextListener) {
CouponListFragment f = new CouponListFragment();
f.assignedPoi = assignedPoi;
f.onNextListener = onNextListener;
f.hasActionBar = false;
return f;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainView = super.onCreateView(inflater, container, savedInstanceState);
couponManager = URCouponManager.getInstance(getActivity());
return mainView;
}
@Override
public void onResume() {
super.onResume();
adapter.loadFirstPage();
this.locationMgr = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
//取得位置提供者,不下條件,讓系統決定最適用者,true 表示生效的 provider
String provider = this.locationMgr.getBestProvider(new Criteria(), true);
if (provider == null) {
return;
}
this.locationMgr.requestLocationUpdates(provider, 0, 0, this);
Location location = this.locationMgr.getLastKnownLocation(provider);
if (location == null) {
return;
}
this.onLocationChanged(location);
}
@Override
protected void updateDistance() {
ArrayList<URCouponObj> coupons = task.getAll();
for (URCouponObj coupon : coupons) {
Double listlat = coupon.lat;
Double listlong = coupon.lon;
float listdistance = 0;
if (Latitude != null && Longitude != null) {
Location crntLocation = new Location("");
crntLocation.setLatitude(Latitude);
crntLocation.setLongitude(Longitude);
Location newLocation = new Location("");
newLocation.setLatitude(listlat);
newLocation.setLongitude(listlong);
listdistance = crntLocation.distanceTo(newLocation); // in m
// listdistance = listdistance / 1000;//km
coupon.couponKm = (int) listdistance;
}
// coupon.couponKm =
}
URCouponObj.sSort = URCouponObj.SORT_DISTANCE;
Collections.sort(coupons);
adapter.notifyDataSetChanged();
}
@Override
protected void oldCoupon() {
ArrayList<URCouponObj> coupons = task.getAll();
URCouponObj.sSort = URCouponObj.SORT_OLDCOUPON;
Collections.sort(coupons);
adapter.notifyDataSetChanged();
}
@Override
protected void newToOldCoupon() {
ArrayList<URCouponObj> coupons = task.getAll();
URCouponObj.sSort = URCouponObj.SORT_NEWTOOLDCOUPON;
Collections.sort(coupons);
for (URCouponObj coupon : coupons) {
Log.e("new_times", String.valueOf(coupon.start_ts));
}
adapter.notifyDataSetChanged();
}
//region = Cate Event =
@Override
public BaseAdapter onCreateItemAdapter() {
adapter = new ListPager(getActivity(), CouponListItemCtrl.class, 0, 30, this);
return adapter;
}
@Override
public void onListItemClick(URCouponObj item, int position) {
if (onNextListener == null) return;
onNextListener.onNextFragmentNeedShow(CouponDetailFragment.initial(item, assignedPoi, CouponListFragment.this));
}
@Override
public boolean onShouldFetchCateFromSys() {
return assignedPoi == null && cateListAdapter.getCount() < 1;
}
@Override
public ArrayList<CateObj> onLoadedSysInfo(URApiSysResponseObj sysInfo) {
return new ArrayList<CateObj>(Arrays.asList(sysInfo.tag_cat_arr));
}
@Override
public void onCateChanged(CateObj cate) {
adapter.clearAllAndReload(); //TODO: Filter
}
//endregion
//region = Load Coupon =
private static final String TAG = "CouponListFragment";
//優惠好康頁面 -> 刷新資料
@Override
public void needToLoadNextPage(final ListPager.ListPagerTask task) {
this.task = task;
ArrayList<URCouponObj> coupons = task.getAll();
final JSONArray jsonArray = new JSONArray();
HashMap<String, JSONObject> hashMap = new HashMap<>();
for (URCouponObj coupon : coupons) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("event","coupon");
jsonObject.put("action","view");
jsonObject.put( "id", coupon.cpn_id);
String key = coupon.cpn_id;
hashMap.put(key, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
for (JSONObject object : hashMap.values()) {
jsonArray.put(object);
}
URBigData.CoupoViewBigData(getActivity(),jsonArray);
String cateVar = selectedCate != null && !selectedCate.isForAll() ? selectedCate.getCateString() : null;
if (assignedPoi != null)
couponManager.loadCouponList(assignedPoi, null, cateVar, task.getPage(), task.getReloadCount(), this);
else
couponManager.loadCouponList(assignedPoi, cateVar, null, task.getPage(), task.getReloadCount(), this);
}
@Override
public void onLoading() {
// TODO: 2016/5/30 線程堵塞導致processDialong 不會旋轉
showLoading();
}
@Override
public void onLoaded(boolean isOnline, ArrayList<URCouponObj> coupons) {
// updateDistance(coupons);
task.newDataArrive(coupons);
final JSONArray jsonArray = new JSONArray();
HashMap<String, JSONObject> hashMap = new HashMap<>();
for (URCouponObj coupon : coupons) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("event","coupon");
jsonObject.put("action","view");
jsonObject.put( "id", coupon.cpn_id);
String key = coupon.cpn_id;
hashMap.put(key, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
for (JSONObject object : hashMap.values()) {
jsonArray.put(object);
}
URBigData.CoupoViewBigData(getActivity(),jsonArray);
/// When has assigned poi, use custom cate for filter.
if (assignedPoi != null && cateListAdapter.getCount() == 0 && coupons.size() > 0) {
URCouponObj couponObj = coupons.get(0);
updateCateList(couponObj.getCustomCateList());
}
// TODO: 2016/5/11 不應使用static
if (assignedPoi != null && coupons.size() == 0 && adapter.getCount() == 0) {
SimpleDialog.showAlert(getFragmentManager(), getString(R.string.ur_f_coupon_text_store_has_no_coupon), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CommonParameters.mFragmentController.popBack();
}
});
}
if (adapter.getCount() == 0) {
showNoCouponNotice(assignedPoi != null, coupons.size() == 0);
} else showNoCouponNotice(assignedPoi != null, false);
dismissLoading();
}
@Override
public void onNeedsToLoadNextPage() {
task.loadNextPage();
}
@Override
public void onTokenInvalid() {
dismissLoading();
SimpleDialog.showAlert(getFragmentManager(), getString(R.string.ur_gen_alert_login_fail), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ProfileType.saveUserId(getActivity(), null);
TaskSharedPreferences.saveApiToken(getActivity(), "");
Intent i = new Intent();
i.setClass(getActivity(), MemberWebActivity.class);
startActivity(i);
getActivity().finish();
}
});
}
//endregion
/// Will only change to got or remove.
@Override
public void onCouponStateChange(boolean needsToRemove, URCouponObj couponObj) {
adapter.removeItem(couponObj);
if (adapter.getCount() == 0) showNoCouponNotice(assignedPoi != null, true);
}
@Override
public void onLocationChanged(Location location) {
if (location == null) {
Latitude = CommonParameters.getLastLatlng().latitude;
Longitude = CommonParameters.getLastLatlng().longitude;
} else {
Latitude = location.getLatitude();
Longitude = location.getLongitude();
this.locationMgr.removeUpdates(this);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onPause() {
super.onPause();
this.locationMgr.removeUpdates(this);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
URGAManager.sendScreenName(getActivity(), getString(R.string.ga_coupon));
}
}
|
package com.appfountain;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class PostTitleActivity extends ActionBarActivity {
private static final String TAG = PostTitleActivity.class.getSimpleName();
private EditText titleEditText; // タイトル
private TextView textCount; // 文字数
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_title);
initViews();
}
// viewの初期化
private void initViews() {
titleEditText = (EditText) findViewById(R.id.post_title_body_text);
textCount = (TextView) findViewById(R.id.post_title_text_count);
// 前画面より質問文を受け取り,セットする
Intent intent = getIntent();
titleEditText.setText(intent.getStringExtra(Intent.EXTRA_TEXT + "title"));
updateTextCount(titleEditText.getText().toString()); // 文字数もセット
// 文字入力毎に文字数の表示を変えるイベントをつける
titleEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before,
int count) {
updateTextCount(titleEditText.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
private void updateTextCount(String text) {
textCount.setText(text.length() + " characters");
}
// OKボタンを推した際の処理
public void onOkClick(View view) {
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_TEXT + "title", titleEditText.getText().toString());
Log.d(Intent.EXTRA_TEXT + "title", titleEditText.getText().toString());
setResult(RESULT_OK, intent);
finish();
}
// 戻るボタンの処理をフック
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_TEXT + "title", titleEditText.getText()
.toString());
setResult(RESULT_CANCELED, intent);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package common.util.web;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import com.gaoshin.points.server.bean.ItemList;
import com.gaoshin.points.server.bean.UserBalanceList;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = {
ItemList.class,
UserBalanceList.class,
};
public JAXBContextResolver() throws Exception {
this.context = new JSONJAXBContext(JSONConfiguration
.mapped()
.arrays("list", "children", "items", "scenes", "msgs",
"values", "ucmList", "members", "attrNames").build(),
types);
}
public JAXBContext getContext(Class<?> objectType) {
for (Class type : types) {
if (type.equals(objectType)) {
return context;
}
}
return null;
}
}
|
package com.lesports.albatross.services;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.lesports.albatross.entity.community.MessageEntity;
import org.greenrobot.eventbus.EventBus;
/**
* 消息通知服务
* Created by jiangjianxiong on 16/6/22.
*/
public class MessageService extends Service {
public static final String ACTION = "com.lesports.albatross.services.MessageService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
}
@Override
public void onStart(Intent intent, int startId) {
new MessageThread().start();
}
private class MessageThread extends Thread {
@Override
public void run() {
EventBus.getDefault().post(new MessageEntity());
}
}
} |
package org.shujito.cartonbox;
import android.util.Log;
public class Logger
{
private static boolean loggingEnabled = true;
public static boolean isLoggingEnabled()
{
return loggingEnabled;
}
public static void setLoggingEnabled(boolean b)
{
loggingEnabled = b;
}
public static int d(String tag, String msg)
{
if(loggingEnabled)
return Log.d(tag, msg);
return 0;
}
public static int d(String tag, String msg, Throwable tr)
{
if(loggingEnabled)
return Log.d(tag, msg, tr);
return 0;
}
public static int e(String tag, String msg)
{
if(loggingEnabled)
return Log.e(tag, msg);
return 0;
}
public static int e(String tag, String msg, Throwable tr)
{
if(loggingEnabled)
return Log.e(tag, msg, tr);
return 0;
}
public static String getStackTraceString(Throwable tr)
{
if(loggingEnabled)
return Log.getStackTraceString(tr);
return null;
}
public static int i(String tag, String msg)
{
if(loggingEnabled)
return Log.i(tag, msg);
return 0;
}
public static int i(String tag, String msg, Throwable tr)
{
if(loggingEnabled)
return Log.i(tag, msg, tr);
return 0;
}
public static boolean isLoggable(String tag, int level)
{
if(loggingEnabled)
return Log.isLoggable(tag, level);
return false;
}
public static int println(int priority, String tag, String msg)
{
if(loggingEnabled)
return Log.println(priority, tag, msg);
return 0;
}
public static int v(String tag, String msg)
{
if(loggingEnabled)
return Log.v(tag, msg);
return 0;
}
public static int v(String tag, String msg, Throwable tr)
{
if(loggingEnabled)
return Log.v(tag, msg, tr);
return 0;
}
public static int w(String tag, Throwable tr)
{
if(loggingEnabled)
return Log.w(tag, tr);
return 0;
}
public static int w(String tag, String msg, Throwable tr)
{
if(loggingEnabled)
return Log.w(tag, msg, tr);
return 0;
}
public static int w(String tag, String msg)
{
if(loggingEnabled)
return Log.w(tag, msg);
return 0;
}
public static int wtf(String tag, Throwable tr)
{
if(loggingEnabled)
return Log.wtf(tag, tr);
return 0;
}
public static int wtf(String tag, String msg)
{
if(loggingEnabled)
return Log.wtf(tag, msg);
return 0;
}
public static int wtf(String tag, String msg, Throwable tr)
{
if(loggingEnabled)
return Log.wtf(tag, msg, tr);
return 0;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sample.form;
import sample.model.Contacts;
import java.util.List;
/**
*
* @author Administrator
*/
public class ContactForm {
private List<Contacts> contacts;
public List<Contacts> getContacts(){
return contacts;
}
public void setContacts(List<Contacts> contacts){
this.contacts = contacts;
}
}
|
package cyfixusBot.minigames;
import java.util.Random;
import cyfixusBot.bot.CyfixusBot;
import cyfixusBot.game.players.Player;
import cyfixusBot.util.StringListener;
/***********************************************************
*
* 2 Players
* sender && sender's target
* target will be extracted from !battle message
* slpit \s regex
* String[] [0] = "!*", [1] = "message"
* temp param for battle will be based upon
* random shit... mthll from player stats
*
* users
* getPlayer....
*/
public class Battle {
private Player playerOne;
private Player playerTwo;
private int winner;
private String channel;
private StringListener stringListener;
private CyfixusBot bot;
private Random random = new Random();
public Battle(Player playerOne, Player playerTwo, CyfixusBot bot,
String channel, StringListener stringListener){
this.playerOne = playerOne;
this.playerTwo = playerTwo;
this.bot = bot;
this.channel = channel;
this.stringListener = stringListener;
//initbattle
winner = declareWinner(battle());
}
/************************************************
* Compare Strength Stamina Intelligence Will
* based on random values obtained from the limits
* defined by the value of the stat
*/
public int[] battle(){
int pTotals[] = {0, 0};
String p1 = playerOne.getName();
String p2 = playerTwo.getName();
int p1Str = random.nextInt(playerOne.getStrength());
int p2Str = random.nextInt(playerTwo.getStrength());
int p1Sta = random.nextInt(playerOne.getStamina());
int p2Sta = random.nextInt(playerTwo.getStamina());
int p1Int = random.nextInt(playerOne.getIntelligence());
int p2Int = random.nextInt(playerTwo.getIntelligence());
int p1Wil = random.nextInt(playerOne.getWill());
int p2Wil =random.nextInt(playerTwo.getWill());
bot.sendMessage(channel, " - battle - ");
bot.sendMessage(channel, p1 +" vs. " + p2);
stringListener.textEmitted(" - battle - \n");
stringListener.textEmitted(p1 +" vs. " + p2 + '\n');
//use ternarrryyy
if(p1Str > p2Str){
pTotals[0]++;
bot.sendMessage(channel, p1 + " overpowered " + p2);
stringListener.textEmitted(p1 + " overpowered " + p2 + '\n');
}
else if(p1Str < p2Str){
pTotals[1]++;
bot.sendMessage(channel, p2 + " smashed " + p1);
stringListener.textEmitted(p2 + " smashed " + p1 + '\n');
}
if(p1Sta > p2Sta){
pTotals[0]++;
bot.sendMessage(channel, p1 + " outlasted " + p2);
stringListener.textEmitted(p1 + " outlasted " + p2 + '\n');
}
else if(p1Sta < p2Sta){
pTotals[1]++;
bot.sendMessage(channel, p2 + " outendured " + p1);
stringListener.textEmitted( p2 + " outendured " + p1 + '\n');
}
if(p1Int > p2Int){
pTotals[0]++;
bot.sendMessage(channel, p1 + " outsmarted " + p2);
stringListener.textEmitted(p1 + " outsmarted " + p2 + '\n');
}
else if(p1Int < p2Int){
pTotals[1]++;
bot.sendMessage(channel, p2 + " outwitted " + p1);
stringListener.textEmitted(p2 + " outwitted " + p1 + '\n');
}
if(p1Wil > p2Wil){
pTotals[0]++;
bot.sendMessage(channel, p1 + " wanted it more than "
+ p2);
stringListener.textEmitted(p1 + " wanted it more than "
+ p2 + '\n');
}
else if(p1Wil < p2Wil){
pTotals[1]++;
bot.sendMessage(channel, p2 + " had the will to win "
+ p1);
stringListener.textEmitted(p2 + " had the will to win "
+ p1 + '\n');
}
return pTotals;
}
public int declareWinner(int[] bda){
int winner = -1;
if(bda[1] > bda[0]){
winner = 1;
}
else if(bda[0] > bda[1]){
winner = 0;
}
return winner;
}
public int getWinner(){
return winner;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab12;
/**
*
* @author ayush488
*/
public class Hashtable {
public Hashtable()
{}
public Hashtable(String key, int value)
{
}
public void add(String key, int value)
{
}
public void remove(String key)
{
}
private void hash(String key)
{
}
public int getNumELements()
{
return 0;
}
public boolean contains(String key)
{
return true;
}
}
|
/**
* Copyright 2013, Big Switch Networks, 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.
**/
/**
* Provides Flow Reconcile service to other modules that need to reconcile
* flows.
*/
package net.floodlightcontroller.flowcache;
import net.floodlightcontroller.core.module.IFloodlightService;
import net.floodlightcontroller.devicemanager.IDevice;
import net.floodlightcontroller.flowcache.IFlowCacheService.FCQueryEvType;
public interface IFlowReconcileService extends IFloodlightService {
/**
* Add a flow reconcile listener
* @param listener The module that can reconcile flows
*/
public void addFlowReconcileListener(IFlowReconcileListener listener);
/**
* Remove a flow reconcile listener
* @param listener The module that no longer reconcile flows
*/
public void removeFlowReconcileListener(IFlowReconcileListener listener);
/**
* Remove all flow reconcile listeners
*/
public void clearFlowReconcileListeners();
/**
* Reconcile flow. Returns false if no modified flow-mod need to be
* programmed if cluster ID is providced then pnly flows in the given
* cluster are reprogrammed
*
* @param ofmRcIn the ofm rc in
*/
public void reconcileFlow(OFMatchReconcile ofmRcIn);
/**
* Updates the flows to a device after the device moved to a new location
* <p>
* Queries the flow-cache to get all the flows destined to the given device.
* Reconciles each of these flows by potentially reprogramming them to its
* new attachment point
*
* @param device device that has moved
* @param handler handler to process the flows
* @param fcEvType Event type that triggered the update
*
*/
public void updateFlowForDestinationDevice(IDevice device,
IFlowQueryHandler handler,
FCQueryEvType fcEvType);
/**
* Updates the flows from a device
* <p>
* Queries the flow-cache to get all the flows source from the given device.
* Reconciles each of these flows by potentially reprogramming them to its
* new attachment point
*
* @param device device where the flow originates
* @param handler handler to process the flows
* @param fcEvType Event type that triggered the update
*
*/
public void updateFlowForSourceDevice(IDevice device,
IFlowQueryHandler handler,
FCQueryEvType fcEvType);
/**
* Generic flow query handler to insert FlowMods into the reconcile pipeline.
* @param flowResp
*/
public void flowQueryGenericHandler(FlowCacheQueryResp flowResp);
}
|
package com.word.wm;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* @Author hzc65
* @Date 2019/12/18 14 42
* @Describe
*/
public class ServletInitializer extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//Application的类名
return application.sources(ServletInitializer.class);
}
}
|
import java.util.ArrayList;
import java.util.List;
public class hoang {
public static void main(String[] args) {
int n = 8;
List<Integer> list = new ArrayList<>();
int[] index = new int[10];
for (int i = 0; i < n; i++)
index[i] = i;
for (int i = 0; i < n - 1; i++) {
// n-1 round
for (int j = 0; j < n / 2; j++) {
// n/2 matches every round
list.add(index[j]);
list.add(index[n - j - 1]);
}
for(int l=0;l<n;l++)
System.out.print(index[l]+" ");
shuffle(index, i, n);
}
}
private static void shuffle(int[] index, int i, int n) {
for (int m = 0; m < i+1; m++)
index[m+1] = n - i - 1+m;
for (int k = i+2; k < n; k++)
index[k]--;
for (int m = 0; m < n; m++)
System.out.print(index[m] + " ");
System.out.println();
}
}
|
package ua.siemens.dbtool.dao.hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import ua.siemens.dbtool.dao.CalendarDAO;
import ua.siemens.dbtool.model.timesheet.CalendarDay;
import ua.siemens.dbtool.model.timesheet.DayEntry;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Collection;
/**
* The implementation of {@link CalendarDAO} interface
*
* @author Perevoznyk Pavlo
* creation date 25 April 2018
* @version 1.0
*/
@Repository
public class CalendarDAOhiber extends GenericDAOhiber<CalendarDay, Long> implements CalendarDAO {
private static final Logger LOG = LoggerFactory.getLogger(CalendarDAOhiber.class);
private final String FIND_BY_PERIOD = "from CalendarDay where date >= :fromDate and date <= :toDate";
public CalendarDAOhiber() {
super(CalendarDay.class);
}
@Override
public Collection<CalendarDay> findByPeriod(int intYear, int intMonth) {
Query query = entityManager.createQuery(FIND_BY_PERIOD);
LocalDate fromDate = LocalDate.of(intYear, intMonth, 1);
LocalDate toDate = LocalDate.of(intYear, intMonth, fromDate.getMonth().length(fromDate.isLeapYear()));
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
return query.getResultList();
}
}
|
package com.emmanuj.todoo.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.emmanuj.todoo.models.ListGroup;
import com.emmanuj.todoo.models.ListItem;
import java.sql.Timestamp;
import java.util.ArrayList;
/**
* Created by emmanuj on 11/12/15.
*/
public class DBController {
private static TodooDBHelper mDbHelper;
private SQLiteDatabase db;
private String TABLE_LIST_GROUP = "list_groups";
private String TABLE_LIST_ITEM = "list_items";
private static volatile DBController instance;
private DBController(Context context) {
mDbHelper = new TodooDBHelper(context);
}
public static DBController getInstance(Context context){
if (instance == null ) {
synchronized (DBController.class) {
if (instance == null) {
instance = new DBController(context);
instance.connect();
}
}
}
return instance;
}
private void connect(){
//TODO: Log connected
db = mDbHelper.getWritableDatabase();
}
public void closeConnection(){
//TODO: log close connection
mDbHelper.close();
}
public long createListGroup(String content){
//TODO: Log create list group
ContentValues values = new ContentValues();
values.put("title",content);
long insertid = db.insert(TABLE_LIST_GROUP, "title", values );
return insertid;
}
public ListGroup getListGroup(long gid){
//TODO: Log return list group or list group not found
ListGroup grp = new ListGroup();
Cursor cursor = db.query(TABLE_LIST_GROUP, null, "groupid = "+ gid, null, null, null, null, null);
cursor.moveToFirst();
grp.setTitle(cursor.getString(cursor.getColumnIndex("title")));
grp.setId("" + cursor.getInt(cursor.getColumnIndex("groupid")));
grp.setCreated(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("created"))));
cursor.close();
return grp;
}
/**
*
* @param id The list group ID to delete
* @return number of rows in thr DB affected
*/
public int removeListGroup(long id){
//TODO: log remove
return db.delete(TABLE_LIST_GROUP, "groupid = "+ id, null); //return 1 otherwise returns 0.
}
/**
*
* @return number of rows deleted
*/
public int clearListGroups(){
return db.delete(TABLE_LIST_GROUP, null, null);
}
public ArrayList<ListGroup> getListGroups(){
//TODO: log get all groups
ArrayList<ListGroup> groups = new ArrayList();
// How you want the results sorted in the resulting Cursor
String sortOrder ="created DESC";
Cursor cursor = db.query(
TABLE_LIST_GROUP, // The table to query
null, // The columns to return //null returns all
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
ListGroup grp = new ListGroup();
//System.out.println(cursor.getString(cursor.getColumnIndex("created")));
grp.setTitle(cursor.getString(cursor.getColumnIndex("title")));
grp.setId("" + cursor.getInt(cursor.getColumnIndex("groupid")));
grp.setCreated(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("created"))));
groups.add(grp);
cursor.moveToNext();
}
cursor.close();
return groups;
}
public long createListItem(int gid, String content, int completed){
//TODO: Log create list group
ContentValues values = new ContentValues();
values.put("content", content);
values.put("completed", completed);
values.put("groupid", gid);
long insertid = db.insert(TABLE_LIST_ITEM, "content", values );
return insertid;
}
public ListItem getListItem(long id){
//TODO: Log return list group or list group not found
ListItem item = new ListItem();
Cursor cursor = db.query(TABLE_LIST_ITEM, null, "itemid = "+ id, null, null, null, null, null);
cursor.moveToFirst();
item.setText(cursor.getString(cursor.getColumnIndex("content")));
item.setId("" + cursor.getInt(cursor.getColumnIndex("itemid")));
item.setGroupid(cursor.getInt(cursor.getColumnIndex("groupid")));
int c = cursor.getInt(cursor.getColumnIndex("completed"));
if(c ==0){
item.setIsCompleted(false);
}else{
item.setIsCompleted(true);
}
item.setCreated(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("created"))));
cursor.close();
return item;
}
public int removeListItem(long id){
//TODO: log remove
return db.delete(TABLE_LIST_ITEM, "itemid = "+ id, null); //return 1 otherwise returns 0.
}
public int clearListItems(){
return db.delete(TABLE_LIST_ITEM, null, null);
}
public ArrayList<ListItem> getListItems(int groupid){
//TODO: log get all items for a group
ArrayList<ListItem> items = new ArrayList();
// How you want the results sorted in the resulting Cursor
String sortOrder ="created DESC";
Cursor cursor = db.query(
TABLE_LIST_ITEM, // The table to query
null, // The columns to return //null returns all
"groupid = "+groupid, // The columns for the WHERE clause (Selection criteria)
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
ListItem item = new ListItem();
item.setText(cursor.getString(cursor.getColumnIndex("content")));
item.setId("" + cursor.getInt(cursor.getColumnIndex("itemid")));
item.setGroupid(cursor.getInt(cursor.getColumnIndex("groupid")));
int c = cursor.getInt(cursor.getColumnIndex("completed"));
if(c ==0){
item.setIsCompleted(false);
}else{
item.setIsCompleted(true);
}
item.setCreated(Timestamp.valueOf(cursor.getString(cursor.getColumnIndex("created"))));
items.add(item);
cursor.moveToNext();
}
cursor.close();
return items;
}
public int updateListGroup(ListGroup grp){
ContentValues values = new ContentValues();
values.put("title", grp.getTitle());
int res = db.update(TABLE_LIST_GROUP,values,"groupid = "+grp.getId(),null);
return res;
}
public int updateListItem(ListItem listItem){
ContentValues values = new ContentValues();
values.put("content", listItem.getText());
values.put("completed", listItem.isCompleted()?1:0);
values.put("groupid", listItem.getGroupid());
int res = db.update(TABLE_LIST_ITEM, values,"itemid = "+ listItem.getId(), null);
return res;
}
}
|
/*
* Copyright (C) 2014 Vasilis Vryniotis <bbriniotis at datumbox.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.datumbox.framework.machinelearning.common.bases.mlmodels;
import com.datumbox.framework.machinelearning.common.bases.validation.ModelValidation;
/**
*
* @author Vasilis Vryniotis <bbriniotis at datumbox.com>
* @param <MP>
* @param <TP>
* @param <VM>
*/
public abstract class BaseMLregressor<MP extends BaseMLregressor.ModelParameters, TP extends BaseMLregressor.TrainingParameters, VM extends BaseMLregressor.ValidationMetrics> extends BaseMLmodel<MP, TP, VM> {
public static abstract class ModelParameters extends BaseMLmodel.ModelParameters {
//number of observations used for training
private Integer n =0 ;
//number of features in data. IN DATA not in the algorithm. Typically the features of the algortihm is d*c
private Integer d =0 ;
/*
@Override
public void bigDataStructureInitializer(BigDataStructureFactory bdsf, MemoryConfiguration memoryConfiguration) {
super.bigDataStructureInitializer(bdsf, memoryConfiguration);
}
*/
public Integer getN() {
return n;
}
public void setN(Integer n) {
this.n = n;
}
public Integer getD() {
return d;
}
public void setD(Integer d) {
this.d = d;
}
}
public static abstract class TrainingParameters extends BaseMLmodel.TrainingParameters {
}
//DO NOT DECLARE ABSTRACT!!!! IT IS INITIALIZED BY StepwiseRegression class
public static class ValidationMetrics extends BaseMLmodel.ValidationMetrics {
}
protected BaseMLregressor(String dbName, Class<MP> mpClass, Class<TP> tpClass, Class<VM> vmClass, ModelValidation<MP, TP, VM> modelValidator) {
super(dbName, mpClass, tpClass, vmClass, modelValidator);
}
} |
package com.zyzd.glidedemo.utils;
import android.app.Activity;
import com.zyzd.glidedemo.MyApp;
/**
* Created by 李宗源 on 2016/9/7.
*/
public class Device {
public static int getWidth(Activity activity){
return activity.getWindowManager().getDefaultDisplay().getWidth();
}
}
|
package com.base.danmaku;
public class DanmakuItem {
public static final int TYPE_NORMAL = 0;// 普通的
public static final int TYPE_COLOR_BG = 1;// 有背景颜色的
public static final int TYPE_GIFT = 2;// 送礼消息
public static final int TYPE_SYSTEM = 3;// 系统消息
public static final int TYPE_LIKE = 4;// 点亮消息
public int type = TYPE_NORMAL;
public String url;
public String text;
public String userName;
public String userId;
public int gender;
public String birthday;
public int giftId = -1;
public DanmakuItem() {
}
public DanmakuItem(String userName, String userId, String text, int type) {
this.userName = userName;
this.userId = userId;
this.text = text;
this.type = type;
}
}
|
package xml;
/*
* ClassName EventListCreator
*
* Created On: 03/02/07
*
* Purpose: To hold data parsed from the config file
*
*/
import java.util.ArrayList;
import java.util.List;
import data.InputDataType;
public class FileData {
private List<InputDataType> anticedentList;
private List<InputDataType> consequentList;
private double minFreq;
private float minConf;
private int antWidth;
private int consWidth;
private int lagWidth;
private String episodeType;
private String allowRepeats;
private int ruleType;
private String lagType;
private double minRelativeDensity;
public FileData() {
anticedentList = new ArrayList<InputDataType>();
consequentList = new ArrayList<InputDataType>();
}
public List<InputDataType> getAnticedentList() {
return anticedentList;
}
public List<InputDataType> getConsequentList() {
return consequentList;
}
public double getMinFreq() {
return minFreq;
}
public float getMinConf() {
return minConf;
}
public double getMinRelativeDensity() {
return this.minRelativeDensity;
}
public void setMinRelativeDensity(double density) {
this.minRelativeDensity = density;
}
public int getAntWidth() {
return antWidth;
}
public int getConsWidth() {
return consWidth;
}
public int getLagWidth() {
return lagWidth;
}
public String getEpisodeType() {
return episodeType;
}
public String getAllowRepeats() {
return allowRepeats;
}
public int getRuleType() {
return ruleType;
}
public String getLagType() {
return lagType;
}
public void setAnticedentList(List<InputDataType> anticedentList) {
this.anticedentList = anticedentList;
}
public void setConsequentList(List<InputDataType> consequentList) {
this.consequentList = consequentList;
}
public void setAntWidth(int antWidth) {
this.antWidth = antWidth;
}
public void setConsWidth(int consWidth) {
this.consWidth = consWidth;
}
public void setMinConf(float minConf) {
this.minConf = minConf;
}
public void setAllowRepeats(String allowRepeats) {
this.allowRepeats = allowRepeats;
}
public void setEpisodeType(String episodeType) {
this.episodeType = episodeType;
}
public void setLagType(String lagType) {
this.lagType = lagType;
}
public void setLagWidth(int lagWidth) {
this.lagWidth = lagWidth;
}
public void setMinFreq(double minFreq) {
this.minFreq = minFreq;
}
public void setRuleType(int ruleType) {
this.ruleType = ruleType;
}
public String toString() {
return this.anticedentList.toString() + "\n" +
this.consequentList.toString() + "\n" +
this.minFreq + "\n" +
this.minConf + "\n" +
this.antWidth + "\n" +
this.consWidth + "\n" +
this.lagWidth + "\n" +
this.episodeType + "\n" +
this.ruleType + "\n" +
this.lagType;
}
}
|
package ca.mcgill.ecse223.kingdomino.controller;
import java.io.*;
import java.util.*;
import ca.mcgill.ecse223.kingdomino.KingdominoApplication;
import ca.mcgill.ecse223.kingdomino.model.*;
import ca.mcgill.ecse223.kingdomino.model.Domino.DominoStatus;
import ca.mcgill.ecse223.kingdomino.model.Draft.DraftStatus;
import ca.mcgill.ecse223.kingdomino.model.Player.PlayerColor;
/**
* This class implements the controller methods for Domino
* @author Violet
*/
public class DominoController {
///////////////////////////// //////
////////////QueryMethods//// //////
/////////////////////////// //////
static TerrainType getTerrainType(String terrain) {
switch (terrain) {
case "W":
return TerrainType.WheatField;
case "F":
return TerrainType.Forest;
case "M":
return TerrainType.Mountain;
case "G":
return TerrainType.Grass;
case "S":
return TerrainType.Swamp;
case "L":
return TerrainType.Lake;
default:
throw new java.lang.IllegalArgumentException("Invalid terrain type: " + terrain);
}
}
public static Domino getdominoByID(int id) {
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
for (Domino domino : game.getAllDominos()) {
if (domino.getId() == id) {
return domino;
}
}
throw new java.lang.IllegalArgumentException("Domino with ID " + id + " not found.");
}
public static Draft getNextDraft(String nextDraft, Game game) {
Draft draft = new Draft(DraftStatus.Sorted, game);
String[] dominoids = nextDraft.split(",");
for (int i = 0; i < dominoids.length; i++) {
draft.addIdSortedDomino(getdominoByID(Integer.parseInt(dominoids[i])));
}
draft.setDraftStatus(DraftStatus.Sorted);
return draft;
}
public static List<Domino> getNextDraftDominos(Draft draft) {
List<Domino> nextDraftDominos = draft.getIdSortedDominos();
return nextDraftDominos;
}
public static List<DominoSelection> getDominoSelection(Draft draft) {
List<DominoSelection> dominoSelection = draft.getSelections();
return dominoSelection;
}
public static Domino getDominobyId(Integer id) {
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
Domino result = null;
for(Domino domino: game.getAllDominos()) {
if(domino.getId() == id)
result = domino;
}
return result;
}
public static List<Domino> getAllDominobyleftTtile(TerrainType left) {
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
dominosL = null;
for(Domino domino: game.getAllDominos()) {
if(domino.getLeftTile() == left)
dominosL.add(domino);
}
return dominosL;
}
public static List<Domino> getAllDominobyRightTile(TerrainType right) {
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
dominosR = null;
for(Domino domino: game.getAllDominos()) {
if(domino.getRightTile() == right)
dominosR.add(domino);
}
return dominosR;
}
public static List<Domino> getAllDominobyTerrainType(String terrain) {
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
dominos = null;
for(Domino domino: game.getAllDominos()) {
if((domino.getRightTile()).toString().equalsIgnoreCase(terrain) || (domino.getLeftTile()).toString().equalsIgnoreCase(terrain))
dominos.add(domino);
}
return dominos;
}
public static int getDominoTotalCrown(Domino domino) {
return domino.getLeftCrown() + domino.getRightCrown();
}
public static String getTerrainTypeString(TerrainType terrain) {
switch (terrain) {
case WheatField:
return "wheat";
case Forest:
return "forest";
case Mountain:
return "mountain";
case Grass:
return "grass";
case Swamp:
return "swamp";
case Lake:
return "lake";
default:
throw new java.lang.IllegalArgumentException("Invalid terrain type: " + terrain);
}
}
static Player currentPlayer;
private static List<Domino> dominosL;
private static List<Domino> dominosR;
private static List<Domino> dominos;
///////////////////////////// //////
///// ///Feature Methods//// //////
/////////////////////////// //////
/**
* Controller implemented for Feature 10: Choose Next Domino
* @param game, current game
* @param dominoId, domino id
* @return true if selection for next draft is different
* false if selection for next draft remains same
* @author Violet Wei
*/
public static boolean chooseNextDomino(Game game,int dominoId) {
Draft cDraft = game.getNextDraft();
if(GameplayController.statemachine.getGamestatus() == Gameplay.Gamestatus.Initializing)
cDraft = game.getCurrentDraft();
for(DominoSelection dominoSelection: cDraft.getSelections()){
if(dominoSelection.getDomino().getId() == dominoId)
return false;
}
Player p = game.getNextPlayer();
if(p.getDominoSelection()!=null){
p.getDominoSelection().delete();
}
Domino domino = getDominobyId(dominoId);
new DominoSelection(p, domino, cDraft);
return true;
}
/**
* Feature 11: Move Current Domino
* As a player, I wish to evaluate a provisional placement of my current
* domino by moving the domino around into my kingdom (up, down, left, right).
* @param player
* @param dominoId
* @author Violet Wei
*/
public static void initialMoveDominoToKingdom(Player player, int dominoId){
Kingdom kingdom = player.getKingdom();
DominoInKingdom dik = KingdomController.getDominoInKingdomByDominoId(dominoId, kingdom);
if(dik != null){
dik.setY(0);
dik.setX(0);
}
}
/**
* Feature 11: Move Current Domino
* As a player, I wish to evaluate a provisional placement of my current
* domino by moving the domino around into my kingdom (up, down, left, right).
* up 0, right 1, down 2, left 3
* @param player
* @param dominoId
* @param movement, expressed by int
* @author Violet Wei
* @return true if successful or false if fail
*/
public static boolean moveCurrentDomino(Player player, int dominoId, String movement) {
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
Kingdom kingdom;
if(game.getNumberOfPlayers() == 2 && (player.getColor() == PlayerColor.Green|| player.getColor() == PlayerColor.Pink)){
System.out.println("Player: "+player.getColor().toString()+"Index: "+ game.indexOfPlayer(player)+"Accepted move domino action");
kingdom = game.getPlayer(game.indexOfPlayer(player)-1).getKingdom();
if(kingdom != null){
System.out.println("Territories Size"+kingdom.getTerritories().size());
}
}else{
kingdom = player.getKingdom();
}
assert kingdom != null;
DominoInKingdom dik = KingdomController.getDominoInKingdomByDominoId(dominoId, kingdom);
int oldx =dik.getX();
int oldy = dik.getY();
int newx = -1; int newy = -1;
int mov = convertMovementStringToInt(movement);
Domino domino;
if(dik != null){
domino = player.getDominoSelection().getDomino();
switch(mov){
case -1:
newx=oldx;
newy=oldy;
break;
case 0:
newx = oldx;
newy = oldy + 1;
break;
case 1:
newx = oldx + 1;
newy = oldy;
break;
case 2:
newx = oldx;
newy = oldy - 1;
break;
case 3:
newx = oldx - 1;
newy = oldy;
break;
}
dik.setX(newx); dik.setY(newy);
Castle castle = KingdomController.getCastle(kingdom);
Square[] grid = GameController.getGrid(getStringFromPlayerColor(player));
System.out.println("Grid "+(grid[Square.convertPositionToInt(0,1)].getTerrain()==null?"Nothing":"Something here"));
if(domino.getStatus() == DominoStatus.InCurrentDraft || VerificationController.verifyGridSize(kingdom.getTerritories())) {
if (VerificationController.verifyNoOverlapping(castle, grid, dik) &&
(VerificationController.verifyNeighborAdjacency(castle, grid, dik) || VerificationController.verifyCastleAdjacency(castle, dik))){
domino.setStatus(DominoStatus.CorrectlyPreplaced);
System.out.println("Current domino status is Correctly Preplaced");
}else{
System.out.println("Current domino status is Erroneously Preplaced");
domino.setStatus(DominoStatus.ErroneouslyPreplaced);
}
}else{
dik.setX(oldx); dik.setY(oldy);
return false;
}
}
return true;
}
/**
* Feature 12: As a player, I wish to evaluate a provisional placement of my current domino in my kingdom
* by rotating it (clockwise or counter-clockwise).
* rotationDir 1 for clockwise, -1 for anticlockwise
* @author Cecilia Jiang
* @param castle, the castle
* @param grid, the square[] grid
* @param territories, territories under current player's control
* @param dominoInKingdom, currently selected domino
* @param rotationDir, rotation direction as String
*/
public static void rotateExistingDomino(Castle castle, Square[] grid, List<KingdomTerritory> territories,
DominoInKingdom dominoInKingdom, int rotationDir){
DominoInKingdom.DirectionKind oldDir = dominoInKingdom.getDirection();
DominoInKingdom.DirectionKind newDir = findDirAfterRotation(rotationDir,oldDir);
dominoInKingdom.setDirection(newDir);
if(VerificationController.verifyGridSize(territories) || dominoInKingdom.getDomino().getStatus() == DominoStatus.InCurrentDraft){
if(VerificationController.verifyNoOverlapping(castle,grid,dominoInKingdom) &&
(VerificationController.verifyCastleAdjacency(castle,dominoInKingdom) ||
VerificationController.verifyNeighborAdjacency(castle,grid,dominoInKingdom))) {
System.out.println("Successfully rotate domino");
dominoInKingdom.getDomino().setStatus(DominoStatus.CorrectlyPreplaced);
}else
dominoInKingdom.getDomino().setStatus(DominoStatus.ErroneouslyPreplaced);
} else{
dominoInKingdom.setDirection(oldDir);
}
}
/**
* Feature 13: As a player, I wish to place my selected domino to my kingdom. If I am satisfied with its placement,
* and its current position respects the adjacency rules, I wish to finalize the placement.
* (Actual checks of adjacency conditions are implemented as separate features)
* @param player, the current player
* @param id which is id of the domino to place
* @author: Cecilia Jiang
*/
public static void placeDomino(Player player, int id) throws java.lang.IllegalArgumentException{
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
DominoInKingdom dominoInKingdom=null;
Kingdom kingdom=null;
if(player==null) {
player=game.getNextPlayer();
}
if(id==0) {
kingdom = game.getNextPlayer().getKingdom();
dominoInKingdom=(DominoInKingdom) kingdom.getTerritory(kingdom.getTerritories().size()-1);
id=dominoInKingdom.getDomino().getId();
}
Domino domino = player.getDominoSelection().getDomino();
if(domino.getId() == id && domino.getStatus() == DominoStatus.CorrectlyPreplaced){
kingdom = game.getNextPlayer().getKingdom();
domino.setStatus(DominoStatus.PlacedInKingdom);
dominoInKingdom=(DominoInKingdom) kingdom.getTerritory(kingdom.getTerritories().size()-1);
String player0Name = getStringFromPlayerColor(game.getNextPlayer());
Square[] grid = GameController.getGrid(player0Name);
int[] pos = Square.splitPlacedDomino(dominoInKingdom, grid);
DisjointSet s = GameController.getSet(getStringFromPlayerColor(game.getNextPlayer()));
Castle castle = getCastle(kingdom);
if (grid[pos[0]].getTerrain() == grid[pos[1]].getTerrain())
s.union(pos[0], pos[1]);
GameController.unionCurrentSquare(pos[0],
VerificationController.getAdjacentSquareIndexesLeft(castle, grid, dominoInKingdom), s);
GameController.unionCurrentSquare(pos[1],
VerificationController.getAdjacentSquareIndexesRight(castle, grid, dominoInKingdom), s);
System.out.println("added the domino to the kingdom with id: "+id+" at position: "+dominoInKingdom.getX()+":"+dominoInKingdom.getY());
if(game.getNumberOfPlayers() == 2){
if(player0Name.equals("Blue")){
GameController.setGrid("Green",grid);
}else if(player0Name.equals("Green")){
GameController.setGrid("Blue",grid);
}else if(player0Name.equals("Pink")){
GameController.setGrid("Yellow",grid);
}else if(player0Name.equals("Yellow")){
GameController.setGrid("Pink",grid);
}
}
for(int i = 4; i >=-4; i-- ){
for(int j = -4 ; j <= 4; j++){
int cur = Square.convertPositionToInt(j,i);
char c = (grid[cur].getTerrain() == null) ?'/':printTerrain(grid[cur].getTerrain());
System.out.print(""+cur+""+c+" ");
}
System.out.println();
}
System.out.println("Disjoint Set");
System.out.println(GameController.getSet(player0Name).toString(grid));
} else{
throw new java.lang.IllegalArgumentException("The current domino placement does not respect the " +
"adjacency rules");
}
}
/**
* Feature 18 : Discard Domino
* Checks if a Domino can be placed in the player's kingdoms
* @author Mohamad Dimassi.
* @param dominoInKingdom that we want to see if it can be discarded.
* @return true if the domino can be placed correctly placed in the kingdom, false otherwise.
*/
public static boolean attemptDiscardSelectedDomino(DominoInKingdom dominoInKingdom) throws java.lang.IllegalArgumentException{
Game game = KingdominoApplication.getKingdomino().getCurrentGame();
Player currentPl = game.getPlayer(0);
Kingdom kingdom = currentPl.getKingdom();
if(dominoInKingdom==null) {
throw new java.lang.IllegalArgumentException("DominoInKingdom is not created");
}
Castle castle = getCastle(kingdom);
Square[] grid = GameController.getGrid(getStringFromPlayerColor(currentPl));
ArrayList<DominoInKingdom.DirectionKind> directions =new ArrayList<DominoInKingdom.DirectionKind>();
directions.add(DominoInKingdom.DirectionKind.Down);
directions.add(DominoInKingdom.DirectionKind.Left);
directions.add(DominoInKingdom.DirectionKind.Up);
directions.add(DominoInKingdom.DirectionKind.Right);
for(int x=-4;x<5;x++) {// brute force, try every combination of x,y,direction
for(int y=-4;y<5;y++) {
for(DominoInKingdom.DirectionKind dir :directions ) {
dominoInKingdom.setDirection(dir);
dominoInKingdom.setX(x);
dominoInKingdom.setY(y);
if((VerificationController.verifyGridSize(currentPl.getKingdom().getTerritories())) && (VerificationController.verifyNoOverlapping(castle,grid,dominoInKingdom)) && ((VerificationController.verifyCastleAdjacency(castle,dominoInKingdom)) || (VerificationController.verifyNeighborAdjacency(castle,grid,dominoInKingdom)))) {
//the above is the verification if the placement is possible
dominoInKingdom.getDomino().setStatus(DominoStatus.ErroneouslyPreplaced);
return true;
}
}
}
}
// if couldn't find a position to place the domino
dominoInKingdom.getDomino().setStatus(DominoStatus.Discarded);
return false;
}
///////////////////////////// //////
///// ///Helper Methods///// //////
/////////////////////////// //////
public static int convertMovementStringToInt(String movement){
int mov = -1;
if(movement==null) {
return -1;
}
if(movement.equals("up") || movement.equals("Up") ) {
mov = 0;
} else if(movement.equals("right") || movement.equals("Right") ) {
mov = 1;
}else if(movement.equals("down") || movement.equals("Down") ) {
mov = 2;
}if(movement.equals("left") || movement.equals("Left") ) {
mov = 3;
}
return mov;
}
private static String getStringFromPlayerColor(Player p){
String result = "";
switch(p.getColor()){
case Blue:
result = "Blue";
break;
case Green:
result = "Green";
break;
case Pink:
result = "Pink";
break;
case Yellow:
result = "Yellow";
break;
}
return result;
}
private static DominoInKingdom.DirectionKind findDirAfterRotation(int rotationDir, DominoInKingdom.DirectionKind oldDir){
DominoInKingdom.DirectionKind dir = DominoInKingdom.DirectionKind.Up;
switch(oldDir){
case Left:
if(rotationDir == 1){
dir = DominoInKingdom.DirectionKind.Up;
}else if(rotationDir == -1){
dir = DominoInKingdom.DirectionKind.Down;
}
break;
case Up:
if(rotationDir == 1){
dir = DominoInKingdom.DirectionKind.Right;
}else if(rotationDir == -1){
dir = DominoInKingdom.DirectionKind.Left;
}
break;
case Down:
if(rotationDir == 1){
dir = DominoInKingdom.DirectionKind.Left;
}else if(rotationDir == -1){
dir = DominoInKingdom.DirectionKind.Right;
}
break;
case Right:
if(rotationDir == 1){
dir = DominoInKingdom.DirectionKind.Down;
}else if(rotationDir == -1){
dir = DominoInKingdom.DirectionKind.Up;
}
break;
}
return dir;
}
private static char printTerrain(TerrainType terrainType){
char c;
switch(terrainType){
case WheatField:
c = 'W';
break;
case Mountain:
c = 'M';
break;
case Lake:
c = 'L';
break;
case Forest:
c = 'F';
break;
case Grass:
c = 'G';
break;
case Swamp:
c = 'S';
break;
default:
c = '/';
break;
}
return c;
}
private static Castle getCastle (Kingdom kingdom) {
for(KingdomTerritory territory: kingdom.getTerritories()){
if(territory instanceof Castle )
return (Castle)territory;
}
return null;
}
}
|
package work.binder.slave.ping;
import java.util.ArrayList;
import java.util.List;
public class SlaveContext {
private static boolean _occupied;
private static List<ProcessData> _processesData = new ArrayList<>();
private static boolean _canceled;
private static boolean _cleared;
public static List<ProcessData> getProcessesData() {
return _processesData;
}
public static boolean isCanceled() {
return _canceled;
}
public static boolean isCleared() {
return _cleared;
}
public static synchronized boolean isOccupied() {
return _occupied;
}
public static void setCanceled(boolean canceled) {
_canceled = canceled;
}
public static void setCleared(boolean cleared) {
_cleared = cleared;
}
public static synchronized void setOccupied(boolean occupied) {
_occupied = occupied;
}
public static void setProcessesData(List<ProcessData> processesData) {
_processesData = processesData;
}
}
|
package com.yea.core.util;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import com.yea.core.exception.YeaException;
public class HashUtil {
public static byte[] hash(String algorithmName, Object source, Object salt, int hashIterations) {
byte[] saltBytes = CodecSupport.toBytes(salt);
byte[] sourceBytes = CodecSupport.toBytes(source);
hashIterations = Math.max(1, hashIterations);
MessageDigest digest;
try {
digest = MessageDigest.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw new YeaException(e.getMessage(), e);
}
if (salt != null) {
digest.reset();
digest.update(saltBytes);
}
byte[] hashed = digest.digest(sourceBytes);
int iterations = hashIterations - 1; // already hashed once above
for (int i = 0; i < iterations; i++) {
digest.reset();
hashed = digest.digest(hashed);
}
return hashed;
}
/**
* 复制自shiro
* @author yiyongfei
*
*/
static class CodecSupport {
static final String PREFERRED_ENCODING = "UTF-8";
/**
* Converts the specified character array to a byte array using the Shiro's preferred encoding (UTF-8).
* <p/>
* This is a convenience method equivalent to calling the {@link #toBytes(String,String)} method with a
* a wrapping String and {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}, i.e.
* <p/>
* <code>toBytes( new String(chars), {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING} );</code>
*
* @param chars the character array to be converted to a byte array.
* @return the byte array of the UTF-8 encoded character array.
*/
static byte[] toBytes(char[] chars) {
return toBytes(new String(chars), PREFERRED_ENCODING);
}
/**
* Converts the specified source argument to a byte array with Shiro's
* {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.
*
* @param source the string to convert to a byte array.
* @return the bytes representing the specified string under the {@link CodecSupport#PREFERRED_ENCODING PREFERRED_ENCODING}.
* @see #toBytes(String, String)
*/
static byte[] toBytes(String source) {
return toBytes(source, PREFERRED_ENCODING);
}
/**
* Converts the specified source to a byte array via the specified encoding, throwing a
* {@link CodecException CodecException} if the encoding fails.
*
* @param source the source string to convert to a byte array.
* @param encoding the encoding to use to use.
* @return the byte array of the specified source with the given encoding.
* @throws CodecException if the JVM does not support the specified encoding.
*/
static byte[] toBytes(String source, String encoding) {
try {
return source.getBytes(encoding);
} catch (UnsupportedEncodingException e) {
String msg = "Unable to convert source [" + source + "] to byte array using " +
"encoding '" + encoding + "'";
throw new YeaException(msg, e);
}
}
/**
* Converts the specified Object into a byte array.
* <p/>
* If the argument is a {@code byte[]}, {@code char[]}, {@link ByteSource}, {@link String}, {@link File}, or
* {@link InputStream}, it will be converted automatically and returned.}
* <p/>
* If the argument is anything other than these types, it is passed to the
* {@link #objectToBytes(Object) objectToBytes} method which must be overridden by subclasses.
*
* @param o the Object to convert into a byte array
* @return a byte array representation of the Object argument.
*/
static byte[] toBytes(Object o) {
if (o == null) {
String msg = "Argument for byte conversion cannot be null.";
throw new IllegalArgumentException(msg);
}
if (o instanceof byte[]) {
return (byte[]) o;
} else if (o instanceof char[]) {
return toBytes((char[]) o);
} else if (o instanceof String) {
return toBytes((String) o);
} else {
String msg = "Argument for byte conversion cannot be "+o.getClass()+".";
throw new IllegalArgumentException(msg);
}
}
}
}
|
package search;
/**
* Generally utility class for this project.
*
* Created by mhotan_dev on 2/12/14.
*/
public class Util {
/**
* Checks if the array is sorted.
*
* @param array Array to check
* @param <T> The Comparable type of the array.
* @return Whether or not the array is sorted
*/
public static <T extends Comparable<? super T>> boolean isSorted(T[] array) {
if (array == null)
throw new IllegalArgumentException("Array cannot be null");
// Any empty or one element array is sorted.
if (array.length <= 1) return true;
// Make sure every element is equals to or less the latter element.
for (int i = 0; i < array.length - 1; ++i) {
// If we ever find a
if (array[i].compareTo(array[i +1 ]) > 1) {
return false;
}
}
return true;
}
}
|
package jp.co.softem.apps.core;
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Pagenator implements Serializable {
private static final long serialVersionUID = 1L;
private final int pageCount;
private final int total;
private final int currentPage;
private final String navigation;
private final String label;
public Pagenator(int total, int recordCount, int currentPage, int limit,
String basePath) {
if (limit < 1) {
throw new IllegalArgumentException(
"Please specify the number of pages is greater than 1.");
}
this.total = total;
BigDecimal b = new BigDecimal(total).divide(new BigDecimal(limit));
int count = b.setScale(0, RoundingMode.CEILING).intValue();
this.pageCount = (count < 1) ? 1 : count;
int page = (currentPage < 1) ? 1 : currentPage;
if (page > this.pageCount) {
this.currentPage = this.pageCount;
} else {
this.currentPage = page;
}
this.navigation = createNavigation(basePath);
int start = ((this.currentPage - 1) * limit + 1);
this.label =
total + "件中 " + start + " - " + (recordCount + start - 1) + "件";
}
public String createNavigation(String basePath) {
int start = (currentPage > 5) ? currentPage - 5 : 1;
StringBuffer sb = new StringBuffer("<ul class=\"navigation\">");
int count = 0;
for (int i = start; i < pageCount + 1; i++) {
String link =
"<a href=\"" + basePath + "index/" + i + "\">" + i + "</a>";
if (currentPage == i) {
link =
"<span class=\"active\">" + String.valueOf(i) + "</span>";
}
sb.append("<li>").append(link).append("</li>");
count++;
if (count >= 10) {
break;
}
}
sb.append("</ul>");
return String.valueOf(sb);
}
public int getPageCount() {
return pageCount;
}
public int getTotal() {
return total;
}
public int getCurrentPage() {
return currentPage;
}
public String getNavigation() {
return navigation;
}
public String getLabel() {
return label;
}
}
|
package com.edu.realestate.model;
import java.util.Arrays;
public class AdvertisementModel {
String username;
TransactionType transactionType;
String title;
RealEstateType realEstateType;
int cityId;
int price;
short area;
int landArea;
int rooms;
String floor;
String description;
byte[] picture;
boolean cellar;
boolean alarm;
boolean swimmingPool;
boolean elevator;
boolean intercom;
boolean balcony;
boolean terrace;
boolean garage;
boolean parking;
boolean digicode;
String energyLevel;
String gasLevel;
public AdvertisementModel(String username, TransactionType transactionType, String title, RealEstateType realEstateType,
int cityId, int price, short area, int landArea, int rooms, String floor, String description,
byte[] picture, boolean cellar, boolean alarm, boolean swimmingPool, boolean elevator, boolean intercom,
boolean balcony, boolean terrace, boolean garage, boolean parking, boolean digicode, String energyLevel,
String gasLevel) {
this.username = username;
this.transactionType = transactionType;
this.title = title;
this.realEstateType = realEstateType;
this.cityId = cityId;
this.price = price;
this.area = area;
this.landArea = landArea;
this.rooms = rooms;
this.floor = floor;
this.description = description;
this.picture = picture;
this.cellar = cellar;
this.alarm = alarm;
this.swimmingPool = swimmingPool;
this.elevator = elevator;
this.intercom = intercom;
this.balcony = balcony;
this.terrace = terrace;
this.garage = garage;
this.parking = parking;
this.digicode = digicode;
this.energyLevel = energyLevel;
this.gasLevel = gasLevel;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public TransactionType getTransactionType() {
return transactionType;
}
public void setTransactionType(TransactionType transactionType) {
this.transactionType = transactionType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public RealEstateType getRealEstateType() {
return realEstateType;
}
public void setRealEstateType(RealEstateType realEstate) {
this.realEstateType = realEstate;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public short getArea() {
return area;
}
public void setArea(short area) {
this.area = area;
}
public int getLandArea() {
return landArea;
}
public void setLandArea(int landArea) {
this.landArea = landArea;
}
public int getRooms() {
return rooms;
}
public void setRooms(int rooms) {
this.rooms = rooms;
}
public String getFloor() {
return floor;
}
public void setFloor(String floor) {
this.floor = floor;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getPicture() {
return picture;
}
public void setPicture(byte[] picture) {
this.picture = picture;
}
public boolean isCellar() {
return cellar;
}
public void setCellar(boolean cellar) {
this.cellar = cellar;
}
public boolean isAlarm() {
return alarm;
}
public void setAlarm(boolean alarm) {
this.alarm = alarm;
}
public boolean isSwimmingPool() {
return swimmingPool;
}
public void setSwimmingPool(boolean swimmingPool) {
this.swimmingPool = swimmingPool;
}
public boolean isElevator() {
return elevator;
}
public void setElevator(boolean elevator) {
this.elevator = elevator;
}
public boolean isIntercom() {
return intercom;
}
public void setIntercom(boolean intercom) {
this.intercom = intercom;
}
public boolean isBalcony() {
return balcony;
}
public void setBalcony(boolean balcony) {
this.balcony = balcony;
}
public boolean isTerrace() {
return terrace;
}
public void setTerrace(boolean terrace) {
this.terrace = terrace;
}
public boolean isGarage() {
return garage;
}
public void setGarage(boolean garage) {
this.garage = garage;
}
public boolean isParking() {
return parking;
}
public void setParking(boolean parking) {
this.parking = parking;
}
public boolean isDigicode() {
return digicode;
}
public void setDigicode(boolean digicode) {
this.digicode = digicode;
}
public String getEnergyLevel() {
return energyLevel;
}
public void setEnergyLevel(String energyLevel) {
this.energyLevel = energyLevel;
}
public String getGasLevel() {
return gasLevel;
}
public void setGasLevel(String gasLevel) {
this.gasLevel = gasLevel;
}
@Override
public String toString() {
return "AdvertisementModel [username=" + username + ", transactionType=" + transactionType + ", title=" + title
+ ", realEstate=" + realEstateType + ", cityId=" + cityId + ", price=" + price + ", area=" + area
+ ", landArea=" + landArea + ", rooms=" + rooms + ", floor=" + floor + ", description=" + description
+ ", picture=" + Arrays.toString(picture) + ", cellar=" + cellar + ", alarm=" + alarm
+ ", swimmingPool=" + swimmingPool + ", elevator=" + elevator + ", intercom=" + intercom + ", balcony="
+ balcony + ", terrace=" + terrace + ", garage=" + garage + ", parking=" + parking + ", digicode="
+ digicode + ", energyLevel=" + energyLevel + ", gasLevel=" + gasLevel + "]";
}
}
|
package com.chain;
/**
* @author yuanqinglong
* @since 2020/10/30 15:21
*/
public class ConsumeConfigInfo {
}
|
package com.grocery.codenicely.vegworld_new.checkout.model;
import com.grocery.codenicely.vegworld_new.checkout.OrderPlaceCallback;
/**
* Created by meghal on 7/11/16.
*/
public interface OrderPlaceHelper {
void requestPlaceOrder(String access_token, String house_no, String locality, String area, String city,
String delivery_slot, String coupon_code, boolean is_express_delivery, OrderPlaceCallback orderPlaceCallback);
}
|
package by.orion.onlinertasks.data.models.credentials;
import android.support.annotation.NonNull;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import by.orion.onlinertasks.BuildConfig;
public class AccessTokenRequestBody {
@SerializedName("username")
@Expose
@NonNull
private final String username;
@SerializedName("password")
@Expose
@NonNull
private final String password;
@SerializedName("client_id")
@Expose
@NonNull
private final String clientId = BuildConfig.CLIENT_ID;
@SerializedName("grant_type")
@Expose
@NonNull
private final String grantType = "password";
public AccessTokenRequestBody(@NonNull String username, @NonNull String password) {
this.username = username;
this.password = password;
}
@NonNull
public String getUsername() {
return username;
}
@NonNull
public String getPassword() {
return password;
}
@NonNull
public String getClientId() {
return clientId;
}
@NonNull
public String getGrantType() {
return grantType;
}
}
|
package com.davivienda.sara.tablas.ofimulti.session;
import com.davivienda.sara.base.BaseAdministracionTablas;
import com.davivienda.sara.entitys.Oficinamulti;
import com.davivienda.sara.tablas.ofimulti.servicio.OfimultiServicio;
import java.util.Collection;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* OficinamultiSessionBean - 01/06/2011
* Descripción :
* Versión : 1.0
*
* @author P-CCHAPA
*/
@Stateless
public class OfimultiSessionBean extends BaseAdministracionTablas<Oficinamulti> implements OfimultiSessionLocal {
@PersistenceContext
private EntityManager em;
private OfimultiServicio ofimultiservicio;
@PostConstruct
public void postConstructor() {
ofimultiservicio = new OfimultiServicio(em);
super.servicio = ofimultiservicio;
}
@SuppressWarnings("unchecked")
public Collection<Oficinamulti> getTodos(Integer pagina, Integer regsPorPagina) throws Exception {
return servicio.consultarPorQuery(pagina, regsPorPagina, "Oficinamulti.Todos");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.