text stringlengths 10 2.72M |
|---|
package com.wq.newcommunitygovern.di.component;
import dagger.BindsInstance;
import dagger.Component;
import com.jess.arms.di.component.AppComponent;
import com.wq.newcommunitygovern.di.module.SigninModule;
import com.wq.newcommunitygovern.mvp.contract.SigninContract;
import com.jess.arms.di.scope.ActivityScope;
import com.wq.newcommunitygovern.mvp.ui.activity.signin.SigninActivity;
/**
* ================================================
* Description:
* <p>
* Created by MVPArmsTemplate on 11/26/2020 15:52
* <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
* <a href="https://github.com/JessYanCoding">Follow me</a>
* <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
* <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
* <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
* ================================================
*/
@ActivityScope
@Component(modules = SigninModule.class, dependencies = AppComponent.class)
public interface SigninComponent {
void inject(SigninActivity activity);
@Component.Builder
interface Builder {
@BindsInstance
SigninComponent.Builder view(SigninContract.View view);
SigninComponent.Builder appComponent(AppComponent appComponent);
SigninComponent build();
}
} |
package extra;
/**
* Created by Angelina on 05.02.2017.
*/
public class TestRegex {
public static final String REGEX = "([-+]?[0-9]*\\.?[0-9]+[\\/\\+\\-\\*])+([-+]?[0-9]*\\.?[0-9]+)";
public static void main(final String[] args) throws Exception {
String[] ss = REGEX.split("/+");
for (String s : ss) {
System.out.println(s);
}
}
}
|
package viper.ui.watermark;
import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.gif4j.GifDecoder;
import com.gif4j.GifEncoder;
import com.gif4j.GifImage;
import com.gif4j.TextPainter;
import com.gif4j.Watermark;
import viper.db.SecureDatabaseConnector;
import viper.ui.file.FileServerConnector;
import viper.ui.main.StoredPreferences;
public class WatermarkController implements StoredPreferences
{
private WatermarkTableModel wtm;
//Holds the names of the file that are to be used for upload and download operations
private Object[][] storageList;
private String[] idList;
private final String LOCATION = "C:/Windows/Temp/";
private SecureDatabaseConnector sdc = new SecureDatabaseConnector();
private String userID;
public WatermarkController()
{
super();
wtm = new WatermarkTableModel();
userID = PREF.get(USERID, null);
}
public String getFileID(int index)
{
if(idList.length != 0)
{
return idList[index];
}
return null;
}
public String getFileName(int index)
{
return (String) storageList[index][0];
}
//Return new versions of the table model for general usage
public WatermarkTableModel getDefaultForStorage()
{
return new WatermarkTableModel();
}
public WatermarkTableModel getCustomForStorage()
{
//Returns default if custom is empty.
if(wtm == null)
{
return getDefaultForStorage();
}
return wtm;
}
public boolean loadStorageList()
{
boolean successful = true;
String sqlCommand = "SELECT *, COUNT(*) AS num " +
"FROM filerecord " +
"WHERE UserID = ? " +
"AND " +
"File_Type = ? " +
"AND " +
"Watermarked = ?";
String[] values = new String[]{userID, ".gif", "0"};
try
{
sdc.connectToDatabase();
sdc.setPreparedStatement(sqlCommand, values);
sdc.performReadAction();
sqlCommand = "SELECT * " +
"FROM filerecord " +
"WHERE UserID = ? " +
"AND " +
"File_Type = ? " +
"AND " +
"Watermarked = ?";
ResultSet rs = sdc.getResultSet();
int count;
if(rs.next())
{
count = rs.getInt("num");
}
else
{
count = 0;
}
int counter = 0;
if(count != 0)
{
sdc.setPreparedStatement(sqlCommand, values);
sdc.performReadAction();
rs = sdc.getResultSet();
rs.next();
storageList = new String[count][2];
idList = new String[count];
do
{
storageList[counter][0] = rs.getString("File_Name");
idList[counter] = rs.getString("File_ID");
counter++;
}
while(rs.next());
wtm = new WatermarkTableModel(storageList);
}
}
catch(SQLException e)
{
successful = false;
e.printStackTrace();
}
finally
{
try
{
sdc.closeConnection();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
return successful;
}
public boolean checkFiles(String fileName)
{
boolean exist = false;
String sqlCommand = "SELECT * " +
"FROM filerecord " +
"WHERE File_Name = ? " +
"AND " +
"UserID = ? " +
"AND " +
"File_Type = ? " +
"Watermarked = ?";
String[] values = {fileName, "2", ".gif", "1"};
try
{
sdc.connectToDatabase();
sdc.setPreparedStatement(sqlCommand, values);
sdc.performReadAction();
if(sdc.getResultSet().next())
{
exist = true;
}
}
catch(SQLException e)
{
exist = false;
e.printStackTrace();
}
finally
{
try
{
sdc.closeConnection();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
return exist;
}
public boolean watermarkedImg(String fileID, String fileName, String text){
boolean successful = false;
GifImage gifImage = null;
GifImage result = null;
File tempFile = null;
File file = null;
try {
successful = FileServerConnector.downloadFile(fileID, fileName, LOCATION);
String newName = checkName(fileName);
//input file path
tempFile = new File(LOCATION + "/" + fileName);
//output file path
file = new File(LOCATION + "/" + newName);
gifImage = GifDecoder.decode(tempFile);
//Watermark image file here
result = addTextWatermarkToGifImage(gifImage, text);
GifEncoder.encode(result, file);
successful = FileServerConnector.uploadFile(file);
if(successful)
{
setEntry(newName);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
file.delete();
tempFile.delete();
}
return successful;
}
private void setEntry(String fileName)
{
try
{
sdc.connectToDatabase();
String sqlStatement = "UPDATE FileRecord " +
"SET Watermarked = ? " +
"WHERE File_Name = ?";
String values[] = new String[]{"1", fileName};
sdc.setPreparedStatement(sqlStatement, values);
sdc.performWriteAction();
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
try
{
sdc.closeConnection();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
private String checkName(String fileName)
{
String sqlCommand = "SELECT * " +
"FROM FileRecord " +
"WHERE File_Name = ? " +
"AND " +
"UserID = ? " +
"ORDER BY File_Name DESC";
String[] values = new String[]{fileName + "_*", "2"};
int append = 2;
String temp = null;
try
{
sdc.connectToDatabase();
sdc.setPreparedStatement(sqlCommand, values);
sdc.performReadAction();
ResultSet rs = sdc.getResultSet();
if(rs.next())
{
rs.first();
temp = rs.getString("File_Name");
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
sdc.closeConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
char check = '.';
for(int i = fileName.length() - 1; i >= 0; i--)
{
if(check == fileName.charAt(i))
{
name = fileName.substring(0,i);
}
}
if(temp != null)
{
for(int i = temp.length() - 1; i >= 0; i--)
{
if(check == temp.charAt(i))
{
append = Integer.parseInt(temp.substring(i - 1,i));
append++;
}
}
}
name += "_";
name += append;
name += ".gif";
return name;
}
private GifImage addTextWatermarkToGifImage(GifImage gifImage, String text) {
//create new TextPainter
TextPainter tp = new TextPainter(new Font("Arial", Font.BOLD,15));
tp.setOutlinePaint(Color.LIGHT_GRAY);
//render the specified text outlined
BufferedImage renderedWatermarkText = tp.renderString(text, true);
//create new Watermark
Watermark watermark = new Watermark(renderedWatermarkText, Watermark.LAYOUT_MIDDLE_CENTER, 0.1f);
//apply watermark to the specified gif image and return the result
return watermark.apply(gifImage, true);
}
}
|
package 笔试题;
import java.util.*;
public class 作业帮二面 {
public static List<Integer> maxSub(int[] nums){
if(nums==null||nums.length==0)return Collections.emptyList();
ArrayList<Integer> res=new ArrayList<>();
ArrayList<Integer> temp;
int max=0,sum;
for (int i=0;i< nums.length;i++){
temp=new ArrayList<>();
sum=0;
for (int j=i;j<nums.length;j++){
sum+=nums[j];
temp.add(nums[j]);
if (sum>=max){
max=sum;
res=new ArrayList<>(new ArrayList<>(temp));
}
}
}
return res;
}
public static void main(String[] args) {
//Scanner in = new Scanner(System.in);
//int a = in.nextInt();
//System.out.println(a);
int[] nums={1,-2,3,10,-4,7,2,-5};
System.out.println(Arrays.toString(maxSub(nums).toArray()));
}
}
//import java.util.Scanner;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//
//public class Main {
// public static double f(String log){
// Pattern p= Pattern.compile("code=\\d\\d\\d");
// Matcher m=p.matcher(log);
// double need=0;
// double max=0;
// while (m.find()){
// String[] temp=m.group().split("=");
// if (temp[1].equals("200"))need++;
// max++;
// }
// return need/max;
// }
// public static void main(String[] args) {
// //Scanner in = new Scanner(System.in);
// //int a = in.nextInt();
// //System.out.println(a);
// System.out.println("Hello World!");
// }
//} |
package com.tencent.mm.plugin.appbrand.config;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
public final class WxaAttributes$d {
public int cbu;
public String foV;
public String fqu;
public int fsi;
public String fsj;
public int fsk;
public List<WxaAttributes$e> fsl;
public boolean fsm;
public String fsn;
public static WxaAttributes$d si(String str) {
if (bi.oW(str)) {
return null;
}
WxaAttributes$d wxaAttributes$d;
try {
JSONObject jSONObject = new JSONObject(str);
wxaAttributes$d = new WxaAttributes$d();
wxaAttributes$d.cbu = jSONObject.optInt("AppVersion", 0);
wxaAttributes$d.fsi = jSONObject.optInt("VersionState", -1);
wxaAttributes$d.fsj = jSONObject.optString("VersionMD5");
wxaAttributes$d.foV = jSONObject.optString("device_orientation");
wxaAttributes$d.fqu = jSONObject.optString("client_js_ext_info");
wxaAttributes$d.fsk = jSONObject.optInt("code_size");
JSONArray optJSONArray = jSONObject.optJSONArray("module_list");
if (optJSONArray != null && optJSONArray.length() > 0) {
wxaAttributes$d.fsl = new LinkedList();
for (int i = 0; i < optJSONArray.length(); i++) {
JSONObject optJSONObject = optJSONArray.optJSONObject(i);
if (optJSONObject != null) {
WxaAttributes$e wxaAttributes$e = new WxaAttributes$e();
wxaAttributes$e.bKg = optJSONObject.optString("md5");
wxaAttributes$e.name = optJSONObject.optString("name");
wxaAttributes$d.fsl.add(wxaAttributes$e);
}
}
}
wxaAttributes$d.fsm = jSONObject.optBoolean("UseModule", false);
wxaAttributes$d.fsn = jSONObject.optString("EntranceModule");
} catch (Exception e) {
wxaAttributes$d = null;
}
return wxaAttributes$d;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.p;
import android.content.Context;
import android.net.Uri;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import com.tencent.mm.plugin.appbrand.g;
import com.tencent.mm.plugin.appbrand.jsapi.p.c.b;
import com.tencent.mm.plugin.appbrand.jsapi.p.c.c;
import com.tencent.mm.plugin.appbrand.page.p;
import com.tencent.mm.plugin.appbrand.report.AppBrandStatObject;
import com.tencent.mm.plugin.appbrand.s.f;
import com.tencent.mm.plugin.appbrand.s.j;
import com.tencent.mm.pluginsdk.ui.tools.s;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.ui.base.MMFalseProgressBar;
import com.tencent.mm.ui.widget.MMWebView;
import com.tencent.xweb.o;
import org.json.JSONObject;
public final class a extends FrameLayout implements c {
private MMFalseProgressBar dEm;
private MMWebView dEn;
private p fFv;
private b gcD;
private final b gcE;
private String gcF = "";
private boolean gcG = true;
private boolean gcH = false;
private o gcI = new 2(this);
private com.tencent.xweb.x5.a.a.a.a.b gcJ = new 3(this);
private String mAppId;
public a(Context context, g gVar, p pVar) {
super(context);
this.mAppId = gVar.mAppId;
this.gcD = new b();
this.gcD.a(pVar);
this.fFv = pVar;
this.dEn = com.tencent.mm.plugin.webview.ui.tools.widget.f.a.qkE.cS(context);
this.dEn.getSettings().cIv();
this.dEn.getSettings().setJavaScriptEnabled(true);
this.dEn.getSettings().setMediaPlaybackRequiresUserGesture(false);
this.dEn.getSettings().cIx();
this.dEn.getSettings().setUserAgentString(s.aV(getContext(), this.dEn.getSettings().getUserAgentString()) + " miniProgram");
this.dEn.getView().setHorizontalScrollBarEnabled(false);
this.dEn.getView().setVerticalScrollBarEnabled(false);
this.dEn.getSettings().setBuiltInZoomControls(true);
this.dEn.getSettings().setUseWideViewPort(true);
this.dEn.getSettings().setLoadWithOverviewMode(true);
this.dEn.getSettings().cIq();
this.dEn.getSettings().cIp();
this.dEn.getSettings().setGeolocationEnabled(true);
this.dEn.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
this.dEn.getSettings().cIt();
this.dEn.getSettings().setAppCachePath(getContext().getDir("webviewcache", 0).getAbsolutePath());
this.dEn.getSettings().cIs();
this.dEn.getSettings().cIu();
this.dEn.getSettings().setDatabasePath(com.tencent.mm.loader.stub.b.duM + "databases/");
this.dEn.setCompetitorView(pVar.gnt);
this.dEn.cAy();
this.dEn.setWebViewCallbackClient(this.gcI);
if (this.dEn.getIsX5Kernel()) {
this.dEn.setWebViewClientExtension(this.gcJ);
}
addView(this.dEn, new LayoutParams(-1, -1));
this.dEm = new MMFalseProgressBar(context);
this.dEm.setProgressDrawable(com.tencent.mm.bp.a.f(context, f.mm_webview_progress_horizontal));
addView(this.dEm, new LayoutParams(-1, com.tencent.mm.bp.a.fromDPToPix(context, 3)));
this.gcE = ((com.tencent.mm.plugin.appbrand.jsapi.p.c.a) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.appbrand.jsapi.p.c.a.class)).a(this);
this.fFv.a(new 1(this));
getReporter().gsF = true;
}
public final String getAppId() {
return this.mAppId;
}
public final MMWebView getWebView() {
return this.dEn;
}
public final void runOnUiThread(Runnable runnable) {
post(runnable);
}
public final void w(JSONObject jSONObject) {
this.gcD.mData = jSONObject.toString();
this.gcD.ahM();
}
public final boolean akm() {
if (getWebView().canGoBack()) {
getReporter().b(this.fFv, true);
getWebView().goBack();
this.gcH = true;
return true;
}
getReporter().b(this.fFv, false);
return false;
}
public final void ud(String str) {
this.fFv.sZ(str);
}
public final void akn() {
akp();
this.dEm.start();
}
public final void ue(String str) {
akp();
this.dEm.finish();
if (!(this.gcG || this.gcH)) {
com.tencent.mm.plugin.appbrand.report.a.p reporter = getReporter();
p pVar = this.fFv;
String str2 = this.gcF;
reporter.grK = (String) reporter.gsD.peekFirst();
reporter.grL = 2;
reporter.grM = str;
reporter.gsD.push(str2);
reporter.k(pVar);
}
this.gcG = false;
this.gcH = false;
setCurrentURL(str);
}
public final void ako() {
this.fFv.fdO.fcz.agJ();
}
private void akp() {
this.dEn.evaluateJavascript("window.__wxjs_environment = \"miniprogram\";", null);
}
private com.tencent.mm.plugin.appbrand.report.a.p getReporter() {
return this.fFv.fdO.fcz.getReporter().gqY;
}
public final void setCurrentURL(String str) {
this.gcF = str;
if (!bi.oW(str)) {
if (!bi.oW(Uri.parse(str).getHost())) {
a(this.fFv, getContext().getString(j.webview_logo_url, new Object[]{r0}));
return;
}
}
a(this.fFv, "");
}
private void a(p pVar, String str) {
pVar.getContentView().post(new 4(this, pVar, str));
}
public final String[] getJsApiReportArgs() {
p pVar = this.fFv;
g gVar = pVar.fdO;
AppBrandStatObject appBrandStatObject = gVar.fcE;
com.tencent.mm.plugin.appbrand.j g = com.tencent.mm.plugin.appbrand.j.g(gVar);
a alS = pVar.alS();
String[] strArr = new String[19];
strArr[0] = appBrandStatObject.scene;
strArr[1] = appBrandStatObject.bGG;
strArr[2] = gVar.mAppId;
strArr[3] = gVar.fcu.frm.fii;
strArr[4] = g.fdE;
strArr[5] = (gVar.fcu.frm.fih + 1);
strArr[6] = appBrandStatObject.gqK;
strArr[7] = pVar.getURL();
strArr[8] = alS == null ? "" : alS.getWebView().getUrl();
strArr[9] = com.tencent.mm.plugin.appbrand.report.a.cH(pVar.mContext);
strArr[10] = "";
strArr[11] = "";
strArr[12] = "";
strArr[13] = "";
strArr[14] = "";
strArr[15] = "";
strArr[16] = appBrandStatObject.cbB;
strArr[17] = appBrandStatObject.cbC;
strArr[18] = (gVar.fct.bGM + 1000);
return strArr;
}
public final boolean akq() {
if (this.fFv.fdO.fcu.fqw) {
return this.fFv.fdO.fcu.fqO;
}
return this.fFv.fdO.fcu.fqL;
}
}
|
package net.sf.ardengine.rpg.multiplayer.messages;
import net.sf.ardengine.rpg.multiplayer.INetworkedNode;
/**
* Message sent by server when loading new level to joined clients
* to synchronize with changes, which occurred since game started.
*/
public class StateMessage extends JsonMessage {
/**Type of JSON message containing complete state info*/
public static final String TYPE = "node-state";
/**
* @param targetNode node, about which is state informs
* @param serverTime current game time
* @param currentStateIndex state, when changes occurred
*/
public StateMessage(INetworkedNode targetNode,
long serverTime, int currentStateIndex) {
super(TYPE, targetNode.getJSONState(), targetNode);
}
}
|
package Primitives;
public class Point2D {
Coordinate _x;
Coordinate _y;
//*************** Constractor ****************//
public Point2D() {
super();
this._x = new Coordinate();
this._y = new Coordinate();
}
public Point2D(Coordinate _x, Coordinate _y) {
super();
this._x = new Coordinate(_x);
this._y = new Coordinate(_y);
}
public Point2D(Point2D p) {
super();
this._x = new Coordinate(p._x);
this._y = new Coordinate(p._y);
}
//*************** Getters/Setters ****************//
public Coordinate get_x() {
return _x;
}
public Coordinate get_y() {
return _y;
}
public void set_x(Coordinate _x) {
this._x = _x;
}
public void set_y(Coordinate _y) {
this._y = _y;
}
//*************** Administration ****************//
@Override
public String toString() {
return "("+ _x + ", " + _y + ")";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Point2D other = (Point2D) obj;
if (_x == null) {
if (other._x != null)
return false;
} else if (!_x.equals(other._x))
return false;
if (_y == null) {
if (other._y != null)
return false;
} else if (!_y.equals(other._y))
return false;
return true;
}
}
|
package fall2018.csc2017.scoring;
import org.junit.Test;
import static org.junit.Assert.*;
public class ScoreTest {
private Score testScore;
private void makeScore() {
this.testScore = new Score("Username", 1000);
}
/**
* Tests the getValue() method.
*/
@Test
public void testGetValue() {
makeScore();
assertEquals(1000, testScore.getValue());
}
/**
* Tests the getUserName() method.
*/
@Test
public void testGetUsername() {
makeScore();
assertEquals("Username", testScore.getUsername());
}
/**
* Tests the setValue() method.
*/
@Test
public void testSetValue() {
makeScore();
testScore.setValue(200);
assertEquals(200, testScore.getValue());
}
/**
* Tests the equals() method with equal Scores.
*/
@Test
public void testEquals() {
makeScore();
Score compareScore = new Score("Username", 1000);
assertEquals(compareScore, testScore);
assertNotEquals(compareScore, "");
}
/**
* Tests the equals() method with unequal Scores.
*/
@Test
public void testNotEquals() {
makeScore();
Score compareScore = new Score("My Name", 1000);
assertNotEquals(compareScore, testScore);
}
/**
* Tests the equals() method with a different object.
*/
@Test
public void testEqualsDifferentType() {
makeScore();
String compare = "This isn't a Score";
assertNotEquals(compare, testScore);
}
/**
* Tests the toString() method.
*/
@Test
public void testToString() {
makeScore();
System.out.println(testScore.toString());
assertEquals("Username : 1000", testScore.toString());
}
} |
package mate.academy.internetshop.dao.jdbc;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import mate.academy.internetshop.dao.OrderDao;
import mate.academy.internetshop.exception.DataProcessingException;
import mate.academy.internetshop.lib.Dao;
import mate.academy.internetshop.model.Order;
import mate.academy.internetshop.model.Product;
import mate.academy.internetshop.model.User;
import mate.academy.internetshop.util.ConnectionUtil;
@Dao
public class OrderDaoJdbcImpl implements OrderDao {
@Override
public Order create(Order order) {
String query = "INSERT INTO orders (user_id) VALUES (?)";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query,
PreparedStatement.RETURN_GENERATED_KEYS);
statement.setLong(1, order.getUserId());
statement.executeUpdate();
ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
order.setOrderId(resultSet.getLong(1));
insertOrdersProducts(order);
return order;
} catch (SQLException e) {
throw new DataProcessingException(e);
}
}
@Override
public Optional<Order> get(Long id) {
String query = "SELECT * FROM orders WHERE order_id = ?";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, id);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
Order order = getOrderFromResultSet(resultSet);
return Optional.of(order);
}
} catch (SQLException e) {
throw new DataProcessingException(e);
}
return Optional.empty();
}
@Override
public List<Order> getAll() {
String query = "SELECT * FROM orders";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query);
ResultSet resultSet = statement.executeQuery();
List<Order> list = new ArrayList<>();
while (resultSet.next()) {
Order order = getOrderFromResultSet(resultSet);
list.add(order);
}
return list;
} catch (SQLException e) {
throw new DataProcessingException(e);
}
}
@Override
public Order update(Order order) {
String query = "UPDATE orders SET user_id = ?"
+ "WHERE order_id = ?";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, order.getUserId());
statement.setLong(2, order.getOrderId());
statement.executeUpdate();
deleteOrderProducts(order.getOrderId());
insertOrdersProducts(order);
return order;
} catch (SQLException e) {
throw new DataProcessingException(e);
}
}
@Override
public boolean delete(Long id) {
String query = "DELETE FROM orders WHERE order_id = ?";
try (Connection connection = ConnectionUtil.getConnection()) {
deleteOrderProducts(id);
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, id);
return statement.executeUpdate() != 0;
} catch (SQLException e) {
throw new DataProcessingException(e);
}
}
@Override
public List<Order> getUserOrders(User user) {
String query = "SELECT * FROM orders WHERE user_id= ?";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, user.getUserId());
ResultSet resultSet = statement.executeQuery();
List<Order> list = new ArrayList<>();
while (resultSet.next()) {
list.add(getOrderFromResultSet(resultSet));
}
return list;
} catch (SQLException e) {
throw new DataProcessingException(e);
}
}
private void insertOrdersProducts(Order order) throws SQLException {
String query = "INSERT INTO orders_products (order_id, product_id)"
+ " VALUES (?, ?)";
try (Connection connection = ConnectionUtil.getConnection()) {
for (Product product : order.getProducts()) {
PreparedStatement insertStatement =
connection.prepareStatement(query);
insertStatement.setLong(1, order.getOrderId());
insertStatement.setLong(2, product.getProductId());
insertStatement.executeUpdate();
}
}
}
private Order getOrderFromResultSet(ResultSet resultSet)
throws SQLException {
Long orderId = resultSet.getLong("order_id");
Long userId = resultSet.getLong("user_id");
Order order = new Order(orderId, getOrderProducts(orderId), userId);
return order;
}
private List<Product> getOrderProducts(Long orderId) throws SQLException {
String query = "SELECT products.* FROM orders_products "
+ "JOIN products USING (product_id) WHERE order_id = ?";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, orderId);
ResultSet resultSet = statement.executeQuery();
List<Product> list = new ArrayList<>();
while (resultSet.next()) {
Long id = resultSet.getLong("product_id");
String name = resultSet.getString("name");
BigDecimal price = resultSet.getBigDecimal("price");
Product product = new Product(id, name, price);
list.add(product);
}
return list;
}
}
private void deleteOrderProducts(Long orderId) throws SQLException {
String query = "DELETE FROM orders_products WHERE order_id = ?";
try (Connection connection = ConnectionUtil.getConnection()) {
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, orderId);
statement.executeUpdate();
}
}
}
|
package com.pangpang6.books.base.lambda;
import org.junit.Test;
import java.util.function.UnaryOperator;
/**
* Created by jiangjiguang on 2018/1/2.
*/
public class UnaryOperatorTest {
@Test
public void identityTest(){
UnaryOperator<String> i = (x)-> x.toUpperCase();
System.out.println(i.apply("test1234"));
}
}
|
package com.sunjian.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage extends BasePage {
public WebDriver driver;
public LoginPage(WebDriver driver){
super(driver, "LoginPage");
this.driver = driver;
}
protected String getURL(){
return getElementContents("url", "value");
}
protected WebElement getUsername(){
return getElement("username");
}
protected String getUsernameValue(){
return getElementContents("username","value");
}
protected WebElement getPassword(){
return getElement("password");
}
protected String getPasswordValue(){
return getElementContents("password","value");
}
protected WebElement getSubmit(){
return getElement("submit");
}
protected WebElement getTips_whenEmpty(){
return getElement("tips_whenEmpty");
}
protected WebElement getTips_whenFailed(){
return getElement("tips_whenFailed");
}
}
|
package com.tutorial.threads.test;
//public class Horse extends Thread {
//Horse extends Animal implements Runnable
public class Horse implements Runnable {
String name;
public Horse(String name) {
this.name = name;
}
public Horse() {
}
@Override
public void run() {
synchronized(this){
for(int i = 0 ; i < 5 ; i++) {
System.out.println("Horse is running from Thread >>> ["+i+"]"
+ " "+Thread.currentThread().getName());
}
}
}
} |
package com.ssm.po;
public class Orderdetail {
private int ordersId;
private int itemsId;
private int id;
private int itemsNum;
private Items items;
public Items getItems() {
return items;
}
public void setItems(Items items) {
this.items = items;
}
public int getOrdersId() {
return ordersId;
}
public void setOrdersId(int ordersId) {
this.ordersId = ordersId;
}
public int getItemsId() {
return itemsId;
}
public void setItemsId(int itemsId) {
this.itemsId = itemsId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getItemsNum() {
return itemsNum;
}
public void setItemsNum(int itemsNum) {
this.itemsNum = itemsNum;
}
}
|
package com.example.mobilebooks;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParsePush;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CompleteDetails extends Activity implements OnClickListener {
public static String searchIndex, searchISBN;
TextView heading, bookName, bookPrice, bookEdition, bookAuthor,
newAvailabel, usedAvailabel;
ImageView bookImage;
public URL url;
public Bitmap myBitmap;
Button buy, sell, rent;
private SharedPreferences prefs;
public static Context applicationContext;
public static String heading_, bookName_, bookAuthor_, bookPrice_,
bookEdition_, bookIsbn_;
public static int bookImageFlag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_complete_details);
searchIndex = getIntent().getStringExtra(BookLists.SEARCH);
heading = (TextView) findViewById(R.id.heading);
bookName = (TextView) findViewById(R.id.bookName);
bookAuthor = (TextView) findViewById(R.id.bookAuthor);
bookEdition = (TextView) findViewById(R.id.bookEdition);
bookPrice = (TextView) findViewById(R.id.bookPrice);
usedAvailabel = (TextView) findViewById(R.id.used_available);
newAvailabel = (TextView) findViewById(R.id.new_available);
bookImage= (ImageView) findViewById(R.id.bookImage);
buy = (Button) findViewById(R.id.buy);
sell = (Button) findViewById(R.id.sell);
rent = (Button) findViewById(R.id.rent);
applicationContext = getApplicationContext();
prefs = applicationContext.getSharedPreferences(
"com.example.mobilebooks", MODE_WORLD_WRITEABLE);
// all the variables bookname_ .... are defined in client.java
heading.setText(bookName_);
bookName.setText(bookName_);
bookAuthor.setText(bookAuthor_);
bookPrice.setText(bookPrice_);
prefs.edit().putString(Preferences.TITLE, bookName_).commit();
prefs.edit().putString(Preferences.AUTHOR, bookAuthor_).commit();
prefs.edit().putString(Preferences.PRICE, bookPrice_).commit();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
HttpURLConnection connection;
try {
url = new URL(BookLists.image[bookImageFlag]);
connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}catch(NullPointerException n){
}
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bookImage.setImageBitmap(myBitmap);
buy.setOnClickListener(this);
sell.setOnClickListener(this);
rent.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.complete_details, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent vendorsActivity;
vendorsActivity = new Intent(CompleteDetails.this, VendorsDetails.class);
switch (v.getId()) {
case R.id.buy:
Intent i = new Intent(CompleteDetails.this, AmazonActivity.class);
System.out.println("Push Sendt");
prefs.edit().putBoolean(Preferences.RENT, false).commit();
prefs.edit().putBoolean(Preferences.BUY, true).commit();
prefs.edit().putBoolean(Preferences.SELL, false).commit();
startActivity(i);
break;
case R.id.sell:
prefs.edit().putBoolean(Preferences.RENT, false).commit();
prefs.edit().putBoolean(Preferences.BUY, false).commit();
prefs.edit().putBoolean(Preferences.SELL, true).commit();
Intent sell = new Intent(CompleteDetails.this,
SellingActivity.class);
startActivity(sell);
break;
case R.id.rent:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
ParsePush push = new ParsePush();
push.setChannel(CompleteDetails.bookIsbn_);
push.clearExpiration();
push.setMessage("A New Buyer Is looking for The book You Posted on : \n Find your books");
push.sendInBackground();
}
});
t.start();
prefs.edit().putBoolean(Preferences.RENT, true).commit();
prefs.edit().putBoolean(Preferences.BUY, false).commit();
prefs.edit().putBoolean(Preferences.SELL, false).commit();
startActivity(vendorsActivity);
break;
}
}
}
|
package com.hnam.androiddagger.di.ChatComponent;
import com.hnam.androiddagger.chat.ChatActivity;
import com.hnam.androiddagger.chat.ChatScreenModule;
import com.hnam.androiddagger.main.MainScreenActivity;
import com.hnam.androiddagger.main.MainScreenModule;
import dagger.Module;
import dagger.android.ContributesAndroidInjector;
/**
* Created by nampham on 12/23/18.
*/
@Module
public abstract class ChatActivityBuilder {
@ContributesAndroidInjector(modules = ChatScreenModule.class)
abstract ChatActivity bindChatActivity();
} |
package at.ebinterface.validation.rtr.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SignatureInfoType complex type. <p/> <p>The following schema fragment specifies
* the expected content contained within this class. <p/>
* <pre>
* <complexType name="SignatureInfoType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="InputData" type="{http://reference.e-government.gv.at/namespace/verificationservice/20120922#}ContentExLocRefBaseType"
* minOccurs="0"/>
* <element name="SignerName" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="SignatureCheck" type="{http://reference.e-government.gv.at/namespace/verificationservice/20120922#}CheckResultType"
* minOccurs="0"/>
* <element name="CertificateCheck" type="{http://reference.e-government.gv.at/namespace/verificationservice/20120922#}CheckResultType"/>
* <element name="ManifestCheck" type="{http://reference.e-government.gv.at/namespace/verificationservice/20120922#}ManifestCheckType"
* minOccurs="0"/>
* <element name="Annotations" type="{http://reference.e-government.gv.at/namespace/verificationservice/20120922#}AnnotationsType"
* minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SignatureInfoType", namespace = "http://reference.e-government.gv.at/namespace/verificationservice/20120922#", propOrder = {
"inputData",
"signerName",
"signatureCheck",
"certificateCheck",
"manifestCheck",
"annotations"
})
public class SignatureInfoType {
@XmlElement(name = "InputData")
protected ContentExLocRefBaseType inputData;
@XmlElement(name = "SignerName", required = true)
protected String signerName;
@XmlElement(name = "SignatureCheck")
protected CheckResultType signatureCheck;
@XmlElement(name = "CertificateCheck", required = true)
protected CheckResultType certificateCheck;
@XmlElement(name = "ManifestCheck")
protected ManifestCheckType manifestCheck;
@XmlElement(name = "Annotations")
protected AnnotationsType annotations;
/**
* Gets the value of the inputData property.
*
* @return possible object is {@link ContentExLocRefBaseType }
*/
public ContentExLocRefBaseType getInputData() {
return inputData;
}
/**
* Sets the value of the inputData property.
*
* @param value allowed object is {@link ContentExLocRefBaseType }
*/
public void setInputData(ContentExLocRefBaseType value) {
this.inputData = value;
}
/**
* Gets the value of the signerName property.
*
* @return possible object is {@link String }
*/
public String getSignerName() {
return signerName;
}
/**
* Sets the value of the signerName property.
*
* @param value allowed object is {@link String }
*/
public void setSignerName(String value) {
this.signerName = value;
}
/**
* Gets the value of the signatureCheck property.
*
* @return possible object is {@link CheckResultType }
*/
public CheckResultType getSignatureCheck() {
return signatureCheck;
}
/**
* Sets the value of the signatureCheck property.
*
* @param value allowed object is {@link CheckResultType }
*/
public void setSignatureCheck(CheckResultType value) {
this.signatureCheck = value;
}
/**
* Gets the value of the certificateCheck property.
*
* @return possible object is {@link CheckResultType }
*/
public CheckResultType getCertificateCheck() {
return certificateCheck;
}
/**
* Sets the value of the certificateCheck property.
*
* @param value allowed object is {@link CheckResultType }
*/
public void setCertificateCheck(CheckResultType value) {
this.certificateCheck = value;
}
/**
* Gets the value of the manifestCheck property.
*
* @return possible object is {@link ManifestCheckType }
*/
public ManifestCheckType getManifestCheck() {
return manifestCheck;
}
/**
* Sets the value of the manifestCheck property.
*
* @param value allowed object is {@link ManifestCheckType }
*/
public void setManifestCheck(ManifestCheckType value) {
this.manifestCheck = value;
}
/**
* Gets the value of the annotations property.
*
* @return possible object is {@link AnnotationsType }
*/
public AnnotationsType getAnnotations() {
return annotations;
}
/**
* Sets the value of the annotations property.
*
* @param value allowed object is {@link AnnotationsType }
*/
public void setAnnotations(AnnotationsType value) {
this.annotations = value;
}
}
|
package com.raju.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.raju.dto.FascilityDto;
import com.raju.exceptions.ResourceNotFoundException;
import com.raju.models.Employee;
import com.raju.models.Fascilities;
import com.raju.repository.EmployeeRepository;
import com.raju.repository.FascilitiesRepository;
@RestController
@RequestMapping("/api/v1")
public class JPAcontroller {
@Autowired
private EmployeeRepository employeeRepository;
@Autowired private FascilitiesRepository fascilitiesRepository;
@GetMapping("/employees")
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
@GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
return ResponseEntity.ok().body(employee);
}
@PostMapping("/employees")
public Employee createEmployee(@Valid @RequestBody Employee employee) {
return employeeRepository.save(employee);
}
@GetMapping("/join/{id}")
public List<FascilityDto> getJoin(@PathVariable(value = "id") Long id){
List<Fascilities> intmresult = fascilitiesRepository.getJoin(id);
List<FascilityDto> result = new ArrayList<>();
for (Fascilities fascility : intmresult) {
result.add(new FascilityDto(fascility.getId(),fascility.getFascilityName(),fascility.getEmployeeId()));
}
return result;
}
@GetMapping("/joinOther/{id}")
public List<FascilityDto> getJoinOther(@PathVariable(value = "id") Long id){
List<Object []> intmresult = fascilitiesRepository.getJoinOther(id);
List<FascilityDto> result = new ArrayList<>();
for (int index = 0 ; index < intmresult.size() ; index++) {
Object[] item = (Object []) intmresult.get(index);
FascilityDto fascilityDto = new FascilityDto((Long) item[0],(String) item[1],(Long) item[2]);
result.add(fascilityDto);
}
return result;
}
@PostMapping("/fascilities")
public Fascilities createFascilities(@Valid @RequestBody Fascilities fascility) {
return fascilitiesRepository.save(fascility);
}
@PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(@PathVariable(value = "id") Long employeeId,
@Valid @RequestBody Employee employeeDetails) throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employee.setEmailId(employeeDetails.getEmailId());
employee.setLastName(employeeDetails.getLastName());
employee.setFirstName(employeeDetails.getFirstName());
final Employee updatedEmployee = employeeRepository.save(employee);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") Long employeeId)
throws ResourceNotFoundException {
Employee employee = employeeRepository.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id :: " + employeeId));
employeeRepository.delete(employee);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
|
package com.goldgov.portal.synUserScore.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.goldgov.dygl.module.partyorganization.service.PartyOrganizationQuery;
import com.goldgov.dygl.module.portal.webservice.olinfo.service.IShellInfoService;
import com.goldgov.gtiles.module.transactionscheduling.service.TransacationSchLogService;
import com.goldgov.gtiles.module.transactionscheduling.service.TransactionSchLog;
import com.goldgov.gtiles.module.transactionscheduling.service.TransactionSchLog.ExcType;
import com.goldgov.portal.synUserScore.dao.ISynUserScoreDao;
import com.goldgov.portal.synUserScore.service.OrgUserScoreBean;
import com.goldgov.portal.synUserScore.service.StatisticsUserLearnInfo;
import com.goldgov.portal.synUserScore.service.SumScoreBean;
import com.goldgov.portal.synUserScore.service.UserLearnInfo;
import com.goldgov.portal.synUserScore.service.UserScoreSynInfo;
@Service("synUserScoreServiceImpl")
public class SynUserScoreServiceImpl implements ISynUserScoreServiceImpl{
@Autowired
@Qualifier("synUserScoreDao")
private ISynUserScoreDao synUserScoreDao;
@Autowired
@Qualifier("OlShellInfoServiceImpl")
private IShellInfoService shellInfoService;
@Autowired
@Qualifier("TransacationSchLogService")
private TransacationSchLogService transacationSchLogService;
// 每天凌晨过5分执行
@Scheduled(cron="0 5 0 * * ? ")
public void sysUserScore() throws Exception{
String jobName="sysUserScore用户学习数据同步";
TransactionSchLog ts = transacationSchLogService.updateInfobyStatu(jobName, ExcType.HOUR, 24);
if(ts!=null){//乐观锁锁定调度成功
String errMsg=null;
try {
System.out.println("调度开始执行");
List<UserScoreSynInfo> userScoreList = synUserScoreDao.findUserScoreInfo();
Map<String,UserScoreSynInfo> userScoreMap = new HashMap<String, UserScoreSynInfo>();
if(userScoreList!=null && userScoreList.size()>0){
for(UserScoreSynInfo userInfo:userScoreList){
userScoreMap.put(userInfo.getLoginId(), userInfo);
}
}
//从接口中获取同步数据
List<UserScoreSynInfo> synUserScoreList = null;
synUserScoreList = shellInfoService.findUserScoreLengthList();
if(synUserScoreList!=null && synUserScoreList.size()>0){
if(userScoreMap!=null && userScoreMap.size()>0){
List<UserScoreSynInfo> prepareAddUserScoreList = new ArrayList<UserScoreSynInfo>();
for(UserScoreSynInfo user:synUserScoreList){
if(user.getScore()!=null && user.getAllScore()!=null){
if(user.getScore()>user.getAllScore()){
user.setScore(user.getAllScore());
}
}
if(user.getDzScore()!=null && user.getAllDzScore()!=null){
if(user.getDzScore()>user.getAllDzScore()){
user.setDzScore(user.getAllDzScore());
}
}
if(user.getXljhScore()!=null && user.getAllXljhScore()!=null){
if(user.getXljhScore()>user.getAllXljhScore()){
user.setXljhScore(user.getAllXljhScore());
}
}
UserScoreSynInfo userInfo = userScoreMap.get(user.getLoginId());
if(userInfo!=null){
//将库中已有的人员积分信息,与接口中传过来的人员积分信息进行对比 ,如果不同,则进行更新操作
if(compareValue(userInfo.getScore(),user.getScore()) //所得课程积分
&& compareValue(userInfo.getAllScore(),user.getAllScore()) //课程总积分
&& compareValue(userInfo.getPlayLength(),user.getPlayLength()) //学习时长 毫秒
&& compareValue(userInfo.getDzScore(),user.getDzScore()) //所得党章积分
&& compareValue(userInfo.getDzPlayLength(),user.getDzPlayLength()) //党章学习时长
&& compareValue(userInfo.getAllDzScore(),user.getAllDzScore()) //党章总积分
&& compareValue(userInfo.getXljhScore(),user.getXljhScore()) //所得系列讲话积分
&& compareValue(userInfo.getXljhPlayLength(),user.getXljhPlayLength()) //系列讲话学习时长
&& compareValue(userInfo.getAllXljhScore(),user.getAllXljhScore())){//系列讲话总积分
continue;
}else{//有字段变更 需更新
user.setLastUpdateTime(new Date());
synUserScoreDao.updateUserScoreInfo(user);
}
}else{//库中不存在该人员的积分信息 存入list中 批量添加
prepareAddUserScoreList.add(user);
}
}
if(prepareAddUserScoreList!=null && prepareAddUserScoreList.size()>0){
int forTimes = prepareAddUserScoreList.size()/100+1;
/*for(int i=0;i<forTimes;i++){
if(i<forTimes-1){
synUserScoreDao.batchAddUserScoreInfo(prepareAddUserScoreList.subList(i*100, (i+1)*100-1));
}else{
synUserScoreDao.batchAddUserScoreInfo(prepareAddUserScoreList.subList(i*100, prepareAddUserScoreList.size()-1));
}
}*/
for(UserScoreSynInfo info:prepareAddUserScoreList){
synUserScoreDao.addUserScoreInfo(info);
}
}
}else{//map为空 用户积分同步信息表无数据 添加
int forTimes = synUserScoreList.size()/100+1;
for(int i=0;i<forTimes;i++){
if(i<forTimes-1){
synUserScoreDao.batchAddUserScoreInfo(synUserScoreList.subList(i*100, (i+1)*100-1));
}else{
synUserScoreDao.batchAddUserScoreInfo(synUserScoreList.subList(i*100, synUserScoreList.size()-1));
}
}
//synUserScoreDao.batchAddUserScoreInfo(synUserScoreList);
}
//人员信息同步之后,将数据统计插入到org_study_ranking表中
String courseId[] = new String[]{"COURSETREE_01001_03,COURSETREE_01001_05","COURSETREE_01001_03","COURSETREE_01001_05"};
String courseType = "ALL,DZ,XLJH";
String[] courseTypes = courseType.split(",");
for(int i=0;i<courseTypes.length;i++){
List<OrgUserScoreBean> orgScoreList = synUserScoreDao.getOrgScoreList(courseId[i],courseTypes[i]);
List<OrgUserScoreBean> oldList = synUserScoreDao.getOrgRankingList(courseId[i]);
Map<String,OrgUserScoreBean> newMap = new HashMap<String, OrgUserScoreBean>();//存放已有的单位得分信息
for(OrgUserScoreBean bean:oldList){
newMap.put(bean.getDepId(), bean);
}
if(newMap!=null && newMap.size()>0){
List<OrgUserScoreBean> prepareAddList = new ArrayList<OrgUserScoreBean>();
for(OrgUserScoreBean bean:orgScoreList){
OrgUserScoreBean oldBean = newMap.get(bean.getDepId());
if(oldBean!=null){//已有单位的得分信息 对比 看是否需要修改
if(compareValue(bean.getTotalScore(),oldBean.getTotalScore())
&&compareValue(bean.getSingleScore(),oldBean.getSingleScore())
&&compareValue(bean.getLearnNum(),oldBean.getLearnNum())
&&compareValue(bean.getTreePath(),oldBean.getTreePath())
&&compareValue(bean.getParentId(),oldBean.getParentId())){
continue;
}else{//单位得分有变动 需修改
oldBean.setTotalScore(bean.getTotalScore());
oldBean.setSingleScore(bean.getSingleScore());
oldBean.setLearnNum(bean.getLearnNum());
oldBean.setTreePath(bean.getTreePath());
oldBean.setParentId(bean.getParentId());
synUserScoreDao.updateOrgRanking(oldBean);
/*System.out.println(oldBean.getDepName()+":"+oldBean.getCourseIds()+"-总分由"+oldBean.getTotalScore()+"改为"+bean.getTotalScore()
+"学习人数由"+oldBean.getLearnNum()+"改为"+bean.getLearnNum());*/
}
}else{//添加
prepareAddList.add(bean);
}
}
if(prepareAddList.size()>0){
int forTimes = prepareAddList.size()/100+1;
/*for(int j=0;j<forTimes;j++){
if(j<forTimes-1){
synUserScoreDao.batchAddOrgRanking(prepareAddList.subList(j*100, (j+1)*100-1));
}else{
synUserScoreDao.batchAddOrgRanking(prepareAddList.subList(j*100, prepareAddList.size()-1));
}
}*/
for(int j=0;j<prepareAddList.size();j++){
synUserScoreDao.addOrgRanking(prepareAddList.get(j));
}
}
}else{//org_study_ranking表数据为空 初始化
for(OrgUserScoreBean bean:orgScoreList){
synUserScoreDao.addOrgRanking(bean);
}
}
}
//org_study_ranking表中 党委和总支的total_credits 、fixed_credits两字段为空 更新
for(int i=0;i<courseId.length;i++){
List<SumScoreBean> beanList = synUserScoreDao.getSumScoreList(courseId[i]);//单位ID和对应的总分列表
synUserScoreDao.batchUpdateOrgScore(beanList,courseId[i]);//统一更新总分
synUserScoreDao.batchUpdateSingleMaxScore(courseId[i]);//统一更新单个分类总分
}
}else{
System.out.println("同步人员积分信息为空");
}
System.out.println("调度执行完毕");
} catch (Exception e) {
e.printStackTrace();
errMsg=jobName+e.getMessage();
}finally{
//保存结束时间 及异常信息
ts.setEndDate(new Date());
ts.setStatu(errMsg==null?TransactionSchLog.JOB_EXEC_END:TransactionSchLog.JOB_EXEC_ERR);//TransactionSchLog.JOB_EXEC_ERR
ts.setExceptionStack(errMsg);
transacationSchLogService.updateInfo(ts);
}
}
}
private boolean compareValue(Double val0,Double val1){
val0 = val0 == null ? 0 : val0;
val1 = val1 == null ? 0 : val1;
if(val0.doubleValue() == val1.doubleValue()){
return true;
}
return false;
}
private boolean compareValue(Integer val0,Integer val1){
val0 = val0 == null ? 0 : val0;
val1 = val1 == null ? 0 : val1;
if(val0.intValue() == val1.intValue()){
return true;
}
return false;
}
private boolean compareValue(String val0,String val1){
val0 = val0 == null ? "" : val0;
val1 = val1 == null ? "" : val1;
if(val0.equals(val1)){
return true;
}
return false;
}
private boolean compareValue(BigDecimal val0,BigDecimal val1){
val0 = (BigDecimal) (val0 == null ? new BigDecimal(0) : val0);
val1 = (BigDecimal) (val1 == null ? new BigDecimal(0) : val1);
if(val0.intValue() == val1.intValue()){
return true;
}
return false;
}
public List<StatisticsUserLearnInfo> findOrgPortalListByPage(PartyOrganizationQuery query){
return synUserScoreDao.findOrgPortalListByPage(query);
}
@Override
public List<StatisticsUserLearnInfo> findOrgLearnedList(
PartyOrganizationQuery query) {
return synUserScoreDao.findOrgLearnedList(query);
}
@Override
public List<UserLearnInfo> getUserLearnInfoList(PartyOrganizationQuery query) {
// TODO Auto-generated method stub
return synUserScoreDao.getUserLearnInfoList(query);
}
@Override
public List<Double> getSingleTotalScore(PartyOrganizationQuery query) {
// TODO Auto-generated method stub
return synUserScoreDao.getSingleTotalScore(query);
}
}
|
import java.awt.Color;
import java.awt.Dimension;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Program extends JFrame{
static panel2 right;
static panel1 left;
public static void main(String[] args) throws IOException, ClassNotFoundException{
//PANELS
left = new panel1();
panel3 top = new panel3();
right = new panel2();
//THREADS
QueueThread q = new QueueThread();
q.start();
MaintenanceThread m = new MaintenanceThread();
m.start();
EarningsThread e = new EarningsThread();
e.start();
//FRAME
JFrame screen = new JFrame();
JPanel bottom = new JPanel();
JPanel all = new JPanel();
//HOUSEKEEPINGS
top.setPreferredSize(new Dimension(1000,130));
bottom.setPreferredSize(new Dimension(1000,670));
all.setPreferredSize(new Dimension(1000, 800));
all.setBackground(Color.red);
bottom.setBackground(Color.red);
top.setBackground(Color.red);
left.setBackground(Color.yellow);
right.setBackground(Color.yellow);
bottom.add(left);
bottom.add(right);
all.add(top);
all.add(bottom);
screen.add(all);
screen.setSize(900, 600);
screen.setLocationRelativeTo(null);
screen.setVisible(true);
screen.setResizable(false);
screen.setDefaultCloseOperation(EXIT_ON_CLOSE);
//CONDITION TO CHECK IF GAME'S OVER
if(panel2.u.getCurrentCash() < 0){
System.out.println("GAME OVER!!!");
System.exit(0);
}
}
}
|
package com.mbc.minibanking;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JPasswordField;
import javax.swing.JPanel;
public class Staff {
private JFrame frame;
private JTextField txtStaff_ID;
private JTextField textField;
private JTextField txtPh_No;
private JTextField txtnrc_no;
private JTextField txtAdd;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Staff window = new Staff();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Staff() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setBackground(Color.LIGHT_GRAY);
frame.setBounds(100, 100, 450, 332);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 434, 33);
frame.getContentPane().add(panel);
JLabel lblStaff = new JLabel("Staff");
lblStaff.setForeground(Color.BLUE);
lblStaff.setFont(new Font("Zawgyi-One", Font.PLAIN, 15));
panel.add(lblStaff);
JLabel lblStaff_ID = new JLabel("Staff ID");
lblStaff_ID.setForeground(Color.BLUE);
lblStaff_ID.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
lblStaff_ID.setBounds(10, 56, 46, 14);
frame.getContentPane().add(lblStaff_ID);
txtStaff_ID = new JTextField();
txtStaff_ID.setBounds(143, 51, 148, 23);
frame.getContentPane().add(txtStaff_ID);
txtStaff_ID.setColumns(10);
JLabel lblStaff_Name = new JLabel("Staff Name");
lblStaff_Name.setForeground(Color.BLUE);
lblStaff_Name.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
lblStaff_Name.setBounds(10, 86, 83, 23);
frame.getContentPane().add(lblStaff_Name);
textField = new JTextField();
textField.setBounds(143, 85, 148, 23);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblStaff_Ph = new JLabel("Phone No");
lblStaff_Ph.setForeground(Color.BLUE);
lblStaff_Ph.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
lblStaff_Ph.setBounds(10, 158, 85, 14);
frame.getContentPane().add(lblStaff_Ph);
JLabel lblNRC_No = new JLabel("NRC No");
lblNRC_No.setForeground(Color.BLUE);
lblNRC_No.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
lblNRC_No.setBounds(10, 192, 71, 14);
frame.getContentPane().add(lblNRC_No);
JLabel lblStaff_Add = new JLabel("Address");
lblStaff_Add.setForeground(Color.BLUE);
lblStaff_Add.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
lblStaff_Add.setBounds(10, 224, 46, 14);
frame.getContentPane().add(lblStaff_Add);
txtPh_No = new JTextField();
txtPh_No.setBounds(143, 153, 148, 23);
frame.getContentPane().add(txtPh_No);
txtPh_No.setColumns(10);
txtnrc_no = new JTextField();
txtnrc_no.setBounds(143, 187, 148, 23);
frame.getContentPane().add(txtnrc_no);
txtnrc_no.setColumns(10);
txtAdd = new JTextField();
txtAdd.setBounds(143, 219, 148, 23);
frame.getContentPane().add(txtAdd);
txtAdd.setColumns(10);
JButton btnNewSave = new JButton("New");
btnNewSave.setForeground(Color.BLUE);
btnNewSave.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
btnNewSave.setBounds(33, 260, 85, 23);
frame.getContentPane().add(btnNewSave);
JButton btnEditDel = new JButton("Edit");
btnEditDel.setForeground(Color.BLUE);
btnEditDel.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
btnEditDel.setBounds(150, 260, 89, 23);
frame.getContentPane().add(btnEditDel);
JButton btnCloseCancel = new JButton("Close");
btnCloseCancel.setForeground(Color.BLUE);
btnCloseCancel.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
btnCloseCancel.setBounds(281, 260, 89, 23);
frame.getContentPane().add(btnCloseCancel);
JLabel lblLogin_ps = new JLabel("Login Password");
lblLogin_ps.setForeground(Color.BLUE);
lblLogin_ps.setFont(new Font("Zawgyi-One", Font.PLAIN, 12));
lblLogin_ps.setBounds(10, 120, 108, 23);
frame.getContentPane().add(lblLogin_ps);
passwordField = new JPasswordField();
passwordField.setBounds(143, 119, 148, 23);
frame.getContentPane().add(passwordField);
}
}
|
package com.elsevier.ews.jacksontest.model;
import java.util.Set;
public class IndexItem {
private String pii;
private Set<String> appIds;
public String getPii() {
return pii;
}
public void setPii(String pii) {
this.pii = pii;
}
public Set<String> getAppIds() {
return appIds;
}
public void setAppIds(Set<String> appIds) {
this.appIds = appIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("IndexItem [pii=");
builder.append(pii);
builder.append(", appIds=");
builder.append(appIds);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((appIds == null) ? 0 : appIds.hashCode());
result = prime * result + ((pii == null) ? 0 : pii.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;
IndexItem other = (IndexItem) obj;
if (appIds == null) {
if (other.appIds != null)
return false;
} else if (!appIds.equals(other.appIds))
return false;
if (pii == null) {
if (other.pii != null)
return false;
} else if (!pii.equals(other.pii))
return false;
return true;
}
}
|
package android.huyhuynh.orderapp.views;
import android.app.Dialog;
import android.content.DialogInterface;
import android.huyhuynh.orderapp.R;
import android.huyhuynh.orderapp.model.Menu;
import android.huyhuynh.orderapp.model.Order;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatDialogFragment;
import com.squareup.picasso.Picasso;
/**
* Created by Huy Huynh on 17-09-2019.
*/
public class FragmentOrderDialog extends AppCompatDialogFragment {
ImageButton imgBtnUp, imgBtnDown;
EditText edtSoluong;
TextView txtTenThucUongDialog,txtTongGiaDialog;
ImageView imgHinhAnhDialog;
int soluong = 1;
int positionfromlist = 0;
double tonggia=1;
DataOrderDialog mDataOrderDialog;
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//Khai báo view và ánh xạ
mDataOrderDialog = (DataOrderDialog) getActivity();
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.order_dialog,null);
imgBtnUp = view.findViewById(R.id.imgBtnUp);
imgBtnDown = view.findViewById(R.id.imgBtnDown);
edtSoluong = view.findViewById(R.id.edtSoluong);
txtTenThucUongDialog = view.findViewById(R.id.txtTenThucUongDialog);
txtTongGiaDialog = view.findViewById(R.id.txtTongGiaDialog);
imgHinhAnhDialog = view.findViewById(R.id.imgHinhAnhDialog);
//Gán button vào dialog
builder.setView(view);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
tonggia = FragmentListMenu.arrMenu.get(getPositionfromlist()).getDonGia()*soluong;
Menu menu = FragmentListMenu.arrMenu.get(getPositionfromlist());
Order order = new Order(MenuActivity.maBan,menu.getMaThucUong(),soluong,tonggia,"",true);
mDataOrderDialog.addToListOrder(order,menu);
mDataOrderDialog.getGia(tonggia);
}
});
builder.setNegativeButton("Huỷ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//Gán các giá trị
txtTenThucUongDialog.setText(FragmentListMenu.arrMenu.get(getPositionfromlist()).getTenThucUong());
txtTongGiaDialog.setText("Giá: "+FragmentListMenu.arrMenu.get(getPositionfromlist()).getDonGia()+"vnđ");
Picasso.get().load(FragmentListMenu.arrMenu.get(getPositionfromlist()).getHinhAnh()).into(imgHinhAnhDialog);
edtSoluong.setText("1");
imgBtnUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
soluong = Integer.parseInt(edtSoluong.getText().toString());
if (soluong<1){
tonggia = FragmentListMenu.arrMenu.get(getPositionfromlist()).getDonGia()*soluong;
txtTongGiaDialog.setText("Giá: "+tonggia+"vnđ");
edtSoluong.setText("1");
} else {
soluong = soluong + 1;
tonggia = FragmentListMenu.arrMenu.get(getPositionfromlist()).getDonGia()*soluong;
txtTongGiaDialog.setText("Giá: "+tonggia+"vnđ");
edtSoluong.setText(String.valueOf(soluong));
}
}
});
imgBtnDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
soluong = Integer.parseInt(edtSoluong.getText().toString());
if (soluong<2){
tonggia = FragmentListMenu.arrMenu.get(getPositionfromlist()).getDonGia()*soluong;
txtTongGiaDialog.setText("Giá: "+tonggia+"vnđ");
edtSoluong.setText("1");
} else {
soluong = soluong - 1;
tonggia = FragmentListMenu.arrMenu.get(getPositionfromlist()).getDonGia()*soluong;
txtTongGiaDialog.setText("Giá: "+tonggia+"vnđ");
edtSoluong.setText(String.valueOf(soluong));
}
}
});
return builder.create();
}
public int getPositionfromlist() {
return positionfromlist;
}
public void setPositionfromlist(int positionfromlist) {
this.positionfromlist = positionfromlist;
}
}
|
package com.example.iutassistant.Acitivities;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.iutassistant.R;
import com.google.firebase.database.FirebaseDatabase;
public class Message extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
}
}
|
/* 1: */ package com.kaldin.user.register.action;
/* 2: */
/* 3: */ import com.kaldin.user.register.dao.impl.AcademicInfoImplementor;
/* 4: */ import com.kaldin.user.register.dao.impl.ExperienceInfoImplementor;
/* 5: */ import com.kaldin.user.register.dao.impl.PersonalInfoImplementor;
/* 6: */ import com.kaldin.user.register.dao.impl.TechInfoImplementor;
/* 7: */ import java.io.PrintWriter;
/* 8: */ import java.util.List;
/* 9: */ import javax.servlet.http.HttpServletRequest;
/* 10: */ import javax.servlet.http.HttpServletResponse;
/* 11: */ import org.apache.struts.action.Action;
/* 12: */ import org.apache.struts.action.ActionForm;
/* 13: */ import org.apache.struts.action.ActionForward;
/* 14: */ import org.apache.struts.action.ActionMapping;
/* 15: */
/* 16: */ public class CallUserProfileAction
/* 17: */ extends Action
/* 18: */ {
/* 19: */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
/* 20: */ throws Exception
/* 21: */ {
/* 22:22 */ List<?> listObj = null;
/* 23: */
/* 24:24 */ String list = null;
/* 25:25 */ String alist = null;
/* 26:26 */ String result = "success";
/* 27:27 */ if ((request.getParameter("op") != null) &&
/* 28:28 */ (request.getParameter("op").equalsIgnoreCase("getRecord")))
/* 29: */ {
/* 30:29 */ int userid = Integer.parseInt(request.getParameter("userId"));
/* 31:30 */ AcademicInfoImplementor acImplementor = new AcademicInfoImplementor();
/* 32:31 */ PersonalInfoImplementor peImplementor = new PersonalInfoImplementor();
/* 33:32 */ ExperienceInfoImplementor exImplementor = new ExperienceInfoImplementor();
/* 34:33 */ TechInfoImplementor teImplementor = new TechInfoImplementor();
/* 35:34 */ listObj = peImplementor.getPersonalRecord(userid);
/* 36:35 */ if ((listObj != null) && (listObj.size() != 0)) {
/* 37:36 */ list = peImplementor.getJSONPList(listObj);
/* 38: */ }
/* 39:38 */ listObj = acImplementor.getAcademicRecord(userid);
/* 40:39 */ if ((listObj != null) && (listObj.size() != 0))
/* 41: */ {
/* 42:40 */ alist = acImplementor.getJSONAList(listObj);
/* 43:41 */ list = list + "$" + alist;
/* 44: */ }
/* 45: */ else
/* 46: */ {
/* 47:43 */ alist = acImplementor.getJSONAList();
/* 48:44 */ list = list + "$" + alist;
/* 49: */ }
/* 50:46 */ listObj = exImplementor.getExpRecord(userid);
/* 51:47 */ if ((listObj != null) && (listObj.size() != 0))
/* 52: */ {
/* 53:48 */ alist = exImplementor.getJSONEList(listObj);
/* 54:49 */ list = list + "$" + alist;
/* 55: */ }
/* 56: */ else
/* 57: */ {
/* 58:51 */ alist = exImplementor.getJSONEList();
/* 59:52 */ list = list + "$" + alist;
/* 60: */ }
/* 61:55 */ listObj = teImplementor.getTechRecord(userid);
/* 62:56 */ if ((listObj != null) && (listObj.size() != 0))
/* 63: */ {
/* 64:57 */ alist = teImplementor.getJSONTList(listObj);
/* 65:58 */ list = list + "$" + alist;
/* 66: */ }
/* 67: */ else
/* 68: */ {
/* 69:60 */ alist = teImplementor.getJSONTList();
/* 70:61 */ list = list + "$" + alist;
/* 71: */ }
/* 72:64 */ response.getWriter().print(list);
/* 73: */
/* 74:66 */ return null;
/* 75: */ }
/* 76:71 */ return mapping.findForward(result);
/* 77: */ }
/* 78: */ }
/* Location: C:\Java Work\Workspace\Kaldin\WebContent\WEB-INF\classes\com\kaldin\kaldin_java.zip
* Qualified Name: kaldin.user.register.action.CallUserProfileAction
* JD-Core Version: 0.7.0.1
*/ |
package com.javarush.task.task14.task1408;
/*
Куриная фабрика
*/
public class Solution {
public static void main(String[] args) {
Hen hen = HenFactory.getHen(Country.RUSSIA);
hen.getCountOfEggsPerMonth();
}
public interface Country {
String UKRAINE = "Ukraine";
String RUSSIA = "Russia";
String MOLDOVA = "Moldova";
String BELARUS = "Belarus";
}
public abstract class Hen {
public abstract int getCountOfEggsPerMonth();
public String getDescription() {
return "Я - курица.";
}
}
public class RussianHen extends Hen {
public int getCountOfEggsPerMonth() {
return 10;
}
public String getDescription() {
return super.getDescription() + " Моя страна - " + Country.RUSSIA + ". Я несу " + this.getCountOfEggsPerMonth() + " яиц в месяц.";
}
}
public class UkrainianHen extends Hen {
public int getCountOfEggsPerMonth() {
return 9;
}
public String getDescription() {
return super.getDescription() + " Моя страна - " + Country.UKRAINE + ". Я несу " + this.getCountOfEggsPerMonth() + " яиц в месяц.";
}
}
public class MoldovanHen extends Hen {
public int getCountOfEggsPerMonth() {
return 8;
}
public String getDescription() {
return super.getDescription() + " Моя страна - " + Country.MOLDOVA + ". Я несу " + this.getCountOfEggsPerMonth() + " яиц в месяц.";
}
}
public class BelarusianHen extends Hen {
public int getCountOfEggsPerMonth() {
return 7;
}
public String getDescription() {
return super.getDescription() + " Моя страна - " + Country.BELARUS + ". Я несу " + this.getCountOfEggsPerMonth() + " яиц в месяц.";
}
}
static class HenFactory {
static Hen getHen(String country) {
Hen hen = null;
if (country.equals("Russia"))
hen = new RussianHen();
else if (country.equals("Ukraine"))
hen = new UkrainianHen();
else if (country.equals("Moldova"))
hen = new MoldovanHen();
else if (country.equals("Belarus"))
hen = new BelarusianHen();
return hen;
}
}
}
|
import java.util.*;
public class e4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Introduzca primer número: ");
int num1 = sc.nextInt();
System.out.print("Introduzca segundo número: ");
int num2 = sc.nextInt();
System.out.print("Introduzca tercer número: ");
int num3 = sc.nextInt();
if (num1 > num2 && num1 > num3) {
System.out.println("Mayor: " + num1);
} else if (num2 > num1 && num2 > num3) {
System.out.println("Mayor: " + num2);
} else {
System.out.println("Mayor: " + num3);
}
}
}
|
/**
* Created by Gauseeban on 21.07.2020.
*/
public class Sirkel {
// Statisk metode som returnerer diameteren til en sirkel
public static double diameter(double radius){
double diameter = radius * 2;
return diameter;
}
// Statisk metode som beregner og returnerer sirkelens omkrets (omkrets = 2*pi*r)
public static double omkrets(double radius){
double omkrets = 2 * Math.PI * radius;
return omkrets;
}
// Statisk metode som beregner og returnerer sirkelens areal (areal = pi * r^2)
public static double areal(double radius){
double areal = Math.PI * Math.pow(radius, 2);
return areal;
}
}
|
package com.sinata.rwxchina.component_entertainment.adapter;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.widget.ImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.sinata.rwxchina.basiclib.HttpPath;
import com.sinata.rwxchina.basiclib.utils.imageUtils.ImageUtils;
import com.sinata.rwxchina.component_entertainment.R;
import com.sinata.rwxchina.component_entertainment.entity.NearScenicEntity;
import java.util.List;
/**
* @author:wj
* @datetime:2017/12/19
* @describe:景区列表适配器
* @modifyRecord:
*/
public class ScenicBodyAdapter extends BaseQuickAdapter<NearScenicEntity.BodyBean,BaseViewHolder> {
private Context mC;
public ScenicBodyAdapter(@LayoutRes int layoutResId, @Nullable List<NearScenicEntity.BodyBean> data,Context context) {
super(layoutResId, data);
this.mC = context;
}
@Override
protected void convert(BaseViewHolder helper, NearScenicEntity.BodyBean item) {
helper.setText(R.id.item_scenic_name,item.getGoods_name())
.setText(R.id.item_scenic_address,item.getGoods_address())
.setText(R.id.item_scenic_mile,item.getDistance() + "km");
ImageUtils.showImage(mC, HttpPath.IMAGEURL+item.getDefault_image(), (ImageView) helper.getView(R.id.item_scenic_image));
}
}
|
package com.tencent.mm.plugin.sns.ui;
import com.tencent.mm.sdk.platformtools.x;
class SnsStrangerCommentDetailUI$10 implements Runnable {
final /* synthetic */ SnsStrangerCommentDetailUI obC;
SnsStrangerCommentDetailUI$10(SnsStrangerCommentDetailUI snsStrangerCommentDetailUI) {
this.obC = snsStrangerCommentDetailUI;
}
public final void run() {
SnsStrangerCommentDetailUI.a(this.obC, SnsStrangerCommentDetailUI.a(this.obC).getBottom());
x.d("MicroMsg.SnsStrangerCommentDetailUI", "listOriginalBottom: " + SnsStrangerCommentDetailUI.g(this.obC));
}
}
|
package rain.test.study20201017;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* 353. 贪吃蛇
* 请你设计一个 贪吃蛇游戏,该游戏将会在一个 屏幕尺寸 = 宽度 x 高度 的屏幕上运行。如果你不熟悉这个游戏,可以 点击这里 在线试玩。
* <p>
* 起初时,蛇在左上角的 (0, 0) 位置,身体长度为 1 个单位。
* <p>
* 你将会被给出一个 (行, 列) 形式的食物位置序列。当蛇吃到食物时,身子的长度会增加 1 个单位,得分也会 +1。
* <p>
* 食物不会同时出现,会按列表的顺序逐一显示在屏幕上。比方讲,第一个食物被蛇吃掉后,第二个食物才会出现。
* <p>
* 当一个食物在屏幕上出现时,它被保证不能出现在被蛇身体占据的格子里。
* <p>
* 对于每个 move() 操作,你需要返回当前得分或 -1(表示蛇与自己身体或墙相撞,意味游戏结束)。
* <p>
* 示例:
* <p>
* 给定 width = 3, height = 2, 食物序列为 food = [[1,2],[0,1]]。
* <p>
* Snake snake = new Snake(width, height, food);
* <p>
* 初始时,蛇的位置在 (0,0) 且第一个食物在 (1,2)。
* <p>
* |S| | |
* | | |F|
* <p>
* snake.move("R"); -> 函数返回 0
* <p>
* | |S| |
* | | |F|
* <p>
* snake.move("D"); -> 函数返回 0
* <p>
* | | | |
* | |S|F|
* <p>
* snake.move("R"); -> 函数返回 1 (蛇吃掉了第一个食物,同时第二个食物出现在位置 (0,1))
* <p>
* | |F| |
* | |S|S|
* <p>
* snake.move("U"); -> 函数返回 1
* <p>
* | |F|S|
* | | |S|
* <p>
* snake.move("L"); -> 函数返回 2 (蛇吃掉了第二个食物)
* <p>
* | |S|S|
* | | |S|
* <p>
* snake.move("U"); -> 函数返回 -1 (蛇与边界相撞,游戏结束)
*/
public class SnakeGame {
int[][] food;
int width, height;
int i, j;
Deque<int[]> data;
boolean[][] flag;
private int foodIdx;
/**
* Initialize your data structure here.
*
* @param width - screen width
* @param height - screen height
* @param food - A list of food positions
* E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
*/
public SnakeGame(int width, int height, int[][] food) {
this.width = width;
this.height = height;
this.food = food;
foodIdx = 0;
i = 0;
j = 0;
data = new ArrayDeque<>();
//创建 数组表示坐标
data.push(new int[]{0, 0});
flag = new boolean[height][width];
flag[0][0] = true;
}
public static void main(String[] args) {
int[][] food = {{1, 2}, {0, 1}};
int width = 3, height = 2;
SnakeGame obj = new SnakeGame(width, height, food);
int param_1 = obj.move("R");
System.out.println(param_1);
int param_2 = obj.move("D");
System.out.println(param_2);
int param_3 = obj.move("R");
System.out.println(param_3);
int param_4 = obj.move("U");
int param_5 = obj.move("L");
int param_6 = obj.move("U");
System.out.println(param_4);
System.out.println(param_5);
System.out.println(param_6);
}
private boolean isValid(int i, int j) {
return i >= 0 && i < height && j >= 0 && j < width;
}
/**
* Moves the snake.
*
* @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
* @return The game's score after the move. Return -1 if game over.
* Game over when snake crosses the screen boundary or bites its body.
*/
public int move(String direction) {
int new_i = i, new_j = j;
if (direction.equals("U")) new_i--;
if (direction.equals("D")) new_i++;
if (direction.equals("L")) new_j--;
if (direction.equals("R")) new_j++;
//判断是否到边界
if (!isValid(new_i, new_j)) {
return -1;
}
int[] lastPos = data.getLast();
//判断 当flag 为true 说明已经在蛇队列中,并且不等于尾结点 则说明已经碰撞
if (flag[new_i][new_j] && (new_i != lastPos[0] || new_j != lastPos[1])) {
return -1;
}
data.addFirst(new int[]{new_i, new_j});
// 标记占用的格子 如果占用则为true 否则为false
flag[new_i][new_j] = true;
// 当前队列中添加数据
if (foodIdx < food.length && food[foodIdx][0] == new_i && food[foodIdx][1] == new_j) {
foodIdx++;
} else {
//否则移除
int[] tail = data.removeLast();
if (tail[0] != new_i || tail[1] != new_j)
flag[tail[0]][tail[1]] = false;
}
i = new_i;
j = new_j;
return data.size() - 1;
}
}
|
package br.usp.memoriavirtual.servicos.soap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;
import br.usp.memoriavirtual.modelo.entidades.Multimidia;
import br.usp.memoriavirtual.modelo.entidades.Usuario;
import br.usp.memoriavirtual.modelo.entidades.bempatrimonial.BemPatrimonial;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.RealizarBuscaSimplesRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.RealizarLoginRemote;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
@WebService(serviceName = "buscar")
public class RealizarBuscaSOAPService {
@Resource
WebServiceContext webServiceContext;
@EJB
private RealizarBuscaSimplesRemote realizarBuscaEJB;
@EJB
private RealizarLoginRemote realizarLoginEJB;
@WebMethod(operationName = "buscar")
public ArrayList<BemPatrimonial> buscar(@WebParam(name = "stringDeBusca") String stringDeBusca,@WebParam(name = "numeroDaPagina") int pagina) {
if(validaClient()){
ArrayList<BemPatrimonial> bensPatrimoniais = null;
try {
bensPatrimoniais = this.realizarBuscaEJB.buscar(stringDeBusca,pagina);
} catch (ModeloException e) {
e.printStackTrace();
}
return bensPatrimoniais;
}
return null;
}
@WebMethod(operationName = "buscarInstituicao")
public ArrayList<BemPatrimonial> buscaPorInstituicao(@WebParam(name = "stringDeBusca") String stringDeBusca,@WebParam(name = "numeroDaPagina") int pagina,
@WebParam(name = "tamanhoPagina") int tamanhoPagina,@WebParam(name = "nomeInstituicao") String nomeInstituicao) {
if(validaClient()){
ArrayList<BemPatrimonial> bensPatrimoniais = null;
try {
bensPatrimoniais = this.realizarBuscaEJB.buscarPorInstituicao(stringDeBusca,pagina,tamanhoPagina,nomeInstituicao);
} catch (ModeloException e) {
e.printStackTrace();
}
return bensPatrimoniais;
}
return null;
}
@WebMethod(operationName = "buscarMidias")
public List<Multimidia> getMidias(@WebParam(name = "idBemPatrimonial") String idBemPatrimonial) {
if(validaClient()){
List<Multimidia> midias = null;
midias = this.realizarBuscaEJB.getMidias(Long.parseLong(idBemPatrimonial));
return midias;
}
return null;
}
@SuppressWarnings("rawtypes")
private boolean validaClient(){
MessageContext mc = webServiceContext.getMessageContext();
Map http_headers = (Map) mc.get(MessageContext.HTTP_REQUEST_HEADERS);
String username = null;
String password = null;
List t = (List)http_headers.get("Authorization");
if(t == null || t.size() == 0) {
throw new RuntimeException("Auth failed");
}
String encodedText = ((String) t.get(0)).substring(5);
byte[] buf = null;
try {
buf = Base64.decode(encodedText.getBytes());
} catch (Base64DecodingException e) {
e.printStackTrace();
}
String credentials = new String(buf);
int p = credentials.indexOf(":");
if(p > -1){
username = credentials.substring(0,p);
password = credentials.substring(p+1);
} else {
throw new RuntimeException("Error in decoding");
}
return autentica(username, password);
}
public boolean autentica(String usuario,String senha){
boolean autenticado = false;
Usuario usuarioAutenticado = null;
try {
usuarioAutenticado = realizarLoginEJB.realizarLogin(usuario,senha);
} catch (ModeloException e) {
e.printStackTrace();
}
if (usuarioAutenticado != null) {
autenticado = true;
}
return autenticado;
}
}
|
package com.tt.miniapp.msg.video;
import android.app.Activity;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.text.TextUtils;
import com.storage.async.Action;
import com.storage.async.Observable;
import com.storage.async.Schedulers;
import com.tt.frontendapiinterface.b;
import com.tt.miniapp.permission.BrandPermissionUtils;
import com.tt.miniapp.permission.PermissionHelper;
import com.tt.miniapp.permission.PermissionsManager;
import com.tt.miniapp.permission.PermissionsResultAction;
import com.tt.miniapp.storage.filestorge.FileManager;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.MiniappHostBase;
import com.tt.miniapphost.host.HostDependManager;
import com.tt.miniapphost.permission.IPermissionsRequestCallback;
import com.tt.miniapphost.util.IOUtils;
import com.tt.option.e.e;
import com.tt.option.n.b;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ApiChooseVideoCtrl extends b {
public b.c callback = new b.c() {
public void onCancel() {
ApiChooseVideoCtrl.this.callbackCancel();
}
public void onFail(String param1String) {
ApiChooseVideoCtrl.this.callbackFail(param1String);
}
public void onSuccess(List<String> param1List) {
if (param1List != null && !param1List.isEmpty()) {
ApiChooseVideoCtrl.this.invokeCallBack(param1List.get(0));
return;
}
ApiChooseVideoCtrl.this.callbackCancel();
}
};
public boolean containsAlbum;
public boolean containsCamera;
public String mVideoPath;
public int maxDuration = 60;
public ApiChooseVideoCtrl(String paramString, int paramInt, e parame) {
super(paramString, paramInt, parame);
}
private void initArgs() throws JSONException {
JSONObject jSONObject = new JSONObject(this.mArgs);
ArrayList<String> arrayList = new ArrayList();
JSONArray jSONArray = jSONObject.optJSONArray("sourceType");
if (jSONArray != null) {
int j = jSONArray.length();
for (int i = 0; i < j; i++)
arrayList.add(jSONArray.getString(i));
}
this.containsCamera = arrayList.contains("camera");
this.containsAlbum = arrayList.contains("album");
this.maxDuration = jSONObject.optInt("maxDuration", 60);
if (this.maxDuration > 180)
this.maxDuration = 180;
if (this.maxDuration <= 0)
this.maxDuration = 60;
}
private void requestVideoCap(final Activity activity) {
final boolean hasRequestCameraPermission = BrandPermissionUtils.hasRequestPermission(14);
HashSet<BrandPermissionUtils.BrandPermission> hashSet = new HashSet();
hashSet.add(BrandPermissionUtils.BrandPermission.CAMERA);
BrandPermissionUtils.requestPermissions(activity, getActionName(), hashSet, new LinkedHashMap<Object, Object>(), new IPermissionsRequestCallback() {
public void onDenied(LinkedHashMap<Integer, String> param1LinkedHashMap) {
if (!hasRequestCameraPermission)
PermissionHelper.reportAuthFailResult("camera", "mp_reject");
ApiChooseVideoCtrl.this.unRegesterResultHandler();
ApiChooseVideoCtrl.this.callbackFail("auth deny");
}
public void onGranted(LinkedHashMap<Integer, String> param1LinkedHashMap) {
HashSet<String> hashSet = new HashSet();
hashSet.add("android.permission.CAMERA");
PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(activity, hashSet, new PermissionsResultAction() {
public void onDenied(String param2String) {
if (!hasRequestCameraPermission)
PermissionHelper.reportAuthFailResult("camera", "system_reject");
ApiChooseVideoCtrl.this.unRegesterResultHandler();
ApiChooseVideoCtrl.this.callbackFail("system auth deny");
}
public void onGranted() {
if (!hasRequestCameraPermission)
PermissionHelper.reportAuthSuccessResult("camera");
if (ApiChooseVideoCtrl.this.containsAlbum) {
ApiChooseVideoCtrl.this.requestAlbum(activity);
return;
}
HostDependManager.getInst().chooseVideo(activity, ApiChooseVideoCtrl.this.maxDuration, ApiChooseVideoCtrl.this.containsAlbum, ApiChooseVideoCtrl.this.containsCamera, ApiChooseVideoCtrl.this.callback);
}
});
}
}null);
}
public void act() {
MiniappHostBase miniappHostBase = AppbrandContext.getInst().getCurrentActivity();
if (miniappHostBase == null) {
callbackFail("activity is null");
return;
}
try {
initArgs();
if (this.containsCamera) {
requestVideoCap((Activity)miniappHostBase);
return;
}
if (this.containsAlbum) {
requestAlbum((Activity)miniappHostBase);
return;
}
this.containsAlbum = true;
this.containsCamera = true;
requestVideoCap((Activity)miniappHostBase);
return;
} catch (Exception exception) {
AppBrandLogger.e("tma_ApiChooseVideoCtrl", new Object[] { exception });
callbackFail(exception);
return;
}
}
public String getActionName() {
return "chooseVideo";
}
public String getFileType(String paramString) {
if (!TextUtils.isEmpty(paramString)) {
int i = paramString.lastIndexOf(".");
if (i > 0 && i < paramString.length())
return paramString.substring(i);
}
return "";
}
public void invokeCallBack(String paramString) {
boolean bool;
if (!TextUtils.isEmpty(paramString) && (new File(paramString)).exists()) {
bool = true;
} else {
bool = false;
}
this.mVideoPath = paramString;
if (!bool)
try {
callbackFail("cancel");
return;
} catch (Exception exception) {
AppBrandLogger.e("tma_ApiChooseVideoCtrl", new Object[] { exception });
callbackFail(exception);
return;
}
Observable.create(new Action() {
public void act() {
try {
boolean bool1;
boolean bool2;
JSONObject jSONObject = new JSONObject();
File file = FileManager.inst().getTempDir();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(System.currentTimeMillis());
stringBuilder.append(ApiChooseVideoCtrl.this.getFileType(ApiChooseVideoCtrl.this.mVideoPath));
file = new File(file, stringBuilder.toString());
IOUtils.copyFile(new File(ApiChooseVideoCtrl.this.mVideoPath), file, false);
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(ApiChooseVideoCtrl.this.mVideoPath);
String str = mediaMetadataRetriever.extractMetadata(9);
Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime();
if (bitmap != null) {
bool2 = bitmap.getWidth();
bool1 = bitmap.getHeight();
} else {
bool1 = false;
bool2 = false;
}
try {
long l = Long.parseLong(str) / 1000L;
if (l > ApiChooseVideoCtrl.this.maxDuration) {
ApiChooseVideoCtrl.this.callbackFail("over the maxDuration");
return;
}
jSONObject.put("duration", l);
} catch (NumberFormatException numberFormatException) {}
jSONObject.put("tempFilePath", FileManager.inst().getSchemaFilePath(file.getCanonicalPath()));
jSONObject.put("size", file.length());
jSONObject.put("width", bool2);
jSONObject.put("height", bool1);
ApiChooseVideoCtrl.this.callbackOk(jSONObject);
return;
} catch (Exception exception) {
AppBrandLogger.e("tma_ApiChooseVideoCtrl", new Object[] { exception });
ApiChooseVideoCtrl.this.callbackFail(exception);
return;
}
}
}).schudleOn(Schedulers.longIO()).subscribeSimple();
}
public void requestAlbum(final Activity activity) {
final boolean hasRequestAlbumPermission = BrandPermissionUtils.hasRequestPermission(17);
HashSet<BrandPermissionUtils.BrandPermission> hashSet = new HashSet();
hashSet.add(BrandPermissionUtils.BrandPermission.ALBUM);
BrandPermissionUtils.requestPermissions(activity, getActionName(), hashSet, new LinkedHashMap<Object, Object>(), new IPermissionsRequestCallback() {
public void onDenied(LinkedHashMap<Integer, String> param1LinkedHashMap) {
if (!hasRequestAlbumPermission)
PermissionHelper.reportAuthFailResult("photo", "mp_reject");
ApiChooseVideoCtrl.this.unRegesterResultHandler();
ApiChooseVideoCtrl.this.callbackFail("auth deny");
}
public void onGranted(LinkedHashMap<Integer, String> param1LinkedHashMap) {
HashSet<String> hashSet = new HashSet();
hashSet.add("android.permission.WRITE_EXTERNAL_STORAGE");
hashSet.add("android.permission.READ_EXTERNAL_STORAGE");
PermissionsManager.getInstance().requestPermissionsIfNecessaryForResult(activity, hashSet, new PermissionsResultAction() {
public void onDenied(String param2String) {
if (!hasRequestAlbumPermission)
PermissionHelper.reportAuthFailResult("photo", "system_reject");
ApiChooseVideoCtrl.this.unRegesterResultHandler();
ApiChooseVideoCtrl.this.callbackFail("system auth deny");
}
public void onGranted() {
if (!hasRequestAlbumPermission)
PermissionHelper.reportAuthSuccessResult("photo");
HostDependManager.getInst().chooseVideo(activity, ApiChooseVideoCtrl.this.maxDuration, ApiChooseVideoCtrl.this.containsAlbum, ApiChooseVideoCtrl.this.containsCamera, ApiChooseVideoCtrl.this.callback);
}
});
}
}null);
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\video\ApiChooseVideoCtrl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.wsg.protocl_7001;
public class Test {
}
|
package com.sinata.rwxchina.basiclib.payment.utils;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;
import com.google.gson.Gson;
import com.sinata.rwxchina.basiclib.base.BaseGoodsInfo;
import com.sinata.rwxchina.basiclib.entity.BaseShopInfo;
import com.sinata.rwxchina.basiclib.payment.entity.SinglePayment;
import com.sinata.rwxchina.basiclib.payment.ordinarypayment.PayMentActivity;
import com.sinata.rwxchina.basiclib.utils.retrofitutils.commonparametersutils.CommonParametersUtils;
import com.sinata.rwxchina.basiclib.utils.toastUtils.ToastUtils;
import com.sinata.rwxchina.basiclib.utils.userutils.UserUtils;
/**
* @author HRR
* @datetime 2017/12/28
* @describe 跳转到支付页面
* @modifyRecord
*/
public class StartPayMentUtils {
/**
* 跳转到支付页面,需携带店铺信息及商品信息
* @param context
* @param goodsInfo
* @param shopInfo
*/
public static void startPayment(Context context,BaseGoodsInfo goodsInfo,BaseShopInfo shopInfo){
if (!UserUtils.isLogin(context)){
return;
}
//设置不是自主买单
SinglePayment.getSinglePayment().setIs_youhui("0");
String shopinfo=new Gson().toJson(shopInfo);
String goodsinfo=new Gson().toJson(goodsInfo);
Intent toPayment=new Intent(context, PayMentActivity.class);
Bundle bundle=new Bundle();
bundle.putString("shopInfo",shopinfo);
bundle.putString("goodsInfo",goodsinfo);
toPayment.putExtras(bundle);
context.startActivity(toPayment);
}
/**
* 跳转到支付页面,需携带店铺信息及商品信息
* @param context
* @param goodsInfo
*/
public static void startPayment(Context context,BaseGoodsInfo goodsInfo){
//设置不是自主买单
SinglePayment.getSinglePayment().setPaytype("0");
String goodsinfo=new Gson().toJson(goodsInfo);
Intent toPayment=new Intent(context, PayMentActivity.class);
Bundle bundle=new Bundle();
bundle.putString("goodsInfo",goodsinfo);
toPayment.putExtras(bundle);
context.startActivity(toPayment);
}
/**
* 跳转到支付页面,需携带店铺信息
* 适用于自助买单
* @param context
* @param shopInfo
*/
public static void startPayment(Context context, BaseShopInfo shopInfo){
if (TextUtils.isEmpty(CommonParametersUtils.getUid(context))){
ToastUtils.showShort("请登录后继续操作");
Class cla= null;
try {
cla = Class.forName("com.sinata.rwxchina.component_login.activity.LoginPhoneActivity");
Intent login=new Intent(context,cla);
context.startActivity(login);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return;
}
//设置是自主买单
SinglePayment.getSinglePayment().setPaytype("1");
BaseGoodsInfo goodsInfo=new BaseGoodsInfo();
//自助买单goods_id为0,商品数量为1
goodsInfo.setGoods_id("0");
goodsInfo.setGoods_number("1");
goodsInfo.setShopid(shopInfo.getShopid());
String shopinfo=new Gson().toJson(shopInfo);
String goodsinfo=new Gson().toJson(goodsInfo);
Intent toPayment=new Intent(context,PayMentActivity.class);
Bundle bundle=new Bundle();
bundle.putString("shopInfo",shopinfo);
bundle.putString("goodsInfo",goodsinfo);
toPayment.putExtras(bundle);
context.startActivity(toPayment);
}
}
|
package com.hesoyam.pharmacy.pharmacy.mapper;
import com.hesoyam.pharmacy.pharmacy.dto.ShowOrderItemDTO;
import com.hesoyam.pharmacy.pharmacy.dto.ShowOrdersDTO;
import com.hesoyam.pharmacy.pharmacy.model.Order;
import com.hesoyam.pharmacy.pharmacy.model.OrderItem;
import java.util.List;
import java.util.stream.Collectors;
public class OrderMapper {
private OrderMapper() {
}
public static ShowOrdersDTO mapOrderToShowOrderDTO(Order order) {
return new ShowOrdersDTO(order.getId(), order.getDeadLine(), order.getPharmacy().getName(), mapOrderItemsToDTO(order.getOrderItems()));
}
private static List<ShowOrderItemDTO> mapOrderItemsToDTO(List<OrderItem> orderItems) {
return orderItems.stream().map(orderItem -> OrderItemMapper.mapOrderItemToShowOrderItemDTO(orderItem)).collect(Collectors.toList());
}
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.presenter.impl.security.model;
import seava.ad.domain.impl.security.Menu;
import seava.j4e.api.annotation.Ds;
import seava.j4e.api.annotation.DsField;
import seava.j4e.api.annotation.SortField;
import seava.j4e.presenter.impl.model.AbstractTypeLov_Ds;
@Ds(entity = Menu.class, sort = {@SortField(field = MenuRtLov_Ds.f_sequenceNo)})
public class MenuRtLov_Ds extends AbstractTypeLov_Ds<Menu> {
public static final String ALIAS = "ad_MenuRtLov_Ds";
public static final String f_sequenceNo = "sequenceNo";
public static final String f_title = "title";
public static final String f_tag = "tag";
@DsField
private Integer sequenceNo;
@DsField
private String title;
@DsField
private String tag;
public MenuRtLov_Ds() {
super();
}
public MenuRtLov_Ds(Menu e) {
super(e);
}
public Integer getSequenceNo() {
return this.sequenceNo;
}
public void setSequenceNo(Integer sequenceNo) {
this.sequenceNo = sequenceNo;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTag() {
return this.tag;
}
public void setTag(String tag) {
this.tag = tag;
}
}
|
package animatronics.client.gui.element;
import java.util.Arrays;
import org.lwjgl.opengl.GL11;
import animatronics.api.energy.ITEHasEntropy;
import animatronics.client.gui.GuiBase;
import animatronics.client.gui.GuiPatterns;
import animatronics.utils.event.EventHookContainer;
import animatronics.utils.misc.MiscUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.util.ResourceLocation;
public class ElementEntropyStorage extends GuiElement {
public ResourceLocation entropy = new ResourceLocation("animatronics", "textures/gui/elements/Capacitor.png");
public int x, y;
public ITEHasEntropy tile;
public ElementEntropyStorage(int i, int j, ITEHasEntropy t) {
x = i;
y = j;
tile = t;
}
@Override
public ResourceLocation getElementTexture() {
return entropy;
}
@Override
public void draw(int posX, int posY) {
this.drawTexturedModalRect(posX, posY, 0, 0, 18, 72);
int percentageScaled = MiscUtils.pixelatedTextureSize(tile.getEntropy(), tile.getMaxEntropy(), 72);
MiscUtils.drawTexture(posX+1, posY-1+(74-percentageScaled), EventHookContainer.entropy, 16, percentageScaled-2, 0);
int xx = GuiBase.mX - (GuiBase.gW-GuiBase.gXS)/2, yy = GuiBase.mY - (GuiBase.gH - GuiBase.gYS)/2;
if(xx >= x && xx <= x+18 && yy >= y && yy <= y+72){
GuiPatterns.drawToolTip(Arrays.asList(new String[]{"Entropy: " + tile.getEntropy() + "/" + tile.getMaxEntropy(), (tile.getEntropy()*100/tile.getMaxEntropy()) + "%"}), xx, yy);
}
}
@Override
public int getX() {
return x;
}
@Override
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
|
package dp;
import static org.junit.Assert.*;
import org.junit.Test;
public class PatternInGridTest {
@Test
public void isPatternInGrid() {
int[][] grid = new int[][] {
{1, 2, 3},
{3, 4, 5},
{5, 6, 7}
};
int[] inPattern = new int[]{1, 3, 4, 6};
int[] outPattern = new int[]{1, 2, 3, 4};
assertTrue("<1, 3, 4, 6> is in grid", PatternInGrid.isPatternInGrid(grid, inPattern));
assertFalse("<1, 2, 3, 4> is not in grid", PatternInGrid.isPatternInGrid(grid, outPattern));
}
} |
package tools;
import models.Entity;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;
public class EntityTool {
private DocumentBuilderFactory factory;
private DocumentBuilder builder;
private Document document;
private TransformerFactory transformerFactory;
private Transformer transformer;
private XMLInputFactory xmlInputFactory;
public EntityTool(boolean isRead) {
if (isRead) {
initReader();
}
else {
initSaver();
}
}
private void initReader() {
xmlInputFactory = XMLInputFactory.newInstance();
}
private void initSaver() {
try {
factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
document = builder.newDocument();
transformerFactory = TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (TransformerException ex) {
ex.printStackTrace();
}
}
public boolean saveEntityXML(final Entity entity, final String path) {
try {
Element rootElement = document.createElement("entity");
document.appendChild(rootElement);
Element nameElement = document.createElement("name");
nameElement.appendChild(document.createTextNode(entity.getName()));
rootElement.appendChild(nameElement);
Element textElement = document.createElement("text");
textElement.appendChild(document.createTextNode(entity.getValue()));
rootElement.appendChild(textElement);
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(new File(path + entity.getName() + ".xml"));
transformer.transform(source, result);
/*StreamResult result = new StreamResult(System.out);
transformer.transform(source, result);*/
} catch (TransformerException ex) {
ex.printStackTrace();
return false;
}
return true;
}
public Entity readEntityXML (File file) {
if (file.length() > 0) {
try {
XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new FileInputStream(file));
Entity entity = null;
int count = -1;
while (xmlEventReader.hasNext()) {
XMLEvent xmlEvent = xmlEventReader.nextEvent();
if (xmlEvent.isStartElement()) {
StartElement startElement = xmlEvent.asStartElement();
if (startElement.getName().getLocalPart().equals("name")) {
count = 0;
} else if (startElement.getName().getLocalPart().equals("text")) {
count = 1;
}
}
if (xmlEvent.isCharacters()) {
Characters chrctrs = xmlEvent.asCharacters();
if (count == 0) {
entity = new Entity(chrctrs.getData());
count = -1;
} else if (count == 1) {
entity.setValue(
AuthTool.getOpenText(chrctrs.getData()));
count = -1;
}
}
}
return entity;
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return null;
}
public List<Entity> loadEntities() {
PropertyTool propertyTool = new PropertyTool();
Set<Map.Entry<Object, Object>> set = propertyTool.getAllProperties();
Iterator<Map.Entry<Object, Object>> it = set.iterator();
List<Entity> result = new ArrayList<>();
while (it.hasNext()) {
Map.Entry<Object, Object> item = it.next();
if (!item.getKey().toString().equals("password")) {
Entity entity = readEntityXML(new File(item.getValue().toString()));
result.add(entity);
}
}
return result;
}
}
|
package com.bvan.javastart.lessons5_6.method;
/**
* @author bvanchuhov
*/
public class TrianglePrinterWithMethods {
public static void main(String[] args) {
printTriangle(5);
}
public static void printTriangle(int size) {
if (size < 0) {
throw new IllegalArgumentException("negative size: " + size);
}
for (int length = 1; length <= size; length++) {
printLine(length);
}
}
public static void printLine(int length) {
if (length < 0) {
throw new IllegalArgumentException("negative length: " + length);
}
for (int i = 1; i <= length; i++) {
System.out.print("*");
}
System.out.println();
}
}
|
package com.yqwl.controller;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yqwl.common.utils.Constants;
import com.yqwl.common.utils.FastJsonUtil;
import com.yqwl.pojo.Type;
import com.yqwl.pojo.User;
import com.yqwl.service.TypeService;
import net.sf.json.JSONArray;
@Controller
@RequestMapping("type")
@Scope("prototype")
public class TypeController {
@Resource
private TypeService typeService;
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* @Title: TZlistType
* @description 跳转类型列表页面
* @return String
* @author dujiawei
* @createDate 2019年6月6日
*/
@RequestMapping(value = "list", method = RequestMethod.GET, produces = Constants.HTML_PRODUCE_TYPE)
public String TZlistType() {
return "views/back/mouldSort/sort";
}
/**
* @Title: listType
* @description (后台)分页查询所有的类型
* @param @param page, limit
* @return String
*
* @author dujiawei
* @createDate 2019年6月6日
*/
@ResponseBody
@RequestMapping(value = "listType", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE)
public String listType(Integer page, Integer limit) {
int code = 0;
String msg = null;
try {
Map<String, Object> types = typeService.listType(page, limit);
if (types.size() != 0) {
code = 0;
msg = "查询成功";
return FastJsonUtil.getResponseJson(code, msg, types);
}
code = 1;
msg = "查询失败";
return FastJsonUtil.getResponseJson(code, msg, null);
} catch (Exception e) {
code = -1;
msg = "系统异常";
logger.error(e.getMessage(), e);
return FastJsonUtil.getResponseJson(code, msg, e);
}
}
/**
* @Title: add
* @description 跳转到新增类型页面
* @return String
* @author dujiawei
* @createDate 2019年6月6日
*/
@RequestMapping("/add")
public String TZsaveType() {
return "views/back/mouldSort/addSort";
}
/**
* @Title: saveType
* @description 增加一个类型
* @param @param type, session
* @return String
* @author dujiawei
* @throws Exception
* @createDate 2019年6月6日
*/
@ResponseBody
@RequestMapping(value = "saveType", method = RequestMethod.POST)
public String saveType(@RequestBody Type type, HttpSession session) throws Exception {
int code = 0;
String msg = null;
List<Type> allType = typeService.showAllType(); //查询所有的类型
if(allType.size() > 0) {
for(int i = 0; i < allType.size(); i++) {
if(allType.get(i).getTypeName().equals(type.getTypeName())){ //判断新增的类型是否已存在
code = 1;
msg = "该类型已存在,新增类型失败";
return FastJsonUtil.getResponseJson(code, msg, null);
}
}
}
try {
User admin = (User) session.getAttribute("login_user");
if (admin != null) {
int num = typeService.saveType(type);
if (num != 0) {
code = 0;
msg = "新增类型成功";
return FastJsonUtil.getResponseJson(code, msg, null);
}
code = 1;
msg = "该类型已存在,新增类型失败";
return FastJsonUtil.getResponseJson(code, msg, null);
} else {
code = 2;
msg = "您没有登录账号!";
return FastJsonUtil.getResponseJson(code, msg, null);
}
} catch (Exception e) {
code = -1;
msg = "系统异常";
logger.error(e.getMessage(), e);
return FastJsonUtil.getResponseJson(code, msg, e);
}
}
/**
* @Title: removeType
* @description (后台)删除一条类型
* @param @param id, session
* @return String
* @author dujiawei
* @createDate 2019年6月6日
*/
@ResponseBody
@RequestMapping(value = "removeType", method = RequestMethod.POST, produces = Constants.HTML_PRODUCE_TYPE)
public String removeType(BigInteger id, HttpSession session) {
int code = 0;
String msg = null;
try {
User admin = (User) session.getAttribute("login_user");
if (admin != null) {
int num = typeService.removeType(id);
if (num != 0) {
code = 0;
msg = "删除类型成功";
return FastJsonUtil.getResponseJson(code, msg, num);
}
code = 1;
msg = "删除类型失败";
return FastJsonUtil.getResponseJson(code, msg, null);
} else {
code = 2;
msg = "未登录";
return FastJsonUtil.getResponseJson(code, msg, null);
}
} catch (Exception e) {
code = -1;
msg = "系统异常";
logger.error(e.getMessage(), e);
return FastJsonUtil.getResponseJson(code, msg, e);
}
}
/**
* @Title: showAllType
* @description (前台)显示所有的类型
* @return Object
* @author dujiawei
* @throws Exception
* @createDate 2019年6月6日
*/
@ResponseBody
@RequestMapping(value = "showAllType", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
public Object showAllType() throws Exception {
List<Type> typeList = typeService.showAllType();
Map<String , Object> result = new HashMap<String , Object>();
result.put("code", 0);
result.put("msg", "Success");
JSONArray array = JSONArray.fromObject(typeList);
result.put("data", array);
return result;
}
}
|
package com.sergiienko.xrserver.parsers;
import com.sergiienko.xrserver.abstracts.RatesParser;
/**
* Parser for fixer.io data
*/
public class CDTStaticParser extends RatesParser {
/**
* Parse source data and store them in DB
* @throws Exception when failed
*/
public final void parse() throws Exception {
final String CURRENCY_NAME = "CDT";
persistRate(CURRENCY_NAME, 0.0);
}
}
|
package com.rednavis.application.rabbit.status;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
/**
* @author Alexander Sokolov
*/
public class TaskStatusManagerImpl implements TaskStatusManager{
private static final Logger logger = LogManager.getLogger(TaskStatusManagerImpl.class);
private boolean cancelTaskRequested;
private boolean timerElapsed;
private Thread timerThread;
public boolean isCancelTaskRequested(){
return cancelTaskRequested;
}
/**
* Marks current service task as cancel required and sets timeout for cancellation
*
* @param timeout time for service to cancel current task. When timeout will elapsed {@link
* TaskStatusManager} will throw an exception on next invocation of {@link
* TaskStatusManager#isHardCancelRequired }
*/
public boolean requestTaskCancel(Integer timeout) {
if (timeout != null && timeout > 0) {
timerThread = new Thread(() -> {
try {
Thread.sleep(timeout * 1000);
logger.info(
"Cancel timer of " + timeout + " seconds elapsed - current task will be canceled throw Exception.");
timerElapsed = true;
} catch (InterruptedException e) {
//stop timer, called cleanUp();
logger.info("TaskStatusManager cleaned up before Cancel timer elapsed.");
}
});
timerThread.start();
}
return cancelTaskRequested = true;
}
public void cleanUp(){
cancelTaskRequested = false;
timerElapsed = false;
if (timerThread != null)
timerThread.interrupt();
}
/**
* Checks rather timeout for cancellation is elapsed and throws {@link RuntimeException} if it is.
* @return 'false' if timer is not elapsed, otherwise throws {@link RuntimeException}
*/
public boolean isHardCancelRequired() {
if (timerElapsed) {
logger.info("Cancellation timed out. Forcing hard cancel.");
throw new RuntimeException("Service was force canceled due to timeout");}
return false;
}
/**
* Marks transaction for current service task as rollback
*/
public void rollbackTask() {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
cleanUp();
logger.info("Task stopped on user CANCEL request. Transaction marked as RollbackOnly.");
}
}
|
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class listiteratorset {
public static void main(String[] args) {
Set<Integer> lhss = new TreeSet<>();
lhss.add(77);
lhss.add(177);
lhss.add(277);
lhss.add(377);
lhss.add(477);
ArrayList<Integer> al = new ArrayList<>(lhss);
Iterator<Integer> i = al.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
|
package com.tencent.mm.plugin.game.gamewebview.b;
import com.tencent.mm.sdk.platformtools.bi;
import java.util.Map;
public final class b {
public static Map<String, a> jHU;
public static void a(a aVar) {
if (!bi.oW(aVar.getName())) {
jHU.put(aVar.getName(), aVar);
}
}
}
|
package combination;
public class DecodeMsg {
// https://www.youtube.com/watch?v=qli-JCrSwuk
// 121 -> 1 21 | 12 1 | 1 2 1
void combine(String result, int[] array, int index) {
if (index == array.length) {
System.out.println("result = " + result);
return;
}
for (int i = index; i < array.length; i++) {
combine(result + array[index], array, index + 1);
combine(result + " " + array[index], array, index + 1);
}
}
int count(int[] array, int index) {
if (index == array.length)
return 1;
if (index > array.length)
return 0;
return count(array, index + 1) + count(array, index + 2);
}
void display(StringBuilder builder, int[] array, int index) {
if (index == array.length) {
String[] split = builder.toString().split(" ");
boolean isValid = true;
for (String _s : split) {
if (Integer.valueOf(_s) > 26) {
isValid = false;
break;
}
}
if (isValid) {
System.out.println("builder = " + builder.toString());
}
return;
}
if (index > array.length)
return;
builder.append(array[index]);
display(builder, array, index + 1);
builder.deleteCharAt(builder.length() - 1);
if (builder.length() > 0) {
builder.append(" ");
builder.append(array[index]);
display(builder, array, index + 1);
builder.deleteCharAt(builder.length() - 1);
builder.deleteCharAt(builder.length() - 1);
}
}
public static void main(String[] args) {
int[] array = {1, 2, 1, 3};
// new DecodeMsg().combine("", array, 0);
new DecodeMsg().display(new StringBuilder(), array, 0);
// System.out.println("count = " + count);
}
}
|
/**
*
*/
package site.com.google.anywaywrite.util.swing;
import java.awt.Component;
import java.awt.Container;
import java.awt.Window;
/**
* @author y-kitajima
*
*/
public class BgGuiUtil {
public static Window getOwnerWindow(Component c) {
if (c == null) {
throw new IllegalArgumentException(
"parameter c should not be null, but was.");
}
if (c instanceof Window) {
return (Window) c;
}
Container parent = c.getParent();
while (parent != null) {
if (parent instanceof Window) {
break;
}
parent = parent.getParent();
}
return (Window) parent;
}
}
|
package enthu_l;
//What changes should be made so that the program will print 54321?
public class e_1464 {
int k = 5;
public boolean checkIt(int k){
return k-->0?true:false;}
public void printThem(){ while(checkIt(k)){
System.out.print(k);}}
public static void main(String[] args) { new e_1464().printThem();}
}
|
/**
*
*/
package mobi.wrt.oreader.app.clients.feedly.bo;
import android.os.Parcel;
import org.json.JSONException;
import org.json.JSONObject;
import by.istin.android.xcore.model.JSONModel;
public class AuthResponse extends JSONModel {
protected static final String REFRESH_TOKEN = "refresh_token";
private static final String ID = "id";
private static final String ACCESS_TOKEN = "access_token";
private static final String EXPIRES_IN = "expires_in";
private static final String STATE = "state";
private static final String TOKEN_TYPE = "token_type";
private static final String PLAN = "plan";
public String getId() {
return getString(ID);
}
public String getAccessToken() {
return getString(ACCESS_TOKEN);
}
public Long getExpiresIn() {
return getLong(EXPIRES_IN);
}
public String getState() {
return getString(STATE);
}
public String getTokenType() {
return getString(TOKEN_TYPE);
}
public String getRefreshToken() {
return getString(REFRESH_TOKEN);
}
public String getPlan() {
return getString(PLAN);
}
public AuthResponse() {
super();
}
public AuthResponse(JSONObject json) {
super(json);
}
public AuthResponse(Parcel source) {
super(source);
}
public AuthResponse(String json) throws JSONException {
super(json);
}
public static final Creator<AuthResponse> CREATOR = new Creator<AuthResponse>() {
public AuthResponse createFromParcel(Parcel in) {
return new AuthResponse(in);
}
public AuthResponse[] newArray(int size) {
return new AuthResponse[size];
}
};
public static ICreator<AuthResponse> MODEL_CREATOR = new ICreator<AuthResponse>() {
@Override
public AuthResponse create(JSONObject jsonObject) {
return new AuthResponse(jsonObject);
}
};
}
|
package hu.aensys.lambda.logic;
import java.io.IOException;
import java.net.URL;
import java.util.*;
public class DataLoader {
private final static String ADDRESS = "https://people.sc.fsu.edu/~jburkardt/data/csv/hw_25000.csv";
public static Collection<Data> downloadData(){
System.out.print("Downloading data\t");
try {
final List<Data> dataList = new ArrayList<>();
final URL url = new URL(ADDRESS);;
final Scanner s = new Scanner(url.openStream());
s.nextLine(); //skipp first line
while(s.hasNextLine()){
final String line = s.nextLine();
dataList.add(convert(line));
}
System.out.println("[OK]");
return Collections.unmodifiableCollection(dataList);
} catch (IOException e) {
System.out.println("[ERR]");
throw new RuntimeException("Couldn't download the file.",e);
}
}
private static Data convert(final String line){
final String[] split = line.split(",");
return new Data(
Integer.parseInt(split[0]),
Float.parseFloat(split[1]),
Float.parseFloat(split[2])
);
}
}
|
package barrelofmonkeys;
import java.util.List;
public interface SongFinderStrategy {
List<Song> playlist(SongLoader loader) throws NoNextSongException;
}
|
package com.conglomerate.dev.Exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
public class NoSuchGroupingException extends ResponseStatusException {
public NoSuchGroupingException(int groupingId) {
super(HttpStatus.BAD_REQUEST, "Grouping with code: \"" + groupingId + "\" does not exist.");
}
}
|
package net.liuzd.spring.boot.v2;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import net.liuzd.spring.boot.v2.customer.CustomerControllerTest;
import net.liuzd.spring.boot.v2.customer.CustomerRepositoryTest;
import net.liuzd.spring.boot.v2.customer.CustomerServiceTest;
@RunWith(Suite.class)
@SuiteClasses({
CustomerControllerTest.class,
CustomerRepositoryTest.class,
CustomerServiceTest.class,
})
public class StartTest {
}
|
package com.grability.test.dlmontano.grabilitytest.util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
/**
* Created by Diego Montano on 07/06/2016.
*/
public class Util {
private static String LOG_TAG = "Util";
public static String getZuluLocalDateStringRepresentation(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
return simpleDateFormat.format(date);
}
public static String getLocalDateStringRepresentation(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss zzz", Locale.getDefault());
simpleDateFormat.setTimeZone(TimeZone.getDefault());
return simpleDateFormat.format(date);
}
public static Date parseDateInZulu(String dateRepresentation) {
Date date;
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
date = simpleDateFormat.parse(dateRepresentation);
return date;
} catch (ParseException e) {
handleException(e, "Date parsing failed.", LOG_TAG + "->parseDateInZulu");
date = Calendar.getInstance().getTime();
}
return date;
}
public static boolean isDeviceOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
private static void handleException(Exception e, String msgHeader, String methodTag) {
StringBuilder msg = new StringBuilder(msgHeader);
if (e.getMessage() != null) {
msg.append(e.getMessage());
} else {
msg.append("No exception message.");
}
msg.append(" - ");
if (e.getLocalizedMessage() != null) {
msg.append(e.getMessage());
} else {
msg.append("No localized exception message.");
}
Log.e(methodTag, msg.toString());
e.printStackTrace();
}
}
|
package com.tencent.mm.plugin.appbrand.collector;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable.Creator;
class CollectSession$1 implements Creator<CollectSession> {
CollectSession$1() {
}
public final /* synthetic */ Object createFromParcel(Parcel parcel) {
CollectSession collectSession = new CollectSession();
collectSession.groupId = parcel.readString();
collectSession.id = parcel.readString();
collectSession.fnY = (TimePoint) parcel.readParcelable(CollectSession.class.getClassLoader());
collectSession.fob = parcel.readString();
Bundle readBundle = parcel.readBundle();
if (readBundle != null) {
collectSession.bQf.putAll(readBundle);
}
TimePoint timePoint = collectSession.fnY;
if (timePoint != null) {
collectSession.foa.put(timePoint.name, timePoint);
while (timePoint.fol.get() != null) {
timePoint = (TimePoint) timePoint.fol.get();
collectSession.foa.put(timePoint.name, timePoint);
}
collectSession.fnZ = timePoint;
}
return collectSession;
}
public final /* bridge */ /* synthetic */ Object[] newArray(int i) {
return new CollectSession[i];
}
}
|
package cn.xiahou.service;
import cn.xiahou.entity.JdItem;
import java.util.List;
public interface JdItemService {
/**
* 保存商品
* @param item
*/
public void save (JdItem item);
/**
* 查询商品
* @param item
* @return
*/
public List<JdItem> find(JdItem item);
}
|
package dbConnection;
import com.sun.rowset.JdbcRowSetImpl;
import org.apache.commons.dbutils.DbUtils;
import utils.Log;
import utils.Property;
import javax.sql.RowSet;
import javax.sql.rowset.JdbcRowSet;
import java.sql.*;
public class JDBCConnection {
private static PreparedStatement preparedStatement;
private static Statement statement;
private static Connection connection;
private static ResultSet resultSet;
private static JdbcRowSet rowSet;
public static Connection connectToDb() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(Property.getProperty("url"),
Property.getProperty("userName"), Property.getProperty("password"));
} catch (ClassNotFoundException e) {
Log.error("Driver not found");
Log.error(e.getMessage());
} catch (SQLException e) {
Log.error("DB connection failed");
Log.error(e.getMessage());
}
return connection;
}
public static void closeConnection() {
DbUtils.closeQuietly(connection, statement, resultSet);
DbUtils.closeQuietly(preparedStatement);
DbUtils.closeQuietly(rowSet);
}
public static void createInstance(String query, String message) throws SQLException {
statement = connectToDb().prepareStatement(query);
Log.info(String.format("Following request sent: *** %s ***", query));
statement.executeUpdate(query);
Log.info(message);
}
public static void changeInstance(String query, String message) throws SQLException {
statement = connectToDb().createStatement();
Log.info(String.format("Following request sent: *** %s ***", query));
statement.executeUpdate(query);
Log.info(message);
}
public static void createTable(String query) {
try {
createInstance(query, "Table successfully created");
} catch (SQLException e) {
Log.error("Table creation failed");
Log.error(e.getMessage());
}
}
public static void createView(String query) {
try {
createInstance(query, "View successfully created");
} catch (SQLException e) {
Log.error("View creation failed");
Log.error(e.getMessage());
}
}
public static ResultSet selectDataFromDB(String query) {
try {
statement = connectToDb().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
Log.info(String.format("Following request sent: *** %s ***", query));
resultSet = statement.executeQuery(query);
Log.info("Data from db retrieved");
} catch (SQLException e) {
Log.error(e.getMessage());
}
return resultSet;
}
public static RowSet selectDataUsingRowSet(String query) {
try {
rowSet = new JdbcRowSetImpl(connectToDb());
rowSet.setCommand(query);
Log.info(String.format("Following request sent: *** %s ***", query));
rowSet.execute();
} catch (SQLException e) {
Log.error(e.getMessage());
}
return rowSet;
}
public static ResultSet selectPreparedDataFromDB(String query) {
try {
preparedStatement = connectToDb().prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
preparedStatement.setString(1, Property.getProperty("userId"));
Log.info(String.format("Following request sent: *** %s ***", query));
resultSet = preparedStatement.executeQuery();
Log.info("Data from db retrieved");
} catch (SQLException e) {
Log.error(e.getMessage());
}
return resultSet;
}
public static void insertDataToDB(String query) {
try {
changeInstance(query, "Data successfully added");
} catch (SQLException e) {
Log.error("Error during data insert occurs");
Log.error(e.getMessage());
}
}
public static void updateDataInsideDB(String query) {
try {
changeInstance(query, "Data successfully updated");
} catch (SQLException e) {
Log.error("Error during data update occurs");
Log.error(e.getMessage());
}
}
public static void deleteDataFromDb(String query) {
try {
changeInstance(query, "Data successfully deleted");
} catch (SQLException e) {
Log.error("Error during data deleting occurs");
Log.error(e.getMessage());
}
}
public static void deleteTableFromDb(String query) {
try {
changeInstance(query, "Table successfully deleted");
} catch (SQLException e) {
Log.error("Error during table deleting occurs");
Log.error(e.getMessage());
}
}
public static void deleteViewFromDb(String query) {
try {
changeInstance(query, "View successfully deleted");
} catch (SQLException e) {
Log.error("Error during view deleting occurs");
Log.error(e.getMessage());
}
}
}
|
package com.tencent.mm.plugin.pwdgroup.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.model.au;
import com.tencent.mm.modelgeo.a.a;
import com.tencent.mm.modelgeo.c;
import com.tencent.mm.plugin.pwdgroup.ui.widget.MMCallBackScrollView;
import com.tencent.mm.plugin.pwdgroup.ui.widget.MMKeyBoardView;
import com.tencent.mm.plugin.pwdgroup.ui.widget.MMPwdInputView;
import com.tencent.mm.pluginsdk.model.lbs.Location;
import com.tencent.mm.protocal.c.vt;
import com.tencent.mm.sdk.platformtools.ag;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.al;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.h;
import com.tencent.mm.ui.widget.MMScrollGridView;
import java.util.HashMap;
import java.util.LinkedList;
public class FacingCreateChatRoomAllInOneUI extends MMActivity implements e {
private a cXs = new a() {
public final boolean a(boolean z, float f, float f2, int i, double d, double d2, double d3) {
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "lat:%f lng:%f accuracy:%f", new Object[]{Float.valueOf(f2), Float.valueOf(f), Double.valueOf(d2)});
if (z) {
Location location = new Location(f2, f, (int) d2, i, "", "");
if (!location.ccc()) {
FacingCreateChatRoomAllInOneUI.this.lZB = location;
FacingCreateChatRoomAllInOneUI.this.lZy = true;
FacingCreateChatRoomAllInOneUI.e(FacingCreateChatRoomAllInOneUI.this);
}
} else {
FacingCreateChatRoomAllInOneUI.this.lZy = false;
}
return false;
}
};
private ProgressDialog eEX;
private String eHp;
private boolean hiW = false;
private boolean lZA = false;
private Location lZB;
private String lZC;
private MMPwdInputView lZD;
private View lZE;
private ProgressBar lZF;
private TextView lZG;
private MMKeyBoardView lZH;
private TextView lZI;
private boolean lZJ = false;
private boolean lZK = false;
private LinkedList<vt> lZL = new LinkedList();
private HashMap<String, vt> lZM = new HashMap();
private LinkedList<vt> lZN = new LinkedList();
private a lZO;
private View lZP;
private TextView lZQ;
private MMScrollGridView lZR;
private View lZS;
private View lZT;
private Button lZU;
private MMCallBackScrollView lZV;
private TextView lZW;
private boolean lZX = false;
private ah lZY = new ah();
private al lZZ = new al(new 1(this), false);
private c lZv;
private boolean lZw = false;
private boolean lZx;
private boolean lZy;
private boolean lZz;
private ag mHandler = new 11(this);
private com.tencent.mm.plugin.pwdgroup.a.a maa;
private com.tencent.mm.plugin.pwdgroup.a.a mab;
private int mad;
private Animation mae;
private AnimationSet maf;
private Animation mag;
public OnMenuItemClickListener mah = new 12(this);
public MMPwdInputView.a mai = new 13(this);
private OnClickListener maj = new OnClickListener() {
public final void onClick(View view) {
FacingCreateChatRoomAllInOneUI.this.lZJ = false;
FacingCreateChatRoomAllInOneUI.d(FacingCreateChatRoomAllInOneUI.this);
}
};
public MMKeyBoardView.a mak = new 15(this);
private al mal = new al(new 17(this), false);
static /* synthetic */ void a(FacingCreateChatRoomAllInOneUI facingCreateChatRoomAllInOneUI) {
if (facingCreateChatRoomAllInOneUI.hiW || facingCreateChatRoomAllInOneUI.lZB == null) {
x.w("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "cancel refresh chat room member.");
return;
}
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "cpan[tryDoSearchScene]-----------");
facingCreateChatRoomAllInOneUI.maa = new com.tencent.mm.plugin.pwdgroup.a.a(0, facingCreateChatRoomAllInOneUI.lZC, facingCreateChatRoomAllInOneUI.eHp, facingCreateChatRoomAllInOneUI.lZB.dRS, facingCreateChatRoomAllInOneUI.lZB.dRT, facingCreateChatRoomAllInOneUI.lZB.accuracy, facingCreateChatRoomAllInOneUI.lZB.bUi, facingCreateChatRoomAllInOneUI.lZB.mac, facingCreateChatRoomAllInOneUI.lZB.bUk);
au.DF().a(facingCreateChatRoomAllInOneUI.maa, 0);
}
static /* synthetic */ void d(FacingCreateChatRoomAllInOneUI facingCreateChatRoomAllInOneUI) {
facingCreateChatRoomAllInOneUI.getString(R.l.app_tip);
facingCreateChatRoomAllInOneUI.eEX = h.a((Context) facingCreateChatRoomAllInOneUI, facingCreateChatRoomAllInOneUI.getString(R.l.app_waiting), true, new 5(facingCreateChatRoomAllInOneUI));
facingCreateChatRoomAllInOneUI.bnU();
au.DF().a(new com.tencent.mm.plugin.pwdgroup.a.a(1, facingCreateChatRoomAllInOneUI.lZC, facingCreateChatRoomAllInOneUI.eHp, facingCreateChatRoomAllInOneUI.lZB.dRS, facingCreateChatRoomAllInOneUI.lZB.dRT, facingCreateChatRoomAllInOneUI.lZB.accuracy, facingCreateChatRoomAllInOneUI.lZB.bUi, facingCreateChatRoomAllInOneUI.lZB.mac, facingCreateChatRoomAllInOneUI.lZB.bUk), 0);
}
static /* synthetic */ void e(FacingCreateChatRoomAllInOneUI facingCreateChatRoomAllInOneUI) {
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "cpan[tryGetChatRoomUser]");
if (facingCreateChatRoomAllInOneUI.mal != null) {
facingCreateChatRoomAllInOneUI.mal.SO();
}
if (facingCreateChatRoomAllInOneUI.lZy) {
if (facingCreateChatRoomAllInOneUI.lZx) {
facingCreateChatRoomAllInOneUI.uQ(a.mas);
}
if (facingCreateChatRoomAllInOneUI.lZy && facingCreateChatRoomAllInOneUI.lZx && !facingCreateChatRoomAllInOneUI.lZz) {
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "do tryGetChatRoomUser");
facingCreateChatRoomAllInOneUI.lZz = true;
facingCreateChatRoomAllInOneUI.lZx = false;
facingCreateChatRoomAllInOneUI.mab = new com.tencent.mm.plugin.pwdgroup.a.a(0, facingCreateChatRoomAllInOneUI.lZC, "", facingCreateChatRoomAllInOneUI.lZB.dRS, facingCreateChatRoomAllInOneUI.lZB.dRT, facingCreateChatRoomAllInOneUI.lZB.accuracy, facingCreateChatRoomAllInOneUI.lZB.bUi, facingCreateChatRoomAllInOneUI.lZB.mac, facingCreateChatRoomAllInOneUI.lZB.bUk);
au.DF().a(facingCreateChatRoomAllInOneUI.mab, 0);
return;
}
return;
}
x.w("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "tryGetChatRoomUser location is no ready.");
facingCreateChatRoomAllInOneUI.uQ(a.mas);
if (facingCreateChatRoomAllInOneUI.mal != null) {
facingCreateChatRoomAllInOneUI.mal.J(15000, 15000);
}
}
protected final int getLayoutId() {
return R.i.facing_create_chatroom_allin;
}
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
x.i("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "summerper checkPermission checkCamera[%b]", new Object[]{Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this, "android.permission.ACCESS_COARSE_LOCATION", 64, null, null))});
if (com.tencent.mm.pluginsdk.permission.a.a(this, "android.permission.ACCESS_COARSE_LOCATION", 64, null, null)) {
bnS();
}
}
private void bnS() {
this.lZv = c.OB();
this.lZv.a(this.cXs, true);
au.DF().a(653, this);
getWindow().getDecorView().setSystemUiVisibility(1280);
initView();
}
public void onRequestPermissionsResult(int i, String[] strArr, int[] iArr) {
x.i("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "summerper onRequestPermissionsResult requestCode[%d],grantResults[%d] tid[%d]", new Object[]{Integer.valueOf(i), Integer.valueOf(iArr[0]), Long.valueOf(Thread.currentThread().getId())});
switch (i) {
case 64:
if (iArr[0] == 0) {
bnS();
return;
} else {
h.a((Context) this, getString(R.l.permission_location_request_again_msg), getString(R.l.permission_tips_title), getString(R.l.jump_to_settings), getString(R.l.cancel), false, new DialogInterface.OnClickListener() {
public final void onClick(DialogInterface dialogInterface, int i) {
FacingCreateChatRoomAllInOneUI.this.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS"));
FacingCreateChatRoomAllInOneUI.this.finish();
}
}, new 2(this));
return;
}
default:
return;
}
}
protected void onResume() {
if (this.lZv != null) {
this.lZv.a(this.cXs, true);
}
if (this.lZX) {
bnT();
}
super.onResume();
}
protected void onPause() {
if (this.lZv != null) {
this.lZv.c(this.cXs);
}
if (this.lZX) {
bnU();
}
super.onPause();
}
protected void onDestroy() {
au.DF().b(653, this);
if (this.lZv != null) {
this.lZv.c(this.cXs);
}
if (!this.lZK) {
au.DF().cancel(653);
if (this.lZB != null) {
this.mab = new com.tencent.mm.plugin.pwdgroup.a.a(2, this.lZC, "", this.lZB.dRS, this.lZB.dRT, this.lZB.accuracy, this.lZB.bUi, this.lZB.mac, this.lZB.bUk);
au.DF().a(this.mab, 0);
}
}
if (this.lZX) {
bnU();
}
super.onDestroy();
}
protected final int getForceOrientation() {
return 1;
}
protected final void initView() {
setMMTitle(R.l.find_friends_create_pwdgroup);
setBackBtn(this.mah);
lF(getResources().getColor(R.e.transparent));
this.lZE = findViewById(R.h.facing_loading_container);
this.lZF = (ProgressBar) findViewById(R.h.facing_loading);
this.lZG = (TextView) findViewById(R.h.facing_loading_msg);
this.lZH = (MMKeyBoardView) findViewById(R.h.facing_keyboard);
this.lZI = (TextView) findViewById(R.h.facing_input_msg);
this.lZD = (MMPwdInputView) findViewById(R.h.facing_input);
this.lZD.setOnFinishInputListener(this.mai);
this.lZD.requestFocus();
this.lZH.setOnInputDeleteListener(this.mak);
uQ(a.mar);
this.lZP = findViewById(R.h.facing_content_container);
this.lZQ = (TextView) findViewById(R.h.facing_content_msg);
this.lZR = (MMScrollGridView) findViewById(R.h.facing_content_member);
this.lZR.setVisibility(4);
this.lZU = (Button) findViewById(R.h.facing_enter_chatroom);
this.lZU.setOnClickListener(this.maj);
this.lZS = findViewById(R.h.facing_enter_container);
this.lZT = findViewById(R.h.facing_enter_div);
this.lZQ.setText(R.l.facing_detail_tip);
this.lZV = (MMCallBackScrollView) findViewById(R.h.facing_scroll);
this.lZW = (TextView) findViewById(R.h.facing_input_copy);
this.lZV.setMMOnScrollListener(new 3(this));
this.lZO = new a(this);
this.lZR.setAdapter(this.lZO);
this.lZO.setData(this.lZL);
}
public final void a(int i, int i2, String str, l lVar) {
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "cpan[onSceneEnd]errType:%d errCode:%d errMsg:%s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str});
switch (lVar.getType()) {
case 653:
com.tencent.mm.plugin.pwdgroup.a.a aVar = (com.tencent.mm.plugin.pwdgroup.a.a) lVar;
int i3 = aVar.bOa;
if (i3 == 0) {
this.lZz = false;
if (this.lZX) {
if (this.lZZ != null) {
this.lZZ.J(3000, 3000);
}
if (i == 0 && i2 == 0) {
this.lZY.H(new 7(this, aVar.bnR().rbQ));
this.eHp = aVar.bnR().rwj;
return;
}
return;
} else if (i == 0 && i2 == 0) {
uQ(a.mar);
this.mad = this.lZI.getHeight();
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "mFacingInputMsgViewHeigth:%d", new Object[]{Integer.valueOf(this.mad)});
this.mae = AnimationUtils.loadAnimation(this, R.a.faded_out);
this.mag = AnimationUtils.loadAnimation(this, R.a.enter_view_in);
this.maf = new AnimationSet(true);
this.maf.addAnimation(AnimationUtils.loadAnimation(this, R.a.scroll_view_in));
Animation translateAnimation = new TranslateAnimation(0.0f, 0.0f, 0.0f, (float) (-this.mad));
translateAnimation.setDuration(300);
this.maf.addAnimation(translateAnimation);
this.mae.setDuration(200);
this.maf.setDuration(300);
this.mag.setDuration(300);
this.mae.setInterpolator(new AccelerateDecelerateInterpolator());
this.maf.setInterpolator(new AccelerateDecelerateInterpolator());
this.mag.setInterpolator(new AccelerateDecelerateInterpolator());
this.maf.setFillAfter(true);
translateAnimation.setFillAfter(true);
this.maf.setAnimationListener(new 4(this));
this.lZD.setVisibility(4);
this.lZD.setAnimation(translateAnimation);
this.lZH.startAnimation(this.mae);
this.lZE.startAnimation(this.mae);
this.lZI.startAnimation(this.mae);
this.lZS.startAnimation(this.mag);
this.lZP.startAnimation(this.maf);
this.lZS.setVisibility(4);
this.lZH.setVisibility(8);
this.lZI.setVisibility(8);
this.lZX = true;
bnT();
return;
} else if (i2 == -431) {
this.lZw = true;
uQ(a.mat);
return;
} else {
this.lZw = true;
uQ(a.mau);
return;
}
} else if (i3 == 3) {
if (i != 0 || i2 != 0) {
if (i2 == -431) {
uQ(a.mat);
this.lZw = true;
return;
}
uQ(a.mau);
return;
}
return;
} else if (i3 != 1) {
aYM();
return;
} else if (i == 0 && i2 == 0) {
aYM();
x.d("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "ChatRoomName is:%s", new Object[]{aVar.bnR().rvj});
this.lZK = true;
finish();
Intent intent = new Intent();
intent.putExtra("Chat_User", r0);
com.tencent.mm.plugin.pwdgroup.a.ezn.e(intent, this);
return;
} else if (i2 == -432 && !this.lZJ) {
this.lZJ = true;
this.mHandler.sendEmptyMessageDelayed(10002, 3000);
return;
} else if (i2 == -23) {
aYM();
zK(getString(R.l.facing_join_group_overmember));
if (this.lZZ != null) {
this.lZZ.J(3000, 3000);
return;
}
return;
} else {
aYM();
com.tencent.mm.h.a eV = com.tencent.mm.h.a.eV(str);
if (eV != null) {
eV.a(this.mController.tml, null, null);
} else {
zK(getString(R.l.radar_join_group_unknow_error));
}
if (this.lZZ != null) {
this.lZZ.J(3000, 3000);
return;
}
return;
}
default:
x.w("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "cpan[onSceneEnd] unknow scene type");
return;
}
}
public void onBackPressed() {
super.onBackPressed();
finish();
}
private void he(boolean z) {
if (this.lZH != null) {
this.lZH.setKeyBoardEnable(z);
}
}
private void uQ(int i) {
if (this.lZG != null) {
switch (10.maq[i - 1]) {
case 1:
he(true);
this.lZw = false;
this.lZA = false;
this.lZF.setVisibility(8);
this.lZG.setVisibility(8);
return;
case 2:
he(false);
this.lZG.setText(R.l.radar_join_group_verify_tip);
this.lZF.setVisibility(0);
this.lZG.setVisibility(8);
return;
case 3:
he(true);
this.lZF.setVisibility(8);
this.lZG.setVisibility(0);
this.lZG.setText(R.l.radar_join_group_simplepwd_error);
bnV();
return;
case 4:
he(true);
this.lZF.setVisibility(8);
this.lZG.setVisibility(0);
this.lZG.setText(R.l.radar_join_group_unknow_error);
bnV();
return;
default:
x.w("MicroMsg.Facing.FacingCreateChatRoomAllInONeUI", "unknow statue tip");
return;
}
}
}
private void aYM() {
if (this.eEX != null && this.eEX.isShowing()) {
this.eEX.dismiss();
}
}
private void zK(String str) {
h.a((Context) this, str, "", getString(R.l.app_ok), new 6(this));
}
private void bnT() {
this.hiW = false;
if (this.lZZ != null) {
this.lZZ.J(0, 0);
}
}
private void bnU() {
this.hiW = true;
if (this.lZZ != null) {
this.lZZ.SO();
}
au.DF().c(this.maa);
}
private void bnV() {
Animation loadAnimation = AnimationUtils.loadAnimation(this, R.a.alpha_out);
Animation loadAnimation2 = AnimationUtils.loadAnimation(this, R.a.alpha_in);
loadAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
loadAnimation.setAnimationListener(new 8(this, loadAnimation2));
loadAnimation2.setAnimationListener(new AnimationListener() {
public final void onAnimationStart(Animation animation) {
}
public final void onAnimationRepeat(Animation animation) {
}
public final void onAnimationEnd(Animation animation) {
if (FacingCreateChatRoomAllInOneUI.this.lZH != null) {
FacingCreateChatRoomAllInOneUI.this.lZH.setKeyBoardEnable(true);
}
}
});
if (this.lZD != null) {
this.lZD.startAnimation(loadAnimation);
}
if (this.lZH != null) {
this.lZH.setKeyBoardEnable(false);
}
}
}
|
package com.lsht.ml;
import java.util.ArrayList;
import java.util.List;
/**
* 节点类,负责记录和维护节点自身信息以及与这个节点相关的上下游连接,实现输出值和误差项的计算。
* Created by Junson on 2017/8/20.
*/
public class Node
{
private int layerIndex;
private int nodeIndex;
private List<Connection> upStreamConnections;
private List<Connection> downStreamConnections;
private double output;
private double delta;
private double sigmoid(double x)
{
return 1.0/(1+Math.pow(Math.E,-x));
}
public Node(int layer_index,int node_index)
{
this.layerIndex=layer_index;
this.nodeIndex=node_index;
downStreamConnections = new ArrayList();
upStreamConnections = new ArrayList();
output = 0;
delta = 0;
}
public void addDownstreamConnection(Connection connection)
{
downStreamConnections.add(connection);
}
public void addUpStreamConnection(Connection connection)
{
upStreamConnections.add(connection);
}
public double calcOutput()
{
output=0;
for(int i=0;i<upStreamConnections.size();i++)
{
Connection conn=upStreamConnections.get(i);
output+=conn.getUpstreamNode().getOutput()*conn.getWeight();
}
output = sigmoid(output);
return output;
}
/**
* 节点属于隐藏层时,根据式4计算delta
* @return
*/
public double calcHiddenLayerDelta()
{
double downstream_delta = 0;
for(Connection conn : downStreamConnections)
{
downstream_delta += conn.getDownstreamNode().delta * conn.getWeight();
}
delta = output * (1 - output) * downstream_delta;
return delta;
}
/**
* 节点属于输出层时,计算delta
* @param label
* @return
*/
public double calcOutputLayerDelta(double label)
{
delta = output * (1 - output) * (label - output);
return delta;
}
public String toString()
{
return "output:"+output+";delta:"+delta+";upStreamConnects:"+upStreamConnections+";downStreamConnectis:"+downStreamConnections;
}
public double getOutput() {
return output;
}
public void setOutput(double output) {
this.output = output;
}
public double getDelta() {
return delta;
}
public void setDelta(double delta) {
this.delta = delta;
}
public int getLayerIndex() {
return layerIndex;
}
public void setLayerIndex(int layerIndex) {
this.layerIndex = layerIndex;
}
public int getNodeIndex() {
return nodeIndex;
}
public void setNodeIndex(int nodeIndex) {
this.nodeIndex = nodeIndex;
}
public List<Connection> getUpStreamConnections() {
return upStreamConnections;
}
public void setUpStreamConnections(List<Connection> upStreamConnections) {
this.upStreamConnections = upStreamConnections;
}
public List<Connection> getDownStreamConnections() {
return downStreamConnections;
}
public void setDownStreamConnections(List<Connection> downStreamConnections) {
this.downStreamConnections = downStreamConnections;
}
}
|
package edu.nju.data.entity;
import edu.nju.data.util.MesType;
import javax.persistence.*;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
/**
* Created by ss14 on 2016/7/21.
*/
@Entity
public class Message {
private Long id;
private MesType mesgType;
private Long sourceId;
private String content;
private Timestamp createdAt =new Timestamp( new Date().getTime());
private Short checked = 0;
private User receiver = new User();
private User sender = new User();
@Transient
public void setSenderId(Long id){
sender.setId(id);
}
@Transient
public Long getSenderId(){
return sender.getId();
}
@Transient
public void setReceiverId(Long id){
receiver.setId(id);
}
@Transient
public Long getReceiverId(){
return receiver.getId();
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Enumerated(EnumType.STRING)
@Column(name = "mesg_type")
public MesType getMesgType() {
return mesgType;
}
public void setMesgType(MesType mesgType) {
this.mesgType = mesgType;
}
@Basic
@Column(name = "source_id")
public Long getSourceId() {
return sourceId;
}
public void setSourceId(Long sourceId) {
this.sourceId = sourceId;
}
@Basic
@Column(name = "content")
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Basic
@Column(name = "created_at")
public Timestamp getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Timestamp createdAt) {
this.createdAt = createdAt;
}
@Basic
@Column(name = "checked")
public Short getChecked() {
return checked;
}
public void setChecked(Short checked) {
this.checked = checked;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Message message = (Message) o;
if (id != message.id) return false;
if (sourceId != message.sourceId) return false;
if (mesgType != null ? !mesgType.equals(message.mesgType) : message.mesgType != null) return false;
if (content != null ? !content.equals(message.content) : message.content != null) return false;
if (createdAt != null ? !createdAt.equals(message.createdAt) : message.createdAt != null) return false;
if (checked != null ? !checked.equals(message.checked) : message.checked != null) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (mesgType != null ? mesgType.hashCode() : 0);
result = 31 * result + (int) (sourceId ^ (sourceId >>> 32));
result = 31 * result + (content != null ? content.hashCode() : 0);
result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0);
result = 31 * result + (checked != null ? checked.hashCode() : 0);
return result;
}
@OneToOne
@JoinColumn(name = "receiver_id", referencedColumnName = "id", nullable = false)
public User getReceiver() {
return receiver;
}
public void setReceiver(User receiver) {
this.receiver = receiver;
}
@OneToOne
@JoinColumn(name = "sender_id", referencedColumnName = "id", nullable = false)
public User getSender() {
return sender;
}
public void setSender(User sender) {
this.sender = sender;
}
@Override
public String toString() {
return "Message{" +
"id=" + id +
", mesgType=" + mesgType +
", sourceId=" + sourceId +
", content='" + content + '\'' +
", createdAt=" + createdAt +
", checked=" + checked +
", receiver=" + receiver +
", sender=" + sender +
'}';
}
}
|
import java.util.ArrayList;
public class Player {
private String name;
private String trainerClass;
private int age;
private Pkmn[] Pkmnlist = new Pkmn[3];//Should be 2 but w/e
private Pkmn currentPkmn;
private ArrayList<Item> itemList = new ArrayList<Item>();
public void showItemList() {
for (int i = 0; i<itemList.size();i++)
{
System.out.println((i+1)+". " + itemList.get(i).getName() +" Amt: " +itemList.get(i).getQuantity());
}
}
public Pkmn[] getPkmnlist() {
return Pkmnlist;
}
public void setPkmnlist(Pkmn[] pkmnlist) {
this.Pkmnlist = pkmnlist;
}
public ArrayList<Item> getItemList() {
return itemList;
}
public Item getItemInItemList( int id) {
return itemList.get(id-1);
}
public void setItemList(ArrayList<Item> itemList) {
this.itemList = itemList;
}
public void showPkmnList() {
for (int i =0; i<3; i++)
{
System.out.println((i+1)+ ". "+ Pkmnlist[i].getName() + " "+ Pkmnlist[i].showHP() );
}
}
public Pkmn getCurrentPkmn() { return currentPkmn; }
public void setCurrentPkmn(Pkmn currentPkmn) {
this.currentPkmn = currentPkmn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTrainerClass() {
return trainerClass;
}
public void setTrainerClass(String trainerClass) {
this.trainerClass = trainerClass;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void setPkmnList(Pkmn pokemon,int id) {
id = id-1;
Pkmnlist[id] = pokemon;
}
public Pkmn getPkmnList(int id) {
id = id-1;
return Pkmnlist[id];
}
Player(String name, String trainerClass, int age ){
this.name = name;
this.trainerClass = trainerClass;
this.age = age;
}
}
|
package cq.java8.lambda;
//定义一个接口
public interface EmployStrategy {
//定义一个筛选方法
public boolean filterEmploy(Employ employ);
}
|
package Aula09;
public class Jogador implements JogadorInterface{
private String nome;
Jogador(String nome){
this.nome=nome;
}
@Override
public void joga() {
// TODO Auto-generated method stub
System.out.print("\nO "+nome+" joga");
}
}
|
package leetcode;
import java.util.HashMap;
import java.util.Hashtable;
/**
* Created by yang on 2017/1/4.
*/
/*
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
Subscribe to see which companies asked this question
*/
public class LongestSubstringWithoutRepeatingCharacters_3 {
public static int lengthOfLongestSubstring(String s) {
int oldPosition = 0;
int max = 0;
char[] chars = s.toCharArray();
HashMap<Character,Integer> map = new HashMap<Character, Integer>();
if(chars.length==0){
return 0;
}
map.put(chars[0],0);
//tmmzuxt uuuuuu
max = 1;
for(int i = 1;i<chars.length;i++){
if(map.containsKey(chars[i])){
oldPosition = Math.max(oldPosition,map.get(chars[i])+1);
}
map.put(chars[i],i);
max = Math.max(max,i-oldPosition+1);
}
return max;
}
public static void main(String[] args){
String s = "tmmzuxt";
System.out.println(LongestSubstringWithoutRepeatingCharacters_3.lengthOfLongestSubstring(s));
}
}
|
package com.saha.test.base;
import com.saha.test.page.TopMenu;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.LocalFileDetector;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URL;
public class BaseTest {
protected WebDriver driver;
public static String baseUrl = "https://www.trendyol.com/";
public static String contractUrl = "https://backoffice-stg.jollytur.ws/";
public static Boolean isTestinium = false;
public static Dimension browserSize = null;
@Before
public void setUp() throws Exception {
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("key", System.getProperty("key"));
if (StringUtils.isEmpty(System.getProperty("key"))){
System.setProperty("webdriver.chrome.driver", "properties/driver/chromedriver");
driver = new ChromeDriver(capabilities);
}
else {
isTestinium = true;
driver = new RemoteWebDriver(new URL("http://hub.testinium.io/wd/hub"), capabilities);
((RemoteWebDriver) driver).setFileDetector(new LocalFileDetector());
}
driver.manage().window().maximize();
browserSize = driver.manage().window().getSize();
driver.get(baseUrl);
}
@After
public void tearDown() throws Exception {
//driver.quit();
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("Confidential Information"). You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms of the
* license agreement you entered into with SAP.
*/
package de.hybris.platform.cmsfacades.util.builder;
import de.hybris.platform.core.model.user.UserGroupModel;
import java.util.Locale;
public class UserGroupModelBuilder
{
private final UserGroupModel model;
private UserGroupModelBuilder()
{
this.model = new UserGroupModel();
}
private UserGroupModelBuilder(final UserGroupModel model)
{
this.model = model;
}
protected UserGroupModel getModel()
{
return this.model;
}
public static UserGroupModelBuilder aModel()
{
return new UserGroupModelBuilder();
}
public static UserGroupModelBuilder fromModel(final UserGroupModel model)
{
return new UserGroupModelBuilder(model);
}
public UserGroupModel build()
{
return getModel();
}
public UserGroupModelBuilder withName(final String name, final Locale locale)
{
getModel().setLocName(name, locale);
return this;
}
public UserGroupModelBuilder withUid(final String uid)
{
getModel().setUid(uid);
return this;
}
}
|
import java.util.Scanner;
public class TipoDeCombustivel {
public static void main(String []agrs) {
Scanner scan = new Scanner(System.in);
int n = Integer.parseInt(scan.nextLine());
int alcool = 0;
int gasolina = 0;
int diesel = 0;
while(n != 4) {
if (n == 1) {
alcool++;
} else if (n == 2) {
gasolina++;
} else if (n == 3) {
diesel++;
}
n = Integer.parseInt(scan.nextLine());
}
System.out.println("MUITO OBRIGADO");
System.out.println("Alcool: "+alcool);
System.out.println("Gasolina: "+gasolina);
System.out.println("Diesel: "+diesel);
scan.close();
}
}
|
package org.usfirst.frc.team467.robot.Autonomous;
/**
* A collection of methods that a drive class must implement to run our autonomous modes
*/
public interface AutoDrive {
void moveLinearFeet(double distance);
void rotateByAngle(double rotationInDegrees);
/**
* Move each side independently. Distances must be equal or opposite.
*/
void moveFeet(double leftDistance, double rightDistance);
boolean isStopped();
/**
* Gets the distance moved for checking drive modes.
*
* @return the absolute distance moved in feet
*/
double absoluteDistanceMoved();
/**
* Resets the current sensor position to zero.
*/
void zero();
} |
package de.jmda.fx.cdi.multiview.view1;
public class FXView1EventData { } |
package com.joshuarichardson.dependencyinjection;
import android.content.Context;
import com.joshuarichardson.dependencyinjection.Modules.AnalyticsModule;
import com.joshuarichardson.dependencyinjection.Modules.DatabaseEntity;
import com.joshuarichardson.dependencyinjection.Modules.DatabaseModule;
import com.joshuarichardson.dependencyinjection.Modules.NameDao;
import com.joshuarichardson.dependencyinjection.Modules.WellbeingDatabase;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import java.util.ArrayList;
import javax.inject.Inject;
import androidx.test.espresso.assertion.ViewAssertions;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import dagger.Module;
import dagger.Provides;
import dagger.hilt.InstallIn;
import dagger.hilt.android.components.ApplicationComponent;
import dagger.hilt.android.qualifiers.ApplicationContext;
import dagger.hilt.android.testing.HiltAndroidRule;
import dagger.hilt.android.testing.HiltAndroidTest;
import dagger.hilt.android.testing.UninstallModules;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@HiltAndroidTest
@UninstallModules({AnalyticsModule.class, DatabaseModule.class})
public class HiltDatabaseTest {
// References:
// Multiple rules - https://developer.android.com/training/dependency-injection/hilt-testing#multiple-testrules
// How to chain rules and keep references to them - https://stackoverflow.com/a/27243450/13496270
// Rule order matters https://dagger.dev/hilt/testing.html
private ActivityScenarioRule<MainActivity> mainActivityScenario = new ActivityScenarioRule<>(MainActivity.class);
public HiltAndroidRule hiltRule = new HiltAndroidRule(this);
@Rule
public RuleChain chain = RuleChain.outerRule(hiltRule).around(mainActivityScenario);
// References:
// Replace a binding https://developer.android.com/training/dependency-injection/hilt-testing#replace-binding
// Finishing off the loose ends https://www.youtube.com/watch?v=nOp_CEP_EjM
// The Hilt docs https://dagger.dev/hilt/testing.html
@Module
@InstallIn(ApplicationComponent.class)
public static class TestDatabaseModule {
@Provides
public WellbeingDatabase provideDatabaseService(@ApplicationContext Context context) {
WellbeingDatabase databaseMock = mock(WellbeingDatabase.class);
NameDao nameDao = mock(NameDao.class);
ArrayList<DatabaseEntity> array = new ArrayList<>();
array.add(new DatabaseEntity(4));
// References:
// How to use any() - https://www.journaldev.com/21876/mockito-argument-matchers-any-eq
// How to use thenReturn() - https://stackoverflow.com/a/60540072/13496270
when(nameDao.insert(any(DatabaseEntity.class))).thenReturn(0L);
when(nameDao.getEntities()).thenReturn(array);
when(databaseMock.nameDao()).thenReturn(nameDao);
return databaseMock;
}
}
@Inject
WellbeingDatabase database;
@Inject
AnalyticsService analyticsService;
@Before
public void setUp() {
// References
// Injecting everything - https://developer.android.com/training/dependency-injection/hilt-testing#testing-features
hiltRule.inject();
}
@Test
public void checkMockedDatabaseMocksTheDataInTheUI() {
onView(withId(R.id.textView2)).check(ViewAssertions.matches(withText("4")));
}
} |
/*
内部类只有被定义在成员位置上时,才能被私有或静态所修饰;一般内部类是不会被公有修饰
内部类可以写在类的任意位置上
*/
class Outer{
int x = 3;
void method(){
class Inner{ // 局部内部类,不能被静态私有修饰,静态、私有只修饰成员,现在Inner在局部,不能被修饰
void function(){ // 内部类中不能有静态成员,如果有,那么说明内部类也得是静态的,与以上相悖;
// 它的成员都是非静态的,没对象不能运行
System.out.println(Outer.this.x); // 可以访问外部成员;
}
}
new Inner().function();
}
}
class InnerClassDemo3{
public static void main(String[] args){
new Outer().method();
}
}
// - _ -! |
import java.io.File;
import javax.swing.JFileChooser;
public class Verzeichnissuche
{
private JFileChooser auswahl;
private int anzahlOrdner;
private int anzahlDateien;
private long groeßeDateien;
public Verzeichnissuche()
{
Verzeichnissuche();
}
private void Verzeichnissuche()
{
auswahl = new JFileChooser("U:\\");
auswahl.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
int returnwert = auswahl.showDialog( null, null );
if(returnwert != JFileChooser.APPROVE_OPTION) return;
File dateien = auswahl.getSelectedFile( );
suche (dateien);
System.out.println( "Anzahl Dateien:\t\t" + anzahlDateien );
System.out.println( "Anzahl Ordner:\t\t"+ anzahlOrdner );
System.out.println( "Größe der Dateien:\t" + groeßeDateien +" bytes" );
}
private void suche (File verzeichnis)
{
File[] liste = verzeichnis.listFiles( );
if(liste != null)
{
for(int i = 0; i < liste.length; i++)
{
if(liste[i].isFile( ))
{
anzahlDateien++;
groeßeDateien = groeßeDateien + liste[i].length( );
}
else if(liste[i].isDirectory( ))
{
anzahlOrdner++;
suche(liste[i]);
}
}
}
}
public static void main(String[] args)
{
new Verzeichnissuche();
}
}
|
package com.filiereticsa.arc.augmentepf.localization;
import android.graphics.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
/**
* Created by anthonyprudhomme on 11/10/16.
* Copyright © 2016 Granite Apps. All rights reserved.
*/
public class GABeaconLocalizer {
private static final String TAG = "Ici";
CoordinatesCalcMethod phoneCoordinateCalcMethod = CoordinatesCalcMethod.CENTROID;
private int historySize = 1;
private double kUnknownAccuracyValue = 1;
private Double unknownAccuracyReplaceValue = null;
// Sorting methods to apply
private ArrayList<ComparisonMethod> accSortComparatorStack = new ArrayList<>();
private Integer lastAccuracySortIndex = null;
private Integer avgAccuracySortIndex = null;
private CoordinatesCalcMethod phoneCoordinateMethod;
private Map<String, ArrayList<LocalizedBeaconStatus>> beaconsStatuses = new HashMap<>();
public void setHistorySize(int newHistorySize) {
if (historySize > newHistorySize) {
checkStatusesForHistorySize(newHistorySize);
}
historySize = newHistorySize;
}
private void checkStatusesForHistorySize(int size) {
for (Map.Entry<String, ArrayList<LocalizedBeaconStatus>> entry : beaconsStatuses.entrySet()) {
if (beaconsStatuses.get(entry.getKey()).size() > size) {
for (int i = 0; i < beaconsStatuses.get(entry.getKey()).size() - size; i++) {
beaconsStatuses.get(entry.getKey()).remove(0);
}
}
}
}
public void setSortUsingLastAccuracy(Boolean useLastAccuracy) {
if (!useLastAccuracy && lastAccuracySortIndex != null) {
accSortComparatorStack.remove((int) lastAccuracySortIndex);
lastAccuracySortIndex = null;
}
if (useLastAccuracy) {
// If it was already enabled, we'll make sure it's applied last again
if (lastAccuracySortIndex != null && lastAccuracySortIndex != (accSortComparatorStack.size() - 1)) {
accSortComparatorStack.remove((int) lastAccuracySortIndex);
}
accSortComparatorStack.add(ComparisonMethod.LAST_ACCURACY);
lastAccuracySortIndex = accSortComparatorStack.size() - 1;
}
}
private int lastAccuracyComparison(ArrayList<LocalizedBeaconStatus> statuses1, ArrayList<LocalizedBeaconStatus> statuses2) {
if (statuses2.size() != 0 && statuses1.size() != 0 && (statuses1.get(statuses1.size() - 1).accuracy <= statuses2.get(statuses2.size() - 1).accuracy)) {
return -1;
} else {
return 1;
}
}
private int averageAccuracyComparison(ArrayList<LocalizedBeaconStatus> statuses1, ArrayList<LocalizedBeaconStatus> statuses2) {
if (statuses1.size() != 0 && statuses2.size() != 0) {
double avg1 = 0;
for (int i = 0; i < statuses1.size(); i++) {
avg1 += statuses1.get(i).accuracy;
}
avg1 = avg1 / (double) (statuses1.size());
double avg2 = 0;
for (int i = 0; i < statuses2.size(); i++) {
avg2 += statuses1.get(i).accuracy;
}
avg2 = avg2 / (double) (statuses2.size());
if (avg1 <= avg2) {
return -1;
} else {
return 1;
}
} else {
return 0;
}
}
public void setPhoneCoordinateCalcMethod(CoordinatesCalcMethod phoneCoordinateCalcMethod) {
switch (phoneCoordinateCalcMethod) {
case SQUARE:
phoneCoordinateMethod = CoordinatesCalcMethod.SQUARE;
break;
case CENTROID:
phoneCoordinateMethod = CoordinatesCalcMethod.CENTROID;
break;
case NEAREST:
phoneCoordinateMethod = CoordinatesCalcMethod.NEAREST;
break;
}
}
// Returns the N closest beacon
public ArrayList<GABeacon> nearestBeacons(Integer beaconsNr) {
if (beaconsNr == null) {
beaconsNr = 1;
}
if (beaconsStatuses.size() != 0) {
// We need a coordinate method
if (phoneCoordinateMethod == null) {
phoneCoordinateCalcMethod = CoordinatesCalcMethod.CENTROID;
}
// Let's apply data filters to beacon statuses
for (Map.Entry<String, ArrayList<LocalizedBeaconStatus>> entry : beaconsStatuses.entrySet()) {
beaconsStatuses.put(entry.getKey(), replaceUnknownAccuracy(kUnknownAccuracyValue, unknownAccuracyReplaceValue, entry.getValue()));
}
// Let's sort the beacons using their last accuracy or other method
// Let's use last comparator method in stack
ArrayList<String> sortedKeys;
ComparisonMethod sortingMethod = null;
if (accSortComparatorStack != null && accSortComparatorStack.size() != 0) {
sortingMethod = accSortComparatorStack.get(accSortComparatorStack.size() - 1);
}
if (sortingMethod != null) {
sortedKeys = sortedBeaconKeys(beaconsStatuses, sortingMethod);
} else {
sortedKeys = new ArrayList<>(this.beaconsStatuses.keySet());
}
ArrayList<LocalizedBeaconStatus> statuses = new ArrayList<>();
for (int i = 0; i < Math.min(sortedKeys.size(), beaconsNr); i++) {
String key = sortedKeys.get(i);
LocalizedBeaconStatus lastStatus = null;
if (beaconsStatuses != null && beaconsStatuses.get(key) != null && beaconsStatuses.get(key).size() != 0) {
lastStatus = beaconsStatuses.get(key).get(beaconsStatuses.get(key).size() - 1);
}
if (lastStatus != null) {
statuses.add(lastStatus);
}
}
return this.beaconsFromStatuses(statuses);
} else {
return null;
}
}
// MARK: - Ranged beacons
public void addRangedBeacons(ArrayList<GABeacon> beacons) {
// Add new data
for (int i = 0; i < beacons.size(); i++) {
GABeacon currentBeacon = beacons.get(i);
if (beaconsStatuses.get(currentBeacon.getKeyString()) == null) {
beaconsStatuses.put(currentBeacon.getKeyString(), new ArrayList<LocalizedBeaconStatus>());
}
// Using map index path
Point beaconCoordinates;
if (currentBeacon.mapIndexPath != null) {
beaconCoordinates = new Point(currentBeacon.mapIndexPath.first, currentBeacon.mapIndexPath.second);
} else {
// Using coordinates
beaconCoordinates = new Point(currentBeacon.getxCoord(), currentBeacon.getyCoord());
}
if (currentBeacon.getAccuracy() != -1) {
beaconsStatuses.get(currentBeacon.getKeyString()).add(new LocalizedBeaconStatus(currentBeacon.getUuid()
, currentBeacon.getProximity()
, currentBeacon.getAccuracy()
, beaconCoordinates
, currentBeacon.getMapId()
, currentBeacon.getMapIndexPath()
, currentBeacon.getKeyString()));
}
// If history's too big, remove first values
if (beaconsStatuses.get(currentBeacon.getKeyString()).size() > historySize) {
beaconsStatuses.get(currentBeacon.getKeyString()).remove(0);
}
}
}
private ArrayList<String> sortedBeaconKeys(final Map<String, ArrayList<LocalizedBeaconStatus>> statusesDic, final ComparisonMethod comparisonMethod) {
ArrayList<String> keys = new ArrayList<>(statusesDic.keySet());
Collections.sort(keys, new Comparator<String>() {
@Override
public int compare(String string1, String string2) {
return getSortingMethod(comparisonMethod, statusesDic.get(string1), statusesDic.get(string2));
}
});
return keys;
}
private ArrayList<LocalizedBeaconStatus> replaceUnknownAccuracy(double unknownAccuracyValue, Double toAccuracy, ArrayList<LocalizedBeaconStatus> statuses) {
int statusIdx = 0;
while (statusIdx < statuses.size()) {
if (statuses.get(statusIdx).accuracy == unknownAccuracyValue) {
if (toAccuracy != null) {
statuses.get(statusIdx).accuracy = toAccuracy;
} else {
statuses.remove(statusIdx);
statusIdx -= 1;
}
}
statusIdx += 1;
}
return statuses;
}
private ArrayList<GABeacon> beaconsFromStatuses(ArrayList<LocalizedBeaconStatus> statuses) {
ArrayList<GABeacon> beacons = new ArrayList<>();
ArrayList<GABeacon> allBeacons = GABeacon.allBeacons;
for (int i = 0; i < statuses.size(); i++) {
for (int j = 0; j < allBeacons.size(); j++) {
if (allBeacons.get(j).getKeyString().equalsIgnoreCase(statuses.get(i).keyString)) {
GABeacon beacon = allBeacons.get(j);
//beacon.setDistance(statuses.get(i).accuracy);
beacons.add(beacon);
}
}
}
return beacons;
}
private int getSortingMethod(ComparisonMethod comparisonMethod, ArrayList<LocalizedBeaconStatus> statuses1, ArrayList<LocalizedBeaconStatus> statuses2) {
switch (comparisonMethod) {
case LAST_ACCURACY:
return lastAccuracyComparison(statuses1, statuses2);
case AVERAGE_ACCURACY:
return averageAccuracyComparison(statuses1, statuses2);
default:
return 0;
}
}
private Point meshCoordinates(ArrayList<Point> beaconsCoordinates, CoordinatesCalcMethod method) {
switch (method) {
case SQUARE:
return squareBasedCoordinates(beaconsCoordinates);
case NEAREST:
return nearestBeaconCoordinates(beaconsCoordinates);
case CENTROID:
return centroidBasedCoordinates(beaconsCoordinates);
default:
return null;
}
}
private Point nearestBeaconCoordinates(ArrayList<Point> coordinates) {
if (coordinates != null && coordinates.size() != 0) {
return coordinates.get(0);
}
return null;
}
private Point squareBasedCoordinates(ArrayList<Point> coordinates) {
if (coordinates != null && coordinates.size() != 0) {
if (coordinates.size() >= 4) {
ArrayList<Point> fourFirstCoordinates = new ArrayList<>();
fourFirstCoordinates.add(coordinates.get(0));
fourFirstCoordinates.add(coordinates.get(1));
fourFirstCoordinates.add(coordinates.get(2));
fourFirstCoordinates.add(coordinates.get(3));
return topLeftCoordinates(fourFirstCoordinates);
}
}
return null;
}
private Point centroidBasedCoordinates(ArrayList<Point> coordinates) {
// We need coordinates
if (coordinates != null && coordinates.size() != 0) {
if (coordinates.size() >= 3) {
ArrayList<Point> extractedPoints = new ArrayList<>();
extractedPoints.add(coordinates.get(0));
extractedPoints.add(coordinates.get(1));
// Append first point in coordinates that is not aligned with the two others
int index = 2;
while (extractedPoints.size() < 3 && index < coordinates.size()) {
if (!isAligned(coordinates.get(index), extractedPoints)) {
extractedPoints.add(coordinates.get(index));
}
index += 1;
}
return topLeftCoordinates(extractedPoints);
}
}
return null;
}
private boolean isAligned(Point point, ArrayList<Point> pointsArray) {
return pointsArray.size() >= 2 && ((point.x == pointsArray.get(0).x && point.x == pointsArray.get(1).x) || (point.y == pointsArray.get(0).y && point.y == pointsArray.get(1).y));
}
// Returns the top-left coordinates in an array of points in the mesh
private Point topLeftCoordinates(ArrayList<Point> coordinatesArray) {
// 4 values: top left value
if (coordinatesArray.size() == 4) {
ArrayList<Point> sortedPoints = null;
Collections.sort(coordinatesArray, new Comparator<Point>() {
@Override
public int compare(Point point1, Point point2) {
if (point1.x <= point2.x && point1.y <= point2.y) {
return -1;
} else {
return 1;
}
}
});
if (sortedPoints != null) {
return sortedPoints.get(0);
} else {
return null;
}
}
// 3 Values: compute the centroid's coordinates (x,y) and
// return the top left coordinate (floor(x), floor(y)).
if (coordinatesArray.size() == 3) {
// centroid
Point a = coordinatesArray.get(0);
Point b = coordinatesArray.get(1);
Point c = coordinatesArray.get(2);
int x = (int) ((a.x + b.x + c.x) / 3.0);
int y = (int) ((a.y + b.y + c.y) / 3.0);
return new Point(x, y);
}
return null;
}
public enum CoordinatesCalcMethod {
NEAREST,
SQUARE,
CENTROID
}
private enum ComparisonMethod {
LAST_ACCURACY,
AVERAGE_ACCURACY
}
}
|
package com.example.a3_pc.complex_calculator;
import java.lang.Math;
public class complex {
public double real;
public double imaginary;
public double modulus;
public double angle;
// Default constructor of a complex number
complex() {
this.real = Double.NaN;
this.imaginary = Double.NaN;
this.modulus = Double.NaN;
this.angle = Double.NaN;
}
// Determines the string's form and constructs a
// complex number based on the string's form
// Valid string format:
// x+yi
// yi
// x
// xe^yi
// e^yi
// e^i
// r(cos(x) + isin(x))
complex(String str) {
str = str.replaceAll(" ", "");
if(str.contains("e^")) { // If in exponential form
complex exp = splitE(str);
this.real = exp.real;
this.imaginary = exp.imaginary;
this.angle = exp.angle;
this.modulus = exp.modulus;
}
else if (str.contains("sin")) {
complex polar = splitP(str);
this.real = polar.real;
this.imaginary = polar.imaginary;
this.angle = polar.angle;
this.modulus = polar.modulus;
}
else { // If in rectangular form
complex rec = splitC(str);
this.real = rec.real;
this.imaginary = rec.imaginary;
this.modulus = Math.sqrt(rec.real*rec.real + rec.imaginary*rec.imaginary);
this.angle = Math.asin(rec.imaginary/rec.modulus);
}
}
// Calculates the index of the last operator in the string to find operator
// in between the real and imaginary value
private static int lastOPindex(String str) {
int i = str.indexOf('+');
int s = str.indexOf('-');
while(i >= 0) {
if(-1 == str.indexOf('+', i+1))
break;
else
i = str.indexOf('+', i+1);
}
while(s >= 0) {
if(-1 == str.indexOf('-', s+1))
break;
else
s = str.indexOf('-', s+1);
}
int middle = Math.max(i, s);
return middle;
}
// Checks if string in rectangular form contains both
// real and imaginary values
private static boolean isBinary(String str) {
if(str.contains("+") || str.contains("-")) {
int middle = lastOPindex(str);
if(str.substring(0, middle).matches("-?\\d+(\\.\\d+)?")
&& str.substring(middle+1).contains("i"))
return true;
}
return false;
}
// Splits the real and imaginary values of the string in rectangular form
public static complex splitC(String str) {
complex num = new complex();
String real = "";
String imaginary = "";
if(isBinary(str)) {
int i = lastOPindex(str);
real = str.substring(0, i);
imaginary = str.substring(i).replaceAll("i", "");
}
else if(!str.contains("i")) {
real = str;
imaginary = "0";
}
else if(!str.contains("+") && str.contains("i")) {
real = "0";
str = str.replaceAll("i", "");
if(str.isEmpty())
imaginary = "1";
else
imaginary = str;
}
if(imaginary.equals("-"))
imaginary = "-1";
else if(imaginary.equals("+"))
imaginary = "1";
num.real = Double.parseDouble(real);
num.imaginary = Double.parseDouble(imaginary);
return num;
}
// Splits the real and imaginary values of the string in exponential form
public static complex splitE(String str) {
int i = str.indexOf("e^");
String r = str.substring(0, i);
double modulus;
if(r.isEmpty())
modulus = 1;
else
modulus = Double.parseDouble(r);
String angle = str.substring(i+2, str.length()-1);
double ang;
if(angle.isEmpty())
ang = 1;
else
ang = Double.parseDouble(angle);
complex ans = new complex();
double length = Double.parseDouble(r);
ans.real = modulus * Math.cos(ang);
ans.imaginary = modulus * Math.sin(ang);
ans.angle = ang;
ans.modulus = length;
return ans;
}
// Splits the real and imaginary values of the string in polar form
public static complex splitP(String str) {
int i = str.indexOf("(");
String r = str.substring(0, i);
complex ans = new complex();
ans.modulus = Double.parseDouble(r);
int open = str.indexOf("cos(");
int closing = str.indexOf(")");
double angle = Double.parseDouble(str.substring(open+4, closing));
ans.angle = angle;
ans.real = Math.cos(angle) * ans.modulus;
ans.imaginary = Math.sin(angle) * ans.modulus;
return ans;
}
// The Addition method for complex numbers
public static complex add(complex v1, complex v2) {
complex ans = new complex();
ans.real = v1.real + v2.real;
ans.imaginary = v1.imaginary + v2.imaginary;
ans.modulus = Math.sqrt(ans.real*ans.real + ans.imaginary*ans.imaginary);
ans.angle = Math.asin(ans.imaginary/ans.modulus);
return ans;
}
// The Subtraction method for complex numbers
public static complex subtract(complex v1, complex v2) {
complex ans = new complex();
ans.real = v1.real - v2.real;
ans.imaginary = v1.imaginary - v2.imaginary;
ans.modulus = Math.sqrt(ans.real*ans.real + ans.imaginary*ans.imaginary);
ans.angle = Math.asin(ans.imaginary/ans.modulus);
return ans;
}
// The Multiplication method for complex numbers
public static complex multiply(complex v1, complex v2) {
complex ans = new complex();
ans.real = (v1.real * v2.real) - (v1.imaginary * v2.imaginary);
ans.imaginary = (v1.real * v2.imaginary) + (v2.real * v1.imaginary);
ans.modulus = Math.sqrt(ans.real*ans.real + ans.imaginary*ans.imaginary);
ans.angle = Math.asin(ans.imaginary/ans.modulus);
return ans;
}
// The Division method for complex numbers
public static complex divide(complex v1, complex v2) {
complex ans = new complex();
complex numerator = new complex();
complex conjugate = v2;
conjugate.imaginary *= -1;
numerator = multiply(v1, conjugate);
ans.real = numerator.real / (v2.real * v2.real + v2.imaginary * v2.imaginary);
ans.imaginary = numerator.imaginary / (v2.real * v2.real + v2.imaginary * v2.imaginary);
ans.modulus = Math.sqrt(ans.real*ans.real + ans.imaginary*ans.imaginary);
ans.angle = Math.asin(ans.imaginary/ans.modulus);
return ans;
}
// Converts a complex number to a string based on the given form
public static String to_String(complex v, String form) {
String ans = "";
if(form.equals("Rectangular")) {
if(v.imaginary >= 0)
ans = String.valueOf(v.real) + "+" + String.valueOf(v.imaginary) + "i";
else if(v.imaginary < 0)
ans = String.valueOf(v.real) + String.valueOf(v.imaginary) + "i";
}
else if(form.equals("Exponential")) {
ans = String.valueOf(v.modulus) + "e^(" + String.valueOf(v.angle) + "i)";
}
else if(form.equals("Polar")) {
ans = String.valueOf(v.modulus) + "(cos(" + String.valueOf(v.angle) + ")"
+ " + isin(" + String.valueOf(v.angle) + "))";
}
else
ans = "ERROR: Complex Form not selected";
return ans;
}
} |
package swt6.client;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import swt6.timer.interfaces.Timer;
import swt6.timer.interfaces.TimerService;
import swt6.timer.interfaces.TimerServiceFactory;
import java.util.List;
import java.util.Scanner;
import java.util.ServiceLoader;
public class Client {
private static boolean isRunning = true;
private static TimerService timerService = getTimerService();
private static Scanner scanner = new Scanner(System.in);
private final static Logger logger = LogManager.getLogger(Client.class);
public static void main(String[] args) {
printCommands();
while(isRunning) {
computeInput(scanner.nextLine());
}
}
private static void computeInput(String cmd) {
switch (cmd) {
case "/create":
computeCreate();
break;
case "/start":
computeStart();
break;
case "/stop":
computeStop();
break;
case "/change":
computeChange();
break;
case "/reset":
computeReset();
break;
case "/list":
computeList();
break;
case "/quit":
computeQuit();
break;
default:
computeUnknownCommand(cmd);
}
}
private static void computeCreate() {
boolean created = false;
Timer t = null;
// read interval
do {
System.out.println("Enter interval in ms and number of iterations > ");
System.out.println("Format: [interval], [iterations]");
String inputCreate = scanner.nextLine();
inputCreate = inputCreate.strip();
try {
// parse values
int commaIndex = inputCreate.indexOf(',');
if (commaIndex < 0) throw new IllegalArgumentException("Invalid format specified");
int interval = Integer.parseInt(inputCreate.substring(0, commaIndex));
int iterations = Integer.parseInt(inputCreate.substring(commaIndex + 1).strip());
// create timer
t = timerService.create(interval, iterations);
created = true;
} catch (Exception e) {
logger.error(e);
}
} while (!created);
if (t != null) {
// add listener
t.addTimerListener(new TimerAdapter());
// read start timer input
String startTimerCmd;
do {
System.out.println("Start timer now? (y, n) >");
startTimerCmd = scanner.nextLine();
} while (!startTimerCmd.equals("y") && !startTimerCmd.equals("n"));
if (startTimerCmd.equals("y")) t.start();
}
}
private static void computeStart() {
List<Timer> inactiveTimers = timerService.getInActiveTimers();
System.out.println("==================================================");
if (inactiveTimers.size() == 0) {
logger.info("There are no inactive timers");
System.out.println("==================================================");
return;
}
printStartStopList(inactiveTimers);
System.out.println("==================================================");
Timer t = getTimerFromInput();
try {
if (t != null) {
t.start();
}
} catch (Exception e) {
logger.error(e);
}
}
private static void computeStop() {
List<Timer> activeTimers = timerService.getActiveTimers();
System.out.println("==================================================");
if (activeTimers.size() == 0) {
logger.info("There are no active timers");
System.out.println("==================================================");
return;
}
printStartStopList(activeTimers);
System.out.println("==================================================");
Timer t = getTimerFromInput();
try {
if (t != null) {
t.stop();
}
} catch (Exception e) {
logger.error(e);
}
}
private static void computeChange() {
computeList();
Timer t = getTimerFromInput();
String changeCmd;
do {
System.out.println("Do you want to change maximum iterations (iter) or interval (inter)? >");
changeCmd = scanner.nextLine();
} while (!changeCmd.equals("iter") && !changeCmd.equals("inter"));
if (changeCmd.equals("iter"))
computeChangeIterations(t);
else
computeChangeInterval(t);
}
private static void computeChangeIterations(Timer t) {
boolean successfulChange = false;
do {
System.out.println(t.getInfo());
System.out.println("Enter new iteration amount >");
try {
int iterations = Integer.parseInt(scanner.nextLine());
timerService.changeTimerIterations(t, iterations);
successfulChange = true;
logger.info("Timer updated:");
logger.info(t.getInfo());
} catch (Exception e) {
logger.error(e);
}
} while (!successfulChange);
}
private static void computeChangeInterval(Timer t) {
boolean successfulChange = false;
do {
System.out.println(t.getInfo());
System.out.println("Enter new interval in ms (>50ms) >");
try {
int interval = Integer.parseInt(scanner.nextLine());
timerService.changeTimerInterval(t, interval);
successfulChange = true;
logger.info("Timer updated:");
logger.info(t.getInfo());
} catch (Exception e) {
logger.error(e);
}
} while (!successfulChange);
}
private static void computeReset() {
computeList();
Timer t = getTimerFromInput();
try {
if (t != null) {
t.reset();
}
} catch (Exception e) {
logger.error(e);
}
}
private static void computeList() {
List<Timer> timers = timerService.getAllTimers();
System.out.println("==================================================");
if (timers.size() == 0) {
logger.info("No timers instantiated");
}
else {
for (Timer t : timers) {
logger.info(t.getInfo() + ", " + (t.isActive() ? "Active": "Inactive"));
}
}
System.out.println("==================================================");
}
private static void computeQuit() {
List<Timer> timers = timerService.getAllTimers();
for (Timer t : timers) {
if (t.isActive())
t.stop();
}
isRunning = false;
}
private static void printStartStopList(List<Timer> l) {
for (Timer t : l) {
logger.info(t.getInfo() + ", " + (t.isActive() ? "Active": "Inactive"));
}
}
private static Timer getTimerFromInput() {
boolean validId = false;
int id = -1;
Timer t = null;
do {
System.out.println("Enter timer id >");
String inputStart = scanner.nextLine();
try {
id = Integer.parseInt(inputStart.strip());
t = timerService.getAllTimers().get(id);
validId = true;
} catch (Exception e) {
if (e instanceof IndexOutOfBoundsException) {
logger.error(String.format("Timer with Id [%s] not found", id));
} else {
logger.error(e);
}
}
} while (!validId);
return t;
}
private static void printCommands() {
System.out.println("Available commands:");
System.out.println("/create, /start, /stop, /change, /reset, /list, /quit");
}
private static void computeUnknownCommand(String cmd) {
System.out.printf("Unknown command: %s%n", cmd);
printCommands();
}
private static TimerService getTimerService () {
TimerService t = null;
ServiceLoader<TimerServiceFactory> loader = ServiceLoader.load(TimerServiceFactory.class);
for (TimerServiceFactory tsf : loader)
if (tsf.providesFeature("TimerServiceImpl"))
t = tsf.getTimerService();
return t;
}
} |
package modul6.ab04;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class SoccerTable {
private List<Team> teams;
private static final Comparator<Team> COMPARATOR_TEAM = Comparator.comparingInt(Team::getScore).thenComparingInt(Team::getGoal).thenComparing(Team::getCounterGoal).reversed();
public List<Team> getTeams() {
return teams;
}
private void setTeams(List<Team> teams) {
this.teams = teams;
}
private void calculateScores(List<Matchup> matchups) {
for (Matchup matchup : matchups) {
if (matchup.getGoalTeam1() > matchup.getGoalTeam2()) {
matchup.getTeam1().addPoint(3);
} else if (matchup.getGoalTeam2() > matchup.getGoalTeam1()) {
matchup.getTeam2().addPoint(3);
} else {
matchup.getTeam1().addPoint(1);
matchup.getTeam2().addPoint(1);
}
}
}
private void calculateGoals(List<Matchup> matchups) {
for (Matchup matchup : matchups) {
matchup.getTeam1().addGoal(matchup.getGoalTeam1());
matchup.getTeam2().addGoal(matchup.getGoalTeam2());
}
}
private void calculateCounterGoals(List<Matchup> matchups) {
for (Matchup matchup : matchups) {
matchup.getTeam1().addCounterGoal(matchup.getGoalTeam2());
matchup.getTeam2().addCounterGoal(matchup.getGoalTeam1());
}
}
private void createTable() {
String result = "";
for (Team team : teams) {
result += "Mannschaftsname: " + team.getName() + ", Punkte: " + team.getScore() + " , Tore: " + team.getGoal() + ", Gegentore: " + team.getCounterGoal() + "\n";
}
System.out.println(result);
}
public static void main(String[] args) {
SoccerTable soccerTable = new SoccerTable();
Team arsenal = new Team("Arsenal", 1);
Team barcelona = new Team("Barcelona", 2);
Team madrid = new Team("Madrid", 3);
Matchup matchup1 = new Matchup(arsenal, barcelona);
Matchup matchup2 = new Matchup(barcelona, madrid);
matchup1.setGoalTeam1(1);
matchup1.setGoalTeam2(5);
matchup2.setGoalTeam1(5);
matchup2.setGoalTeam2(10);
List<Team> teams = Arrays.asList(arsenal, barcelona, madrid);
List<Matchup> matchups = Arrays.asList(matchup1, matchup2);
soccerTable.setTeams(teams);
soccerTable.calculateScores(matchups);
soccerTable.calculateGoals(matchups);
soccerTable.calculateCounterGoals(matchups);
teams.sort(COMPARATOR_TEAM);
soccerTable.createTable();
}
} |
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import model.Job_History;
import utils.DBConnectionUtil;
public class Job_HistoryDAO {
PreparedStatement pst;
ResultSet rs;
Statement st;
Connection conn;
public List<Job_History> findALL(String em_Id) {
List<Job_History> jList = new ArrayList<Job_History>();
final String sql ="SELECT * FROM JOB_HISTORY WHERE EMPLOYMENT_ID =? ORDER BY JOB_HISTORY_ID DESC";
conn = DBConnectionUtil.sqlConnection();
try {
pst = conn.prepareStatement(sql);
pst.setString(1, em_Id);
rs = pst.executeQuery();
while(rs.next()) {
Job_History job_History = new Job_History(rs.getInt("jOB_HISTORY_ID"), rs.getString("eMPLOYMENT_ID"), rs.getString("dEPARTMENT"), rs.getString("dIVISION"),
rs.getDate("fROM_DATE"), rs.getDate("tHRU_DATE"), rs.getString("jOB_TITLE"), rs.getString("sUPERVISOR"), rs.getString("lOCATION"), rs.getString("tYPE_OF_WORK"));
jList.add(job_History);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jList;
}
}
|
package com.nsp.test.jdk.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Test;
public class InetAddressTest
{
@Test
public void testGetHostName()
{
try
{
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(inetAddress.getCanonicalHostName());
System.out.println(inetAddress.getHostName());
System.out.println(inetAddress.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
}
}
|
package com.bit.myfood.repository;
import com.bit.myfood.model.entity.OrderDetail;
import com.bit.myfood.model.entity.OrderDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface OrderDetailRepository extends JpaRepository<OrderDetail, Long> {
Optional<OrderDetail> findById(Long id);
Optional<OrderDetail> getFirstByOrderByIdDesc();
Optional<Long> countBy();
}
|
package interfaces.interfaces;
import java.util.List;
import dto.main.Respuesta;
public interface ICrud<C, I> {
Respuesta<C> obtenerPorId(I id);
Respuesta<List<C>> obtenerTodos();
Respuesta<C> crear(C toCreate);
Respuesta<List<Respuesta<C>>> crear(Iterable<C> toCreate);
Respuesta<List<Respuesta<C>>> crear(Iterable<C> toCreate, int batchSize);
Respuesta<C> actualizar(I id, C toUpdate);
Respuesta<C> actualizar(C toUpdate);
Respuesta<Boolean> borrar(I id);
}
|
package corejava.io.files;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Configurations;
import org.apache.commons.configuration2.ex.ConfigurationException;
/**
* Created by xulz on 2017/3/11.
*/
public class PropertyReadWrite {
public void getPropValues(){
Properties prop = new Properties();
InputStream input = null;
try {
input = getClass().getResourceAsStream("/config.properties");
if (input == null){
System.out.println("Can not find property file!");
return;
}
prop.load(input);
System.out.println("Get poolSize: " + prop.getProperty("threadPoolSize"));
}
catch (Exception e){
e.printStackTrace();
}finally {
if(input != null){
try{
input.close();}
catch (IOException e){
e.printStackTrace();
}
}
}
}
public void setPropValues(){
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("abc.properties");
prop.setProperty("threadPoolSize","32");
prop.store(output,null);
System.out.println("Set Size:" + prop.getProperty("threadPoolSize"));
}
catch (Exception e){
e.printStackTrace();
}finally {
if(output != null){
try{
System.out.println("output closed");
output.close();
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
// use third library
public void getConfiguration(){
Configurations configs = new Configurations();
try
{
Configuration config = configs.properties("config.properties");
// access configuration properties
int threadPoolSize = config.getInt("threadPoolSize");
System.out.println("Configuration get poolSize:" + threadPoolSize);
}
catch (ConfigurationException cex)
{
cex.printStackTrace();
}
}
public void setConfiguration(){
Configurations configs = new Configurations();
try{
FileBasedConfigurationBuilder<PropertiesConfiguration> builder = configs.propertiesBuilder("config.properties");
PropertiesConfiguration config = builder.getConfiguration();
config.setProperty("threadPoolSize",128);
builder.save();
}
catch (ConfigurationException ce){
ce.printStackTrace();
}
}
public static void main(String[] args) {
PropertyReadWrite properties = new PropertyReadWrite();
properties.setPropValues();
properties.getPropValues();
properties.getConfiguration();
properties.setConfiguration();
}
}
|
package com.hesoyam.pharmacy.user.controller;
import com.hesoyam.pharmacy.pharmacy.model.Pharmacy;
import com.hesoyam.pharmacy.pharmacy.service.impl.PharmacyService;
import com.hesoyam.pharmacy.user.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityNotFoundException;
@RestController
@RequestMapping(value = "/administrator", produces = MediaType.APPLICATION_JSON_VALUE)
public class AdministratorController {
@Autowired
private PharmacyService pharmacyService;
@PreAuthorize("hasRole('ADMINISTRATOR')")
@GetMapping("pharmacy/id")
public ResponseEntity<Long> getPharmacyId(@AuthenticationPrincipal User user){
try {
Pharmacy pharmacy = pharmacyService.getByAdministrator(user.getId());
return ResponseEntity.status(HttpStatus.OK).body(pharmacy.getId());
} catch(EntityNotFoundException e){
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(-1L);
}
}
}
|
package lishuai.common.util;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* 获取系统的MAC地址
* @author li
*
*/
public class LocalMAC {
public static String getSystemMAC(InetAddress addr) throws SocketException{
byte[] mac=NetworkInterface.getByInetAddress(addr).getHardwareAddress();
return byte2hex(mac);
}
public static void main(String[] args) throws UnknownHostException, SocketException {
InetAddress addr=InetAddress.getLocalHost();
System.out.println(addr);
System.out.println(getSystemMAC(addr));
}
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == 1)
hs += ("0" + stmp);
else
hs += stmp;
}
return hs.toUpperCase();
}
}
|
package exercises.ella;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SideBar extends JPanel implements ActionListener, KeyListener {
JLabel barTitle = new JLabel("FIND:");
JLabel snakeName = new JLabel("snake");
JLabel ringName = new JLabel("ring");
JLabel backpackName = new JLabel("backpack");
JLabel sparklesName = new JLabel("sparkles");
JLabel pawprintsName = new JLabel("pawprints");
JLabel diamondName = new JLabel("diamond");
JLabel balloonName = new JLabel("balloon");
JLabel appleName = new JLabel("apple");
JLabel bowName = new JLabel("bow");
JLabel roseName = new JLabel("rose");
JLabel cloudName = new JLabel("cloud");
JLabel chickenName = new JLabel("chicken");
JLabel earthName = new JLabel("earth");
JLabel cactusName = new JLabel("cactus");
JLabel timeName = new JLabel("Time: 0");
int foundMeX = 76;
int foundMeWidth = 275;
int foundMeHeight = 75;
int findMeY = 90;
int findMeY2 = findMeY + 40;
int findMeY3 = findMeY + 80;
int findMeY4 = findMeY + 120;
int findMeY5 = findMeY + 160;
int findMeY6 = findMeY + 200;
int findMeY7 = findMeY + 240;
final int BAR1 = 0;
final int BAR2 = 1;
int currentBar = BAR1;
SideBar() {
setPreferredSize(new Dimension(285, 1000));
// bar.setBounds(1800, 900, 500, 500);
add(barTitle);
barTitle.setFont(new Font("Serif", Font.PLAIN, 45));
setLayout(null);
barTitle.setBounds(84, 20, 200, 100);
objectNames();
setOpaque(true);
setBackground(Color.PINK);
repaint();
}
private void ObjectInit(JLabel buttonName, int xPosition, int yPosition, int width) {
add(buttonName);
buttonName.setFont(new Font("Serif", Font.PLAIN, 30));
buttonName.setBounds(xPosition, yPosition, width, 75);}
void objectNames() {
ObjectInit(snakeName, 102, findMeY, 100);
ObjectInit(ringName, 113, findMeY2, 100);
ObjectInit(backpackName, 83, findMeY3, 275);
ObjectInit(sparklesName, 90, findMeY4, 250);
ObjectInit(pawprintsName, 83, findMeY5, 275);
ObjectInit(diamondName, 87, findMeY6, 250);
ObjectInit(balloonName, 95, findMeY7, 250);
ObjectInit(timeName, 95, 850, 250);
}
void object2Names() {
ObjectInit(appleName, 102, findMeY, 100);
ObjectInit(bowName, 109, findMeY2, 90);
ObjectInit(roseName, 110, findMeY3, 100);
ObjectInit(cloudName, 101, findMeY4, 100);
ObjectInit(chickenName, 92, findMeY5, 250);
ObjectInit(earthName, 101, findMeY6, 100);
ObjectInit(cactusName, 101, findMeY7, 100);
}
void nextLevelBar() {
currentBar += 1;
if (currentBar > BAR2) {
currentBar = BAR1;
}
if (currentBar == BAR1) {
setBackground(Color.PINK);
}
System.out.println(currentBar);
if (currentBar == 1) {
setBackground(Color.BLUE);
object2Names();
}
repaint();
}
void foundSparkles() {
sparklesName.setVisible(false);
}
void foundRing() {
ringName.setVisible(false);
}
void foundBackpack() {
backpackName.setVisible(false);
}
void foundPawprint() {
pawprintsName.setVisible(false);
}
void foundDiamond() {
diamondName.setVisible(false);
}
void foundSnake() {
snakeName.setVisible(false);
}
void foundBalloon() {
balloonName.setVisible(false);
}
void foundApple() {
appleName.setVisible(false);
}
void foundBow() {
bowName.setVisible(false);
}
void foundRose() {
roseName.setVisible(false);
}
void foundCloud() {
cloudName.setVisible(false);
}
void foundChicken() {
chickenName.setVisible(false);
}
void foundEarth() {
earthName.setVisible(false);
}
void foundCactus() {
cactusName.setVisible(false);
}
void showTime(int time) {
timeName.setText("Time: " + time);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
|
package cn.tedu.jdbc.day02;
/*
* 这个程序可以防止注入,1' or '1'='1 是不能成为万能密码的
* */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
public class Login_Update {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("username:");
String username = sc.nextLine();
System.out.println("password:");
String password = sc.nextLine();
boolean flag = login(username,password);
if(flag==true) {
System.out.println("登录成功!!!"+"Hello"+" "+username);
}else {
System.out.println("登录失败!!!");
}
}
public static boolean login(String name,String pwd) {
Connection conn = null;
try {
conn = DbUtils.getConnection();
String sql = "select count(*) as c from Login_user "
+ "where name=? and pwd=?";
System.out.println(sql);
PreparedStatement pstate = conn.prepareStatement(sql);
pstate.setString(1, name);
pstate.setString(2, pwd);
ResultSet set = pstate.executeQuery();
while(set.next()) {
int n = set.getInt("c");
return n>=1;
}
}catch(Exception ex) {
ex.printStackTrace();
throw new RuntimeException();
}finally {
DbUtils.close(conn);
}
return false;
}
}
|
package com.ntxdev.zuptecnico.util;
import android.content.Context;
import android.os.Environment;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.File;
import okio.BufferedSink;
import okio.Okio;
public class FileUtils {
public static boolean imageExists(Context context, String filename) {
File imagesFolder = getImagesFolder(context);
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
return new File(imagesFolder, filename).exists();
}
public static boolean imageExists(Context context, String subfolder, String filename) {
File imagesFolder = getImagesFolder(context, subfolder);
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
return new File(imagesFolder, filename).exists();
}
public static File getImagesFolder(Context context) {
return new File(context.getFilesDir() + File.separator + "images" + File.separator + "images");
}
public static File getImagesFolder(Context context, String subfolder) {
return new File(context.getFilesDir() + File.separator + "images" + File.separator + "images" + File.separator + subfolder);
}
public static File getTempImagesFolder() {
File imagesFolder = new File(Environment.getExternalStorageDirectory() + File.separator + "ZUP" + File.separator + "temp");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
return imagesFolder;
}
}
|
/**
*
*/
package com.wonders.task.contractReview.service.impl;
import com.wonders.schedule.util.DbUtil;
import com.wonders.task.contractReview.model.bo.PAttach;
import com.wonders.task.contractReview.model.bo.PContract;
import com.wonders.task.contractReview.model.vo.CompanyRoute;
import com.wonders.task.contractReview.service.ContractReviewService;
import com.wonders.task.contractReview.util.ContractReviewUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zhoushun
* @ClassName: ContractReviewServiceImpl
* @Description: TODO(这里用一句话描述这个类的作用)
* @date 2014年1月21日 下午12:06:54
*/
@Service("contractReviewService")
@Transactional(value = "dsTransactionManager2", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ContractReviewServiceImpl implements ContractReviewService {
@Override
public Map<String, CompanyRoute> getLine() {
String sql = "select object_name lineName,id lineId,unitName,unitId" +
" from C_COMPANY_ROUTE c" +
" left join (select s.object_name unitName, s.id unitId" +
" from C_COMPANY_ROUTE s" +
" where s.id <> '01'" +
" and s.removed = '0' and s.type='1') on unitId = c.pid" +
" where c.pid <> '01'" +
" and c.removed = '0' ";
List<CompanyRoute> companyRouteList = DbUtil.getJdbcTemplate("stptdemo").query(sql, new BeanPropertyRowMapper(CompanyRoute.class));
HashMap<String, CompanyRoute> result = new HashMap<String, CompanyRoute>();
for (CompanyRoute companyRoute : companyRouteList) {
if (companyRoute.getLineName().equals("8号线三期")&&companyRoute.getUnitId().equals("113")) {
result.put(companyRoute.getLineName(), companyRoute);
} else if (companyRoute.getLineName().equals("5号线南延伸")&&companyRoute.getUnitId().equals("112")) {
result.put(companyRoute.getLineName(), companyRoute);
}else if (companyRoute.getLineName().equals("14号线")&&companyRoute.getUnitId().equals("114")) {
result.put(companyRoute.getLineName(), companyRoute);
}else if(!companyRoute.getLineName().equals("8号线三期")&&!companyRoute.getLineName().equals("5号线南延伸")&&!companyRoute.getLineName().equals("14号线"))
result.put(companyRoute.getLineName(), companyRoute);
}
return result;
}
@Override
public Map<String, CompanyRoute> getCompany() {
String sql = "select id unitId,object_name unitName from C_COMPANY_ROUTE where type=? and removed = ?";
List<CompanyRoute> companyRouteList = DbUtil.getJdbcTemplate("stptdemo").query(sql, new Object[]{"1", "0"}, new BeanPropertyRowMapper(CompanyRoute.class));
HashMap<String, CompanyRoute> result = new HashMap<String, CompanyRoute>();
for (CompanyRoute companyRoute : companyRouteList) {
result.put(companyRoute.getUnitName(), companyRoute);
}
return result;
}
@Override
public Map getCorporation() {
String sql = "select company_name_chn,max(comp_id) comp_id from ps_corporation group by company_name_chn";
List<Map<String,Object>> result = DbUtil.getJdbcTemplate("stptdemo").queryForList(sql);
HashMap<String, String> mapResult = new HashMap<String, String>();
for (Map<String,Object> map : result) {
mapResult.put((String)map.get("company_name_chn"), ((BigDecimal)map.get("comp_id")).intValue()+"");
}
return mapResult;
}
@Override
public Map<String, String> getDept() {
String sql = "select name,max(id) id from c_dept_tree group by name";
List<Map<String,Object>> result = DbUtil.getJdbcTemplate("stptdemo").queryForList(sql);
HashMap<String, String> mapResult = new HashMap<String, String>();
for (Map<String,Object> map : result) {
mapResult.put((String)map.get("name"), ((String)map.get("id")));
}
return mapResult;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public List<PContract> getInfo() {
String sql = "select t.project_id projectId,"
+ " t.contract_type1_id||','||t.contract_type2_id contractType,"
+ " t.contract_group_id contractGrouping,"
+ " t.purchase_type_id inviteBidType,"
+ " t.project_name projectName,"
+ " t.project_identifier projectNo,"
+ " t.contract_identifier contractNo,"
+ " t.contract_self_num selfNo,"
+ " t.contract_name contractName,"
+ " t.contract_money contractPrice,"
+ " t.contract_money_type payType,"
+ " t.opposite_company buildSupplierName,"
+ " t.reg_person registerPersonName,"
+ " replace(t.reg_login_name,'ST/','') registerPersonLoginName,"
+ " t.reg_time createDate,"
+ " t.pass_time contractPassedDate,"
+ " t.sign_time contractSignedDate,"
+ " t.exec_period_start contractStartDate,"
+ " t.exec_period_end contractEndDate,"
+ " t.remark remark,"
+ " t.attach contractAttachMent,"
+ " t.project_charge_dept contractOwnerExecuteName,"
+ " t.money_source contractOwnerName,"
+ " t.budget_type budgetType,"
+ " t.budget_type_code budgetTypeCode,"
+ " t.stat_type statType"
+ " from t_contract_review t "
+ " where t.operate_time < to_char(sysdate,'yyyy-mm-dd')"
+ " and t.operate_time >= to_char(sysdate-1,'yyyy-mm-dd')"
+ " and t.removed=0 and t.flag = '1'";
List<PContract> list = DbUtil.getJdbcTemplate("stptinc").
query(sql, new BeanPropertyRowMapper(PContract.class));
return list;
}
public List<PAttach> getAttachInfo(String groupId) {
String url = ContractReviewUtil.url;
String sql = "select "
+ " t.filename,"
+ " t.fileextname,"
+ " t.filesize,"
+ " case when instr(t.path,'http')>0 then path else ? || id end path,"
+ " '' savefilename,"
+ " t.operate_time operateTime, "
+ " t.uploaddate,t.uploader,"
+ " t.uploader_login_name uploaderLoginName from t_attach t "
+ " where t.groupid=? and t.removed =0 ";
@SuppressWarnings({"unchecked", "rawtypes"})
List<PAttach> list = DbUtil.getJdbcTemplate("stptinc").
query(sql, new Object[]{url, groupId}, new BeanPropertyRowMapper(PAttach.class));
return list;
}
}
|
/*
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
*/
class Solution {
public int minCut(String s) {
int n = s.length();
char[] sc = s.toCharArray();
int[] dp = new int[n];
boolean[][] isPalidrome = new boolean[n][n];
for (int i = 0; i < n; i++) {
int min = i;
for (int j = 0; j <= i; j++) {
if (sc[i] == sc[j] && (j >= i - 1 || isPalidrome[j + 1][i - 1])) {
min = j == 0 ? 0 : Math.min(dp[j - 1] + 1, min);
isPalidrome[j][i] = true;
}
}
dp[i] = min;
}
return dp[n - 1];
}
}
|
package com.zhowin.miyou.recommend.fragment;
import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.Fragment;
import com.gyf.immersionbar.ImmersionBar;
import com.zhowin.base_library.adapter.HomePageAdapter;
import com.zhowin.base_library.utils.ConstantValue;
import com.zhowin.miyou.R;
import com.zhowin.miyou.base.BaseBindFragment;
import com.zhowin.miyou.databinding.IncludeCharmListFragmentBinding;
import java.util.ArrayList;
import java.util.List;
/**
* author : zho
* date :2020/9/17
* desc : 贡献榜单 / 魅力榜单
*/
public class CharmListFragment extends BaseBindFragment<IncludeCharmListFragmentBinding> {
private String[] titles = {"贡献榜", "魅力榜"};
private List<Fragment> mFragments = new ArrayList<>();
private int roomID,fragmentIndex;
public static CharmListFragment newInstance(int roomId,int index) {
CharmListFragment fragment = new CharmListFragment();
Bundle bundle = new Bundle();
bundle.putInt(ConstantValue.ID, index);
bundle.putInt(ConstantValue.INDEX, index);
fragment.setArguments(bundle);
return fragment;
}
@Override
public int getLayoutId() {
return R.layout.include_charm_list_fragment;
}
@Override
public void initView() {
roomID = getArguments().getInt(ConstantValue.ID);
fragmentIndex = getArguments().getInt(ConstantValue.INDEX);
Log.e("xy", "fragmentIndex:" + fragmentIndex);
}
@Override
public void initData() {
for (int i = 0; i < titles.length; i++) {
mFragments.add(CharmInformationFragment.newInstance(roomID,fragmentIndex, i));
}
HomePageAdapter homePageAdapter = new HomePageAdapter(getChildFragmentManager(), mFragments, titles);
mBinding.noScrollViewPager.setAdapter(homePageAdapter);
mBinding.noScrollViewPager.setScroll(true);
mBinding.segmentTabLayout.setTabData(titles);
}
@Override
public void initImmersionBar() {
ImmersionBar.with(this)
.fitsSystemWindows(true) //使用该属性,必须指定状态栏颜色
.statusBarColor(R.color.color_8234FC)
.keyboardEnable(true)
.statusBarDarkFont(true, 0f)
.init();
}
}
|
package com.tencent.mm.ar;
import android.content.ContentValues;
import android.database.Cursor;
public final class m {
private String bNH = (this.id + "_" + this.bPh);
public int bPh = 0;
int bWA = -1;
private String dHL = "";
private String dHM = "";
private int dHN = 0;
private int dHO = 0;
String ecV = "";
public int id = 0;
String name = "";
int size = 0;
public int status = 0;
public int version = 0;
public final void d(Cursor cursor) {
this.version = cursor.getInt(2);
this.name = cursor.getString(3);
this.size = cursor.getInt(4);
this.ecV = cursor.getString(5);
this.status = cursor.getInt(6);
this.dHL = cursor.getString(8);
this.dHM = cursor.getString(9);
this.bPh = cursor.getInt(7);
this.dHO = cursor.getInt(11);
this.id = cursor.getInt(1);
this.dHN = cursor.getInt(10);
this.bNH = cursor.getString(0);
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if ((this.bWA & 2) != 0) {
contentValues.put("id", Integer.valueOf(this.id));
}
if ((this.bWA & 4) != 0) {
contentValues.put("version", Integer.valueOf(this.version));
}
if ((this.bWA & 8) != 0) {
contentValues.put("name", this.name == null ? "" : this.name);
}
if ((this.bWA & 16) != 0) {
contentValues.put("size", Integer.valueOf(this.size));
}
if ((this.bWA & 32) != 0) {
contentValues.put("packname", Ql());
}
if ((this.bWA & 64) != 0) {
contentValues.put("status", Integer.valueOf(this.status));
}
if ((this.bWA & 128) != 0) {
contentValues.put("type", Integer.valueOf(this.bPh));
}
if ((this.bWA & 256) != 0) {
contentValues.put("reserved1", this.dHL == null ? "" : this.dHL);
}
if ((this.bWA & 512) != 0) {
contentValues.put("reserved2", this.dHM == null ? "" : this.dHM);
}
if ((this.bWA & 1024) != 0) {
contentValues.put("reserved3", Integer.valueOf(this.dHN));
}
if ((this.bWA & 2048) != 0) {
contentValues.put("reserved4", Integer.valueOf(this.dHO));
}
if ((this.bWA & 1) != 0) {
contentValues.put("localId", this.id + "_" + this.bPh);
}
return contentValues;
}
public final String Ql() {
return this.ecV == null ? "" : this.ecV;
}
}
|
package com.project.services;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.project.model.Cv;
import com.project.model.Education;
import com.project.model.Experience;
import com.project.model.Language;
import com.project.model.Skill;
import com.project.repository.CvRepository;
import com.project.repository.EducationRepository;
import com.project.repository.ExperienceRepository;
import com.project.repository.LanguageRepository;
import com.project.repository.SkillRepository;
@Service
public class CvServiceImpl implements CvService {
@Autowired
private CvRepository cvRepo;
@Autowired
private EducationRepository educationRepo;
@Autowired
private LanguageRepository languageRepo;
@Autowired
private ExperienceRepository experienceRepository;
@Autowired
private SkillRepository skillRepository;
@Override
public Cv save(Cv cv) {
return cvRepo.save(cv);
}
@Override
public List<Cv> getAll() {
return cvRepo.findAll();
}
@Override
public Document generatePdf(Cv cv) {
Document document = new Document();
try {
String filePath = cv.getUser().getName() + "_" + cv.getId() + ".pdf";
FileOutputStream pdfFile = new FileOutputStream("C:\\Users\\Sabina\\Desktop\\" + filePath);
PdfWriter.getInstance(document, pdfFile);
document.open();
// title
Paragraph title = new Paragraph();
Font romanianTitleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
Paragraph titleRomanian = new Paragraph(cv.getUser().getName() + "\n" + "(" + dateFormat.format(date) + ")",
romanianTitleFont);
titleRomanian.setAlignment(Paragraph.ALIGN_RIGHT);
title.add(titleRomanian);
document.add(title);
document.add(new Paragraph("\n"));
document.add(new Paragraph("\n"));
// line
Paragraph line = new Paragraph(
"---------------------------------------------------------------------------------------------------------------------");
document.add(line);
// Info
Font infoFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Paragraph INFO = new Paragraph("INFO ", infoFont);
Paragraph infoAddress = new Paragraph("Address: " + cv.getUser().getAddress());
Paragraph infoPhone = new Paragraph("Phone: " + cv.getUser().getPhone());
Paragraph infoName = new Paragraph("Email: " + cv.getUser().getEmail());
Paragraph infoBirth = new Paragraph("Born: " + cv.getUser().getBirthDate());
Paragraph infoJob = new Paragraph("Proffesion: " + cv.getUser().getProffesion());
document.add(INFO);
document.add(infoAddress);
document.add(infoPhone);
document.add(infoName);
document.add(infoBirth);
document.add(infoJob);
document.add(new Paragraph("\n"));
Paragraph EDUCATION = new Paragraph("EDUCATION ", infoFont);
document.add(line);
document.add(EDUCATION);
List<Education> educations = educationRepo.findAll();
Paragraph educationParagraph;
for (Education education : educations) {
if (cv.getId().equals(education.getCv().getId())) {
educationParagraph = new Paragraph(education.getName() + "\t BEGIN: " + education.getStartDate()
+ "\t END: " + education.getEndDate());
document.add(educationParagraph);
}
}
Paragraph LANGUAGES = new Paragraph("LANGUAGES ", infoFont);
document.add(line);
document.add(LANGUAGES);
List<Language> languages = languageRepo.findAll();
Paragraph laguageParagraph;
for (Language language : languages) {
if (cv.getId().equals(language.getCv().getId())) {
laguageParagraph = new Paragraph(language.getName() + "\t QUALIFIER: " + language.getQualifier());
document.add(laguageParagraph);
}
}
Paragraph EXPERIENCE = new Paragraph("EXPERIENCE ", infoFont);
document.add(line);
document.add(EXPERIENCE);
List<Experience> experiences = experienceRepository.findAll();
Paragraph experienceParagraph;
for (Experience experience : experiences) {
if (cv.getId().equals(experience.getCv().getId())) {
experienceParagraph = new Paragraph(experience.getName() + "\t BEGIN: " + experience.getStartDate()
+ "\t END: " + experience.getEndDate());
document.add(experienceParagraph);
}
}
Paragraph SKILLS = new Paragraph("SKILLS ", infoFont);
document.add(line);
document.add(SKILLS);
List<Skill> skills = skillRepository.findAll();
Paragraph skillParagraph;
for (Skill skill : skills) {
if (cv.getId().equals(skill.getCv().getId())) {
skillParagraph = new Paragraph(skill.getName() + "\t QUALIFIER: " + skill.getQualifier());
document.add(skillParagraph);
}
}
Paragraph OTHER = new Paragraph("OTHER QUALIFICATIONS ", infoFont);
document.add(line);
document.add(OTHER);
Paragraph other = new Paragraph(cv.getOtherQualifications());
document.add(other);
Paragraph DESCRIPTION = new Paragraph("PERSONAL DESCRIPTION ", infoFont);
document.add(line);
document.add(DESCRIPTION);
Paragraph description = new Paragraph(cv.getPersonalDescription());
document.add(description);
cv.setPath("C:\\Users\\Sabina\\Desktop\\" + filePath);
cvRepo.save(cv);
sendCvOnEmail(cv.getUser().getEmail(), cv);
} catch (DocumentException | IOException | MessagingException e) {
e.printStackTrace();
} finally {
document.close();
try {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + cv.getPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return document;
}
@Override
public void showPdf(Cv cv) {
try {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + cv.getPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void delete(Cv cv) {
List<Language> languages = languageRepo.findAll();
for (Language language : languages) {
if (cv.getId().equals(language.getCv().getId())) {
languageRepo.delete(language);
}
}
List<Education> educations = educationRepo.findAll();
for (Education education : educations) {
if (cv.getId().equals(education.getCv().getId())) {
educationRepo.delete(education);
}
}
List<Experience> experiences = experienceRepository.findAll();
for (Experience experience : experiences) {
if (cv.getId().equals(experience.getCv().getId())) {
experienceRepository.delete(experience);
}
}
List<Skill> skills = skillRepository.findAll();
for (Skill skill : skills) {
if (cv.getId().equals(skill.getCv().getId())) {
skillRepository.delete(skill);
}
}
cvRepo.delete(cv);
}
private void sendCvOnEmail(String email, Cv cv) throws AddressException, MessagingException {
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.mailtrap.io");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "smtp.mailtrap.io");
Session session = Session.getInstance(prop, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("lazareanu_sabina@yahoo.com", "nasturel1*");
}
});
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("lazareanu_sabina@yahoo.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
message.setSubject("Mail Subject");
String msg = "This is my first email using JavaMailer";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
// String to = "lazareanu_sabina@yahoo.com";// change accordingly
// String from = "lazareanusabina@gmail.com";
// String host = "localhost";// or IP address
//
// // Get the session object
// Properties properties = System.getProperties();
// properties.setProperty("mail.smtp.host", host);
// Session session = Session.getDefaultInstance(properties);
//
// // compose the message
// try {
// MimeMessage message = new MimeMessage(session);
// message.setFrom(new InternetAddress(from));
// message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// message.setSubject("Ping");
// message.setText("Hello, this is example of sending email ");
//
// // Send message
// Transport.send(message);
// System.out.println("message sent successfully....");
//
// } catch (MessagingException mex) {
// mex.printStackTrace();
// }
}
}
|
package wrapper;
import java.util.Date;
/*
* Class which represents information about drivers and their availability.
* It also allows the application to get and set the number of hours a
* driver has worked over time periods of a week or a year, and the
* holidays taken by a driver in the current calendar year.<br><br>
*
* As well as an ID, drivers (like buses) have numbers which are traditionally
* used to identify them. You can also get the name of a specified driver<br><br>
*
* The methods contain checks for invalid queries, which will result in
* InvalidQueryExceptions being thrown, but it does not enforce "business
* rules" such as checking for dates in the past.
*/
public class SoldItem
{
// This class is not intended to be instantiated
private SoldItem()
{
}
/*
* Get the IDs of all the drivers in the database
*/
public static int[] getItems()
{
return database.busDatabase.select_ids("solds_id", "sold", "sold_id");
}
public static int[] getItemsbyDate()
{
return database.busDatabase.select_ids("solds_id", "solds", "date");
}
/*
* Find the driver with the specified driver number
*/
public static int findDriver(String number)
{
return database.busDatabase.find_id("driver", "number", number);
}
/*
* Get the real name of a driver
*/
public static String getName(int solds)
{
if (solds == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_string("solds", solds, "name");
}
/*
* Get the number of days holiday taken, or planned to be taken, in the
* current calendar year
*/
public static Double getItemsPrice(int solds)
{
if (solds == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_float("solds",solds, "price");
}
public static int getItemsClearStatus(int item)
{
if (item == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_int("items", item, "clear");
}
/*
* Set the number of days holiday taken, or planned to be taken, in
* the current calendar year.
*/
public static void setItemsPrice(int item, int value)
{
if (item == 0) throw new InvalidQueryException("Nonexistent driver");
database.busDatabase.set_value("solds", item, "price", value);
}
public static int getItemsQuantity(int solds)
{
if (solds == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_int("solds", solds, "quantity");
}
public static int getItemsID(int item)
{
if (item == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_int("solds", item, "items_id");
}
public static Date getSoldsDate(int solds)
{
if (solds == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_date("solds", solds, "date");
}
/*
* Set the number of days holiday taken, or planned to be taken, in
* the current calendar year.
*/
public static void setItemsQuantity(int item, int value)
{
if (item == 0) throw new InvalidQueryException("Nonexistent driver");
database.busDatabase.set_value("items", item, "quantity", value);
}
public static void setItemsClearStatus(int item, int value)
{
if (item == 0) throw new InvalidQueryException("Nonexistent driver");
database.busDatabase.set_value("items", item, "clear", value);
}
/*
* Get the identification number of a driver
*/
public static String getNumber(int driver)
{
if (driver == 0) throw new InvalidQueryException("Nonexistent driver");
return database.busDatabase.get_string("driver", driver, "number");
}
/*
* Determine whether a driver is available on a given date
*/
public static boolean isAvailable(int driver, Date date)
{
if (date == null)
throw new InvalidQueryException("Date is null");
if (driver == 0)
throw new InvalidQueryException("Nonexistent driver");
database db = database.busDatabase;
if (db.select_record("driver_availability", "driver", driver, "day", date))
return (Integer)db.get_field("available") != 0;
else
return true;
}
/*
* Determine whether a driver is available today
*/
public static boolean isAvailable(int driver)
{
return isAvailable(driver, database.today());
}
/*
* Set whether a driver is available on a given date
*/
public static void addItem(String name,int item ,double price, int quantity, Date date)
{
database.busDatabase.new_record("solds", new Object[][]{{"items_id", item},{"name", name}, {"quantity", quantity},
{"price", price},{"date", date}});
}//setAvailable
public static void addItem( String name, double price,int quantity)
{
database.busDatabase.new_record("solds", new Object[][]{{"name", name}, {"quantity", quantity},
{"price", price}});
}//setAvailable
public static void deleteSold(int solds)
{
if (solds == 0) throw new InvalidQueryException( " does not exist");
database.busDatabase.delete_record("solds", "solds_id", solds);
}
/*
* Set whether a driver is available today
*/
}//class
|
/*
* Copyright 2014, Stratio.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stratio.cassandra.index.schema.mapping;
import com.stratio.cassandra.index.schema.Schema;
import org.apache.lucene.document.Field;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class ColumnMapperDoubleTest {
@Test()
public void testValueNull() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", null);
Assert.assertNull(parsed);
}
@Test
public void testValueInteger() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3);
Assert.assertEquals(Double.valueOf(3), parsed);
}
@Test
public void testValueLong() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3l);
Assert.assertEquals(Double.valueOf(3), parsed);
}
@Test
public void testValueFloatWithoutDecimal() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3f);
Assert.assertEquals(Double.valueOf(3), parsed);
}
@Test
public void testValueFloatWithDecimalFloor() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3.5f);
Assert.assertEquals(Double.valueOf(3.5d), parsed);
}
@Test
public void testValueFloatWithDecimalCeil() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3.6f);
Assert.assertEquals(Double.valueOf(3.6f), parsed);
}
@Test
public void testValueDoubleWithoutDecimal() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3d);
Assert.assertEquals(Double.valueOf(3), parsed);
}
@Test
public void testValueDoubleWithDecimalFloor() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3.5d);
Assert.assertEquals(Double.valueOf(3.5d), parsed);
}
@Test
public void testValueDoubleWithDecimalCeil() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", 3.6d);
Assert.assertEquals(Double.valueOf(3.6d), parsed);
}
@Test
public void testValueStringWithoutDecimal() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", "3");
Assert.assertEquals(Double.valueOf(3), parsed);
}
@Test
public void testValueStringWithDecimalFloor() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", "3.2");
Assert.assertEquals(Double.valueOf(3.2d), parsed);
}
@Test
public void testValueStringWithDecimalCeil() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Double parsed = mapper.indexValue("test", "3.6");
Assert.assertEquals(Double.valueOf(3.6d), parsed);
}
@Test
public void testField() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
Field field = mapper.field("name", "3.2");
Assert.assertNotNull(field);
Assert.assertEquals(3.2d, field.numericValue());
Assert.assertEquals("name", field.name());
Assert.assertEquals(false, field.fieldType().stored());
}
@Test
public void testExtractAnalyzers() {
ColumnMapperDouble mapper = new ColumnMapperDouble(1f);
String analyzer = mapper.analyzer();
Assert.assertEquals(ColumnMapper.KEYWORD_ANALYZER, analyzer);
}
@Test
public void testParseJSON() throws IOException {
String json = "{fields:{age:{type:\"double\"}}}";
Schema schema = Schema.fromJson(json);
ColumnMapper columnMapper = schema.getMapper("age");
Assert.assertNotNull(columnMapper);
Assert.assertEquals(ColumnMapperDouble.class, columnMapper.getClass());
}
@Test
public void testParseJSONEmpty() throws IOException {
String json = "{fields:{}}";
Schema schema = Schema.fromJson(json);
ColumnMapper columnMapper = schema.getMapper("age");
Assert.assertNull(columnMapper);
}
@Test(expected = IOException.class)
public void testParseJSONInvalid() throws IOException {
String json = "{fields:{age:{}}";
Schema.fromJson(json);
}
}
|
package com.study.collura.objectboxstudy.mvp.base;
import com.study.collura.objectboxstudy.mvp.data.AppDataManager;
public abstract class BaseHelper {
private AppDataManager dataManager;
public BaseHelper (AppDataManager dataManager) {
this.dataManager = dataManager;
}
} |
package com.travel.services;
import java.util.List;
import com.travel.models.Trip;
public interface TripService {
void save(Trip trip);
Trip findById(Long id);
List<Trip> findAll();
List<Trip> findByOrganizerId(Long id);
void deleteById(Long id);
void merge(Long id, Long mergedId);
} |
package game.app.services.impl;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import game.app.dtos.request.GameDto;
import game.app.dtos.response.GameResponse;
import game.app.entities.Game;
import game.app.exceptions.GameKONotFoundException;
import game.app.helper.GameHelper;
import game.app.repositories.GameRepository;
import game.app.services.GameService;
@Service
@Transactional
public class GameServiceImpl implements GameService{
@Autowired
private GameRepository gameRepository;
@Autowired
private GameHelper gameHelper;
@Autowired
private ConversionService converter;
//PARA GUARDAR EL JUEGO EN LA BBDD
@Override
public GameResponse addGame(GameDto gameDto) {
System.out.println("Añadiendo juego a la bbdd");
//Game game = GameConverter.dtoToEntity(gameDto);
Game gameNew = gameHelper.convertGameRequestToGame(gameDto);
Optional<Game> updatedGame = gameRepository.findByTitle(gameDto.getTitle());
if(updatedGame.isPresent()) {
Game game = gameRepository.saveAndFlush(updatedGame.get());
System.out.println(game.getTitle());
return new GameResponse();
}
gameRepository.save(gameNew);
return new GameResponse();
}
//PARA BUSCAR EL JUEGO POR TITULO
@Override
public GameResponse getGame(String title) {
Optional<Game> game = gameRepository.findByTitle(title);
//GameDto gameRequest = GameConverter.entityToDto(game.get());
if(game.isPresent()) {
return converter.convert(game.get(),GameResponse.class);
}
else {
throw new GameKONotFoundException();
}
//return gameRequest;
}
//PARA ELIMINAR UN JUEGO
@Override
public GameResponse deleteGame(String title) {
System.out.println("Eliminando juego de la bbdd");
Optional<Game> game = gameRepository.findByTitle(title);
if(game.isPresent()) {
gameRepository.deleteByTitle(title);
}
else {
throw new GameKONotFoundException();
}
System.out.println("Juego eliminado con exito de la bbdd");
return converter.convert(game.get(),GameResponse.class);
}
//METODO PARA ACTUALIZAR UN JUEGO
@Override
public GameResponse updateGame(GameDto gameDto) {
System.out.println("Actualizado juego de la bbdd");
//Game game = gameHelper.convertGameRequestToGame(gameDto);
Optional<Game> updatedGame = gameRepository.findByTitle(gameDto.getTitle());
System.out.println(updatedGame.get().getTitle());
updatedGame.get().setPrice(gameDto.getPrice());
updatedGame.get().setDescription(gameDto.getDescription());
updatedGame.get().setRelease(gameDto.getRelease());
Game game = gameRepository.saveAndFlush(updatedGame.get());
System.out.println(game.getDescription());
System.out.println("Juego actualizado con exito en la bbdd");
return new GameResponse();
}
//OTRAS PRUEBAS
// @Override
// public Game updateGame(GameDto gameDto) {
// Game game = gameHelper.convertGameRequestToGame(gameDto);
// return gameRepository.save(game);
// }
// }
//
/*
//ANTES DE CREACION DE REPOSITORIO Y CONVERTER
//lista para guardar los juegos con post
List<GameDto> gameList = new ArrayList<>();
@Override
public void addGame(GameDto gameDto) {
gameList.add(gameDto);
}
@Override
public GameDto getGame(String title) {
Optional<GameDto> gameDto = gameList.stream().filter(g-> g.getTitle().equals(title)).findAny();
return gameHelper.checkIfExists(gameDto);
}
*/
}
|
package exercice1;
/**
* Exceptions for TODOList: bad commands management
* @author Thomas COTTIN
*/
@SuppressWarnings("serial")
public class TODOListSaisirException extends Exception{
private String command;
public TODOListSaisirException(String command){
super();
this.command = command;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append("\n");
sb.append("Tried to perform the following command: \t"+command).append("\n");
sb.append("Correct commands are : \n");
sb.append("- add [your task] \t adds the task to the list\n");
sb.append("- list \t\t\t lists the advailable tasks\n");
sb.append("- first \t\t starts the first task (prints it and removes it form the list)\n");
sb.append("- last \t\t\t starts the last task (prints it and removes it form the list)\n");
return sb.toString();
}
}
|
package com.selesgames.weave.ui.main;
import javax.inject.Inject;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.InjectView;
import com.selesgames.weave.ForActivity;
import com.selesgames.weave.R;
import com.selesgames.weave.WeavePrefs;
import com.selesgames.weave.model.Feed;
import com.selesgames.weave.model.News;
import com.selesgames.weave.ui.BaseFragment;
import com.squareup.picasso.Picasso;
public class NewsFragment extends BaseFragment {
private static final String KEY_FEED = "feed";
private static final String KEY_NEWS = "news";
public static NewsFragment newInstance(Feed feed, News news) {
Bundle b = new Bundle();
b.putParcelable(KEY_FEED, feed);
b.putParcelable(KEY_NEWS, news);
NewsFragment f = new NewsFragment();
f.setArguments(b);
return f;
}
@Inject
@ForActivity
Context mContext;
@Inject
NewsController mController;
@Inject
WeavePrefs mPrefs;
@Inject
Picasso mPicasso;
@InjectView(R.id.progress)
ProgressBar mProgress;
@InjectView(R.id.title)
TextView mTitle;
@InjectView(R.id.source)
TextView mSource;
@InjectView(R.id.time)
TextView mTime;
@InjectView(R.id.image)
ImageView mImage;
private Feed mFeed;
private News mNews;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getArguments();
mFeed = b.getParcelable(KEY_FEED);
mNews = b.getParcelable(KEY_NEWS);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_news, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTitle.setText(mNews.getTitle());
mSource.setText(mFeed.getName());
long date = mNews.getOriginalDownloadDateTime().getTime();
CharSequence time = DateUtils.getRelativeTimeSpanString(mContext, date, true);
mTime.setText(time);
String imageUrl = mNews.getImageUrl();
if (TextUtils.isEmpty(imageUrl)) {
mImage.setVisibility(View.GONE);
} else {
mImage.setVisibility(View.VISIBLE);
mPicasso.load(imageUrl).fit().centerCrop().into(mImage);
}
getView().setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mController.onNewsSelected(mFeed, mNews);
}
});
}
}
|
package org.ubiquity.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Ignores a property for copy.
* This annotation can be used either on getter or on setter, with same effect.
*
* Date: 16/04/12
*
* @author François LAROCHE
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface CopyIgnore {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.