text
stringlengths 10
2.72M
|
|---|
package com.primersql;
import java.sql.*;
/**
*
* @author Israel Sanchez Aguilar
*/
public class testMySqlJDBC {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/test?useSSL=false"
+ "&useTimezone=true=&serverTimezone=UTC&allowPublicKeyRetrieval=true";
try {
//Class.forName("com.mysql.cj.jdbc.Driver");
Connection conexion = DriverManager.getConnection(url, "root", "OnePiece");
Statement instruccion = conexion.createStatement();
String sql = "SELECT id_persona, nombre, apellido, email, telefono FROM persona";
ResultSet resultado = instruccion.executeQuery(sql);
while (resultado.next()) {
System.out.println("Id persona: " + resultado.getInt("id_persona"));
}
resultado.close();
instruccion.close();
conexion.close();
} /*catch (ClassNotFoundException ex) {
ex.printStackTrace(System.out);
} */ catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
}
|
package com.tencent.mm.ui.chatting.viewitems;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.util.SparseArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.model.au;
import com.tencent.mm.modelvideo.o;
import com.tencent.mm.modelvideo.r;
import com.tencent.mm.modelvideo.s;
import com.tencent.mm.modelvideo.s$a;
import com.tencent.mm.modelvideo.s$a.b;
import com.tencent.mm.modelvideo.t;
import com.tencent.mm.platformtools.ai;
import com.tencent.mm.plugin.appbrand.jsapi.bh;
import com.tencent.mm.plugin.game.f$k;
import com.tencent.mm.pluginsdk.model.j;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.c;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bd;
import com.tencent.mm.ui.chatting.b.b.g;
import com.tencent.mm.ui.chatting.viewitems.ai.e;
import com.tencent.mm.ui.chatting.viewitems.b.a;
import com.tencent.mm.ui.widget.MMPinProgressBtn;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class ai$d extends a {
private static Map<String, WeakReference<ai$d>> ubi = new HashMap();
private static SparseArray<String> ueB = new SparseArray();
TextView mfT;
ImageView nEI;
ImageView tZR;
ImageView tZS;
TextView tZU;
ImageView uai;
ImageView ube;
ImageView udn;
View ueA;
TextView uew;
MMPinProgressBtn uex;
View uey;
ProgressBar uez;
public static boolean b(s$a.a aVar) {
if (aVar.eoc != b.eoh) {
return false;
}
r nW = t.nW(aVar.fileName);
if (nW == null) {
x.w("MicroMsg.VideoItemHoder", "update status, filename %s, videoInfo not found", new Object[]{aVar.fileName});
return false;
} else if (nW.status != 112 && nW.status != 104 && nW.status != 103) {
return false;
} else {
ah.A(new 1(nW));
return true;
}
}
public final a q(View view, boolean z) {
ImageView imageView;
ProgressBar progressBar;
View view2 = null;
super.dx(view);
this.hrs = (TextView) view.findViewById(R.h.chatting_time_tv);
this.ube = (ImageView) view.findViewById(R.h.chatting_content_iv);
this.mQc = (TextView) view.findViewById(R.h.chatting_user_tv);
this.mfT = (TextView) view.findViewById(R.h.chatting_size_iv);
this.uew = (TextView) view.findViewById(R.h.chatting_length_iv);
this.nEI = (ImageView) view.findViewById(R.h.chatting_status_btn);
this.tZR = (ImageView) view.findViewById(R.h.chatting_continue_btn);
this.tZS = (ImageView) view.findViewById(R.h.chatting_stop_btn);
this.uex = (MMPinProgressBtn) view.findViewById(R.h.chatting_download_progress);
this.uey = view.findViewById(R.h.chatting_video_data_area);
this.hrH = view.findViewById(R.h.chatting_click_area);
this.tZU = (TextView) view.findViewById(R.h.chatting_appmsg_comment_tv);
this.jBR = (CheckBox) view.findViewById(R.h.chatting_checkbox);
this.gFD = view.findViewById(R.h.chatting_maskview);
this.udn = (ImageView) view.findViewById(R.h.chatting_content_mask_iv);
if (z) {
imageView = null;
} else {
imageView = (ImageView) view.findViewById(R.h.chatting_status_tick);
}
this.uai = imageView;
if (z) {
progressBar = null;
} else {
progressBar = (ProgressBar) view.findViewById(R.h.chatting_video_pb);
}
this.uez = progressBar;
if (!z) {
view2 = view.findViewById(R.h.uploading_view);
}
this.ueA = view2;
return this;
}
public static void a(ai$d ai_d, bd bdVar, boolean z, int i, com.tencent.mm.ui.chatting.c.a aVar, int i2, OnClickListener onClickListener, OnLongClickListener onLongClickListener) {
int fromDPToPix;
String str = (String) ueB.get(ai_d.hashCode());
if (str != null) {
ubi.remove(str);
}
ueB.put(ai_d.hashCode(), bdVar.field_imgPath);
ubi.put(bdVar.field_imgPath, new WeakReference(ai_d));
r nW = t.nW(bdVar.field_imgPath);
if (nW == null) {
nW = new r();
}
o.Ta();
Bitmap a = com.tencent.mm.ak.o.Pf().a(s.nL(bdVar.field_imgPath), com.tencent.mm.bp.a.getDensity(aVar.tTq.getContext()), aVar.tTq.getContext(), i2);
ai_d.udn.setLayoutParams(new LayoutParams(0, 0));
if (a == null) {
fromDPToPix = com.tencent.mm.bp.a.fromDPToPix(aVar.tTq.getContext(), 85);
int ad = com.tencent.mm.bp.a.ad(aVar.tTq.getContext(), R.f.ChatImgLimitWidth);
Bitmap a2 = c.a(c.ah(aVar.tTq.getContext().getResources().getColor(R.e.grey_color_01), fromDPToPix, ad), i2, fromDPToPix, ad);
au.HU();
if (com.tencent.mm.model.c.isSDCardAvailable()) {
ai_d.ube.setImageBitmap(c.a(a2, i2, fromDPToPix, ad));
} else {
ai_d.ube.setImageDrawable(com.tencent.mm.bp.a.f(aVar.tTq.getContext(), R.k.video_no_sd_icon));
ai_d.ube.setBackground(new BitmapDrawable(a2));
}
ViewGroup.LayoutParams layoutParams = new LayoutParams(fromDPToPix, ad);
ai_d.udn.setLayoutParams(layoutParams);
if (ai_d.ueA != null) {
ai_d.ueA.setLayoutParams(layoutParams);
}
} else {
ai_d.ube.setImageBitmap(a);
ViewGroup.LayoutParams layoutParams2 = new LayoutParams(a.getWidth(), a.getHeight());
ai_d.udn.setLayoutParams(layoutParams2);
if (ai_d.ueA != null) {
ai_d.ueA.setLayoutParams(layoutParams2);
}
}
if (z) {
ai_d.mfT.setText(ai.bF((long) nW.dHI));
ai_d.uew.setText(ai.iR(nW.enM));
fromDPToPix = nW.status;
x.i("MicroMsg.VideoItemHoder", "parseVideo from video status : " + fromDPToPix + " info : " + nW.getFileName());
if (fromDPToPix == 199) {
ai_d.nEI.setImageDrawable(com.tencent.mm.bp.a.f(aVar.tTq.getContext(), R.k.shortvideo_play_btn));
} else {
ai_d.nEI.setImageDrawable(com.tencent.mm.bp.a.f(aVar.tTq.getContext(), R.k.shortvideo_play_btn));
ai_d.mfT.setVisibility(8);
}
if (fromDPToPix == 112 || fromDPToPix == 122 || fromDPToPix == 120) {
ai_d.tZR.setVisibility(8);
ai_d.nEI.setVisibility(8);
ai_d.uex.setVisibility(0);
ai_d.uex.setProgress(t.f(nW));
x.v("MicroMsg.VideoItemHoder", "status begin");
ai_d.uex.invalidate();
} else if (fromDPToPix == 113 || fromDPToPix == bh.CTRL_INDEX || nW.Tn()) {
ai_d.tZR.setVisibility(0);
ai_d.tZS.setVisibility(8);
ai_d.uex.setVisibility(8);
ai_d.nEI.setVisibility(0);
x.v("MicroMsg.VideoItemHoder", "status pause");
} else {
ai_d.tZS.setVisibility(8);
ai_d.tZR.setVisibility(8);
ai_d.uex.setVisibility(8);
ai_d.nEI.setVisibility(0);
x.v("MicroMsg.VideoItemHoder", "status gone");
}
} else {
ai_d.mfT.setText(ai.bF((long) nW.dHI));
ai_d.uew.setText(ai.iR(nW.enM));
fromDPToPix = nW.status;
ai_d.nEI.setImageDrawable(com.tencent.mm.bp.a.f(aVar.tTq.getContext(), R.k.shortvideo_play_btn));
if (ai_d.uez != null) {
ai_d.uez.setVisibility(8);
}
if (ai_d.ueA != null) {
ai_d.ueA.setVisibility(8);
}
x.v("MicroMsg.VideoItemHoder", "video status %d", new Object[]{Integer.valueOf(fromDPToPix)});
if (fromDPToPix == 104 || fromDPToPix == 103) {
if (com.tencent.mm.plugin.mmsight.c.sK(nW.enN)) {
if (ai_d.uez != null) {
ai_d.uez.setVisibility(0);
}
if (ai_d.ueA != null) {
ai_d.ueA.setVisibility(0);
}
ai_d.uew.setText(null);
ai_d.mfT.setText(null);
ai_d.nEI.setImageDrawable(null);
ai_d.tZS.setVisibility(8);
ai_d.tZR.setVisibility(8);
ai_d.uex.setVisibility(8);
} else {
if (ai_d.uez != null) {
ai_d.uez.setVisibility(8);
}
if (ai_d.ueA != null) {
ai_d.ueA.setVisibility(8);
}
ai_d.tZR.setVisibility(8);
ai_d.nEI.setVisibility(8);
ai_d.uex.setVisibility(0);
ai_d.uex.setProgress(t.g(nW));
}
x.v("MicroMsg.VideoItemHoder", "status begin");
} else if (fromDPToPix == 105 || fromDPToPix == bh.CTRL_INDEX || nW.Tn()) {
ai_d.tZR.setVisibility(0);
ai_d.tZS.setVisibility(8);
ai_d.uex.setVisibility(8);
ai_d.nEI.setVisibility(0);
x.v("MicroMsg.VideoItemHoder", "status pause");
} else if (fromDPToPix != f$k.AppCompatTheme_ratingBarStyle) {
ai_d.tZS.setVisibility(8);
ai_d.tZR.setVisibility(8);
ai_d.uex.setVisibility(8);
ai_d.nEI.setVisibility(0);
x.v("MicroMsg.VideoItemHoder", "status gone");
} else if (j.SN(bdVar.field_imgPath)) {
if (ai_d.uez != null) {
ai_d.uez.setVisibility(0);
}
if (ai_d.ueA != null) {
ai_d.ueA.setVisibility(0);
}
ai_d.uew.setText(null);
ai_d.mfT.setText(null);
ai_d.nEI.setImageDrawable(null);
ai_d.tZS.setVisibility(8);
ai_d.tZR.setVisibility(8);
ai_d.uex.setVisibility(8);
} else {
t.nP(bdVar.field_imgPath);
}
}
ImageView imageView = ai_d.tZS;
e eVar = new e(bdVar, aVar.cwr(), i, bdVar.field_talker);
eVar.hER = 4;
imageView.setTag(eVar);
ai_d.tZS.setOnClickListener(onClickListener);
imageView = ai_d.tZR;
eVar = new e(bdVar, aVar.cwr(), i, bdVar.field_talker);
eVar.hER = 3;
imageView.setTag(eVar);
ai_d.tZR.setOnClickListener(onClickListener);
View view = ai_d.hrH;
eVar = new e(bdVar, aVar.cwr(), i, bdVar.field_talker);
eVar.hER = 2;
view.setTag(eVar);
ai_d.hrH.setOnClickListener(onClickListener);
ai_d.hrH.setOnLongClickListener(onLongClickListener);
ai_d.hrH.setOnTouchListener(((g) aVar.O(g.class)).ctw());
}
}
|
package csci152.impl;
public class BinaryTree<T> {
private TreeNode<T> root;
public BinaryTree(TreeNode<T> root) {
this.root = root;
}
public TreeNode<T> getRoot() {
return this.root;
}
public void setRoot(TreeNode<T> root) {
this.root = root;
}
private String preOrder(TreeNode<T> node) {
if(node == null) return "";
String contents = "" + node.getValue() + "\n";
if(node.getLeft() != null) contents += "/\n" + preOrder(node.getLeft());
if(node.getRight() != null) contents += "\\ \n" + preOrder(node.getRight());
return contents;
}
private String inOrder(TreeNode<T> node) {
if(node == null) return "";
String contents = "";
if(node.getLeft() != null) contents += inOrder(node.getLeft());
contents += node.getValue() + "\n";
if(node.getRight() != null) contents += inOrder(node.getRight());
return contents;
}
private String postOrder(TreeNode<T> node) {
if(node == null) return "";
String contents = "";
if(node.getLeft() != null) contents += postOrder(node.getLeft());
if(node.getRight() != null) contents += postOrder(node.getRight());
contents += node.getValue() + "\n";
return contents;
}
@Override
public String toString() {
return postOrder(root);
}
}
|
class Solution {
public String pushDominoes(String dominoes) {
char[] arr = dominoes.toCharArray();
int n = arr.length , st = 0 , end = 0;
while (end < n) {
while (end < n && arr[end] == '.')
end += 1;
if (end == n)
break;
if (arr[end] == 'L') {
if (arr[st] == 'R') {
int temp = end;
while (st < temp) {
arr[st++] = 'R';
arr[temp--] = 'L';
}
} else {
while (st < end)
arr[st++] = 'L';
}
} else {
if (arr[st] == 'R') {
while (st < end)
arr[st++] = 'R';
}
}
st = end;
end += 1;
}
if (st < n && arr[st] == 'R') {
while (st < n)
arr[st++] = 'R';
}
return String.valueOf(arr);
}
}
|
/**
*
*/
package org.usfirst.frc.team467.robot.simulator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.usfirst.frc.team467.robot.Logging;
import org.usfirst.frc.team467.robot.RobotMap;
import org.usfirst.frc.team467.robot.RobotMap.RobotID;
import org.usfirst.frc.team467.robot.Autonomous.ActionGroup;
import org.usfirst.frc.team467.robot.Autonomous.MatchConfiguration;
import org.usfirst.frc.team467.robot.simulator.communications.RobotData;
import org.usfirst.frc.team467.robot.simulator.gui.MapController;
import org.usfirst.frc.team467.robot.simulator.gui.SimulatedData;
/**
* The simulated robot
*/
public class Robot {
private static final Logger LOGGER = LogManager.getLogger(Robot.class);
DriveSimulator drive;
MapController simulatorView;
RobotData data;
ActionGroup autonomous;
private MatchConfiguration matchConfig;
public void robotInit() {
Logging.init();
RobotMap.init(RobotID.Competition_1);
RobotMap.useSimulator = true;
RobotMap.USE_FAKE_GAME_DATA = true;
drive = DriveSimulator.getInstance();
matchConfig = MatchConfiguration.getInstance();
data = RobotData.getInstance();
// data.startServer();
LOGGER.info("Started the robot simulator");
}
public void setView(MapController simulatorView) {
this.simulatorView = simulatorView;
}
/*
* starting coordinates:
* Left: (2.5, 0)
* Center: (12.5, 0)
* Right: (21.58, 0)
*/
public void autonomousInit() {
drive.zero();
matchConfig.load();
if (SimulatedData.autoMode.startsWith("Left")) {
data.startingLocation(2.5, 0);
} else if (SimulatedData.autoMode.startsWith("Center")) {
data.startingLocation(12.5, 0);
} else { // Right
data.startingLocation(21.58, 0);
}
data.send();
autonomous = matchConfig.autonomousDecisionTree();
}
public void autonomousPeriodic() {
autonomous.run();
}
}
|
package com.example.sch;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Locale;
import static com.example.sch.LoginActivity.log;
import static com.example.sch.LoginActivity.loge;
public class PeriodFragment extends Fragment {
private String COOKIE, ROUTE;
private int USER_ID;
TableLayout table;
Subject[] subjects;
boolean ready = false;
public PeriodFragment () {}
public void start(final Context context) {
COOKIE = TheSingleton.getInstance().getCOOKIE();
ROUTE = TheSingleton.getInstance().getROUTE();
USER_ID = TheSingleton.getInstance().getUSER_ID();
table = new TableLayout(context);
new Thread() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void run() {
try {
URL url = new URL("https://app.eschool.center/ec-server/student/getDiaryUnits?userId=" + USER_ID + "&eiId=97932");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Cookie", COOKIE + "; route=" + ROUTE + "; _pk_ses.1.81ed=*; site_ver=app; _pk_id.1.81ed=de563a6425e21a4f.1553009060.16.1554146944.1554139340.");
StringBuilder result = new StringBuilder();
log("cookie: " + con.getRequestProperty("Cookie"));
log("code " + con.getResponseCode());
Log.v("mylog", con.getResponseMessage());
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
Log.v("mylog","diary: " + result.toString());
JSONObject obj = new JSONObject(result.toString());
JSONArray array = obj.getJSONArray("result");
int[] unitId_array = new int[array.length()];
subjects = new Subject[array.length()];
for (int i = 0; i < array.length(); i++) {
// tmp = new ArrayList<>();
obj = array.getJSONObject(i);
unitId_array[i] = obj.getInt("unitId");
/*if(!obj.has("overMark"))
continue;*/
if(obj.has("overMark")) {
if (obj.getDouble("overMark") != 0.0) {
if (obj.has("rating")) {
subjects[i] = new Subject(obj.getString("unitName"), obj.getDouble("overMark"), obj.getString("rating"));
} else {
subjects[i] = new Subject(obj.getString("unitName"), obj.getDouble("overMark"), "");
}
} else {
subjects[i] = new Subject(obj.getString("unitName"), -1, "");
}
}
}
url = new URL("https://app.eschool.center/ec-server/student/getDiaryPeriod?userId=" + USER_ID + "&eiId=97932");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Cookie", COOKIE + "; route=" + ROUTE + "; _pk_ses.1.81ed=*; site_ver=app; _pk_id.1.81ed=de563a6425e21a4f.1553009060.16.1554146944.1554139340.");
log("getting marks...");
log(con.getResponseCode() + "");
result = new StringBuilder();
rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
log(result.toString());
ArrayList<ArrayList<String>> arr = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
arr.add(new ArrayList<String>());
}
ArrayList<String> tmp;
obj = new JSONObject(result.toString());
array = obj.getJSONArray("result");
for (int i = 0; i < array.length(); i++) {
obj = array.getJSONObject(i);
if (obj.has("markVal")) {
int unitId = obj.getInt("unitId");
int k = -1;
for (int j = 0; j < unitId_array.length; j++) {
if (unitId == unitId_array[j]) {
k = j;
break;
}
}
tmp = arr.get(k);
tmp.add(obj.getString("markVal"));
}
}
TableRow row;
TextView tv;
for (int i = 0; i < arr.size(); i++) {
row = new TableRow(context);
tmp = arr.get(i);
if(tmp.size() == 0) {
tv = new TextView(context);
tv.setLayoutParams(new TableRow.LayoutParams(0));
tv.setText("");
row.addView(tv);
tv.setHeight(86);
}
for (int j = 0; j < tmp.size(); j++) {
tv = new TextView(context);
tv.setTextSize(16);
tv.setLayoutParams(new TableRow.LayoutParams(j));
tv.setPadding(0, 0, 8, 8);
tv.setText(tmp.get(j));
tv.setTextColor(getResources().getColor(R.color.three));
tv.setHeight(86);
row.addView(tv);
}
row.setPadding(0, 0, 0, 8);
table.addView(row);
}
ready = true;
} catch (Exception e) {
loge(e.toString());
}
}
}.start();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.diary, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
while(true) {
try {
Thread.sleep(10);
if(ready)
break;
} catch (InterruptedException e) {
//
}
}
LinearLayout l_subjects = view.findViewById(R.id.linear);
LinearLayout tmp;
TextView tv_tmp;
for (Subject s: subjects) {
if(s == null) {
log("null");
continue;
}
log(s.toString());
tmp = new LinearLayout(getContext());
tmp.setOrientation(LinearLayout.HORIZONTAL);
tv_tmp = new TextView(getContext());
tv_tmp.setText(s.name);
tv_tmp.setTextSize(16);
tv_tmp.setTextColor(getResources().getColor(R.color.three));
tv_tmp.setPadding(0, 0, 8, 0);
tmp.addView(tv_tmp);
if(!(s.avg == -1)) {
tv_tmp = new TextView(getContext());
tv_tmp.setText(String.format(Locale.UK, "%.2f", s.avg));
tv_tmp.setTextSize(16);
tv_tmp.setTextColor(getResources().getColor(R.color.two));
tv_tmp.setPadding(0, 0, 8, 0);
tmp.addView(tv_tmp);
}
if(!s.rating.equals("")) {
tv_tmp = new TextView(getContext());
tv_tmp.setText(s.rating);
tv_tmp.setTextSize(16);
tv_tmp.setTextColor(getResources().getColor(R.color.one));
tv_tmp.setPadding(0, 0, 8, 0);
tmp.addView(tv_tmp);
}
tmp.setPadding(0, 0, 0, 8);
l_subjects.addView(tmp);
}
HorizontalScrollView scroll = view.findViewById(R.id.tv_users);
LinearLayout layout = new LinearLayout(getContext());
if(table.getParent() != null) {
((ViewGroup)table.getParent()).removeView(table);
}
layout.addView(table, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
scroll.addView(layout, HorizontalScrollView.LayoutParams.MATCH_PARENT, HorizontalScrollView.LayoutParams.WRAP_CONTENT);
}
class Subject {
String name, rating;
double avg;
Subject(String name, double avg, String rating) {
this.name = name;
this.avg = avg;
this.rating = rating;
}
@Override
public String toString() {
return name + " " + rating + " " + avg;
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
log("onAttach");
}
@Override
public void onDetach() {
super.onDetach();
log("onDetach");
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("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 Hybris.
*/
package com.cnk.travelogix.b2c.facades.homepage;
import java.util.Date;
import java.util.List;
import com.cnk.travelogix.common.core.enums.ProductTypeEnum;
import com.cnk.travelogix.common.core.model.TravellerTypeModel;
import com.cnk.travelogix.common.facades.home.data.TravellerDealData;
import com.cnk.travelogix.common.facades.product.data.flight.PopularFlightData;
import com.cnk.travelogix.common.facades.product.data.flight.PopularHotelCityData;
/**
*
*/
public interface HomePageFacade
{
List<TravellerDealData> getTravellerDealData();
List<PopularFlightData> getPopularFlightData();
List<PopularHotelCityData> getPopularHotelCityData();
List<TravellerTypeModel> getTravellerType();
List<String> getTop4PopularCities(Date startDate, Date endDate, ProductTypeEnum productType);
List getTop9PopularFlights(Date startDate, Date endDate, ProductTypeEnum productType);
}
|
package it.polimi.ingsw.GC_21.GAMEMANAGEMENT;
import java.io.Serializable;
import java.util.ArrayList;
import org.omg.CORBA.PUBLIC_MEMBER;
import it.polimi.ingsw.GC_21.BOARD.Dice;
import it.polimi.ingsw.GC_21.GAMECOMPONENTS.DevCardType;
import it.polimi.ingsw.GC_21.GAMECOMPONENTS.DevDeck;
import it.polimi.ingsw.GC_21.PLAYER.Color;
import it.polimi.ingsw.GC_21.PLAYER.FamilyMember;
import it.polimi.ingsw.GC_21.PLAYER.Player;
import it.polimi.ingsw.GC_21.VIEW.RemoteView;
public class Round implements Serializable{
private int roundNumber;
private Game game;
private Player blackPlayer;
public Round(int roundNumber, Game game) {
this.roundNumber = roundNumber;
this.game = game;
}
private void setTurnOrder() {
ArrayList<Player> turnOrder = game.getBoard().getCouncilPalace().getTurnOrder();
game.setThisTurnOrder(turnOrder);
blackPlayer = game.getSpecificPlayer(Color.Black);
ArrayList<Player> playersInGame = game.getPlayers();
for (int j = 0; j < playersInGame.size(); j++) {
if (!turnOrder.contains(playersInGame.get(j))) {
turnOrder.add(playersInGame.get(j));
}
}
}
public void executeRound() {
if (!game.isSavedGame()) {
setTurnOrder();
game.getBoard().refreshBoard();
for (int i = 0; i < game.getPlayers().size(); i++) {
game.getPlayers().get(i).refreshPlayer();
}
this.placeCard();
}
else {
game.setSavedGame(false);
}
if (blackPlayer != null && game.isBlackTurn()) {
game.getTurnOrder().remove(blackPlayer);//for black player there is a specific notify turn in which he plays all his family members at the beginning
for (int i = game.getCurrentTurn().getTurnNumber(); i < 5; i++) {
Turn currentTurn = new Turn(i, game);
game.setCurrentTurn(currentTurn);
game.notifyBlackTurn(blackPlayer);
}
game.setBlackTurn(false);
game.setCurrentTurn(new Turn(1, game));
}
for (int i = game.getCurrentTurn().getTurnNumber(); i < 5 ; i++) {
Turn currentTurn = new Turn(i, game);
game.setCurrentTurn(currentTurn);
currentTurn.executeView(game.getTurnOrder());
}
game.setBlackTurn(true);
game.setCurrentTurn(new Turn(1, game));
game.getBoard().setDices(Dice.factoryDices());
for (int i = 0; i < game.getNumberOfPlayers(); i++) {
game.getPlayers().get(i).setFamilyMembers(FamilyMember.factoryFamilyMembers(game.getBoard().getDices(), game.getPlayers().get(i)));
}
}
public void placeCard() {
game.getBoard().getSpecificTower(DevCardType.Building).pickCards(game.getCurrentAge().buildingDeck);
game.getBoard().getSpecificTower(DevCardType.Territory).pickCards(game.getCurrentAge().territoryDeck);
game.getBoard().getSpecificTower(DevCardType.Venture).pickCards(game.getCurrentAge().ventureDeck);
game.getBoard().getSpecificTower(DevCardType.Character).pickCards(game.getCurrentAge().characterDeck);
}
public int getRoundNumber() {
return roundNumber;
}
public void setRoundNumber(int roundNumber) {
this.roundNumber = roundNumber;
}
public Player getBlackPlayer() {
return blackPlayer;
}
public void setBlackPlayer(Player blackPlayer) {
this.blackPlayer = blackPlayer;
}
}
|
package com.tencent.mm.plugin.location.ui;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.tencent.mm.plugin.location.model.LocationInfo;
import com.tencent.mm.plugin.location_soso.ViewManager;
import com.tencent.mm.plugin.map.a;
import com.tencent.mm.plugin.map.a.e;
import com.tencent.mm.plugin.map.a.f;
import com.tencent.mm.plugin.r.d;
public final class n implements c {
public boolean bNu = false;
public boolean isVisible = true;
private String kCs;
public double kCw = 1000000.0d;
public double kCx = 1000000.0d;
public boolean kEX = true;
private View kEY;
private TextView kEs;
private ProgressBar kEt;
private String kEx = "";
public String kFa;
public final String kHE = "info_window_tag";
public ImageView kHF;
public FrameLayout kHG;
private TextView kHH;
public boolean kHI;
private Context mContext;
public ViewManager mViewManager;
public final void b(LocationInfo locationInfo) {
this.kCw = locationInfo.kCw;
this.kCx = locationInfo.kCx;
}
public n(d dVar, Context context, boolean z) {
this.mContext = context;
this.kHI = z;
this.kHF = new ImageView(context);
this.kHF.setBackgroundResource(a.d.mm_trans);
this.kHF.setScaleType(ScaleType.CENTER_CROP);
this.kHG = (FrameLayout) View.inflate(context, f.map_overlay_layout, null);
if (z) {
this.kHF.setImageResource(a.d.location_arrows);
} else {
this.kHF.setImageResource(a.d.location_artboard1);
}
this.kEY = this.kHG;
this.mViewManager = (ViewManager) dVar.getViewManager();
}
public final void setText(String str) {
this.kCs = str;
CharSequence charSequence = this.kCs;
this.kEs = (TextView) this.kHG.findViewById(e.location_tips);
this.kEt = (ProgressBar) this.kHG.findViewById(e.location_load_progress);
this.kHH = (TextView) this.kHG.findViewById(e.location_poiname);
if (charSequence == null || charSequence.equals("")) {
this.kEt.setVisibility(0);
} else {
this.kEt.setVisibility(8);
this.kEs.setVisibility(0);
this.kEs.setText(charSequence);
}
if (this.kFa == null || this.kFa.equals("")) {
this.kHH.setText("");
this.kHH.setVisibility(8);
} else {
this.kHH.setVisibility(0);
this.kHH.setText(this.kFa);
}
if (this.kEX) {
this.mViewManager.updateViewLayout(this.kHF, this.kCw, this.kCx, false);
if (this.kHI) {
this.mViewManager.showInfoWindowByView(this.kHF);
}
}
}
public final String getPreText() {
return this.kEx;
}
}
|
package com.leetcode.easy;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/**
* Created by saml on 1/11/2018.
*/
public class BinaryTreeLevelOrderTraversalII {
Stack<TreeNode> stack = new Stack<>();
public void pushIntoStack(TreeNode root){
if(root != null){
stack.push(root.right);
stack.push(root.left);
pushIntoStack(root.left);
pushIntoStack(root.right);
}
}
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root == null){
return new ArrayList<List<Integer>>();
}
stack.push(root);
pushIntoStack(root);
List<List<Integer>> list = new ArrayList<>();
TreeNode left, right = null;
while(stack.size() != 1){
List<Integer> list2 = new ArrayList<>();
left = stack.pop();
right = stack.pop();
if(left != null){
list2.add(left.val);
}
if(right != null){
list2.add(right.val);
}
if(list2.size() != 0){
list.add(list2);
}
}
List<Integer> list3 = new ArrayList<>();
list3.add(stack.pop().val);
list.add(list3);
return list;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
BinaryTreeLevelOrderTraversalII binaryTreeLevelOrderTraversalII = new BinaryTreeLevelOrderTraversalII();
binaryTreeLevelOrderTraversalII.levelOrderBottom(root);
}
}
|
package day16_Recap;
import java.util.Scanner;
public class nextLine2 {
public static void main(String[] args) {
/*
write a program that accepts zipcode,city,state,phonenumber
and then display all those gathered information
do not use next method
*/
Scanner input=new Scanner(System.in);
System.out.println("Enter your zip code");
int zip = input.nextInt();
//12345"ENTER"//to get rid of this enter from scanner, i need to give something to take that ENTER
//input.nextLine();===>takes out that enter
input.nextLine();
System.out.println("Enter your city");
String city= input.nextLine();
System.out.println("Enter your phone number");
int phone = input.nextInt();
//65657 ENTER
input.nextLine();//take the ENTER from previous line
System.out.println("Enter your state");
String state=input.nextLine();
System.out.println("zip code is: "+zip);
System.out.println("city name is: "+city);
System.out.println("phone number is: "+ phone);
System.out.println("state name is: "+state);
}
}
|
package com.rex.demo.study.test;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
/**
* @Author li zhiqang
* @create 2020/11/24
*/
public class Common {
public static void main(String[] args) throws Exception {
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
DataSource<String> text = env.readTextFile("hdfs://hadoop-master:9000/test/data/json.txt");
text.print();
/**
* 异常的原因就是说,自上次执行以来,没有定义新的数据接收器。对于离线批处理的算子,如:“count()”、“collect()”或“print()”等既有sink功能,还有触发的功能。我们上面调用了print()方法,会自动触发execute,所以最后面的一行执行器没有数据可以执行。
* 对于学过sparkstreaming后初学flink的小伙伴来说,这里要注意一下,有点小区别。
*/
// env.execute();
}
}
|
package com.kdgm.webservice;
import java.util.ArrayList;
import java.util.List;
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 ArrayOfAnaKurumlarButceTurleri complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfAnaKurumlarButceTurleri">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="AnaKurumlarButceTurleri" type="{http://kaysis.gov.tr/}AnaKurumlarButceTurleri" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfAnaKurumlarButceTurleri", propOrder = {
"anaKurumlarButceTurleri"
})
public class ArrayOfAnaKurumlarButceTurleri {
@XmlElement(name = "AnaKurumlarButceTurleri", nillable = true)
protected List<AnaKurumlarButceTurleri> anaKurumlarButceTurleri;
/**
* Gets the value of the anaKurumlarButceTurleri property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the anaKurumlarButceTurleri property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAnaKurumlarButceTurleri().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AnaKurumlarButceTurleri }
*
*
*/
public List<AnaKurumlarButceTurleri> getAnaKurumlarButceTurleri() {
if (anaKurumlarButceTurleri == null) {
anaKurumlarButceTurleri = new ArrayList<AnaKurumlarButceTurleri>();
}
return this.anaKurumlarButceTurleri;
}
}
|
package com.nic.usermanagement.dao;
import java.util.Map;
import com.nic.usermanagement.model.BhudharRegistration;
public interface BhudharDAO {
public BhudharRegistration bhudharRegistration(BhudharRegistration bhurdetails);
public BhudharRegistration BhudharDetailsById(Integer bhudharid);
BhudharRegistration bhudharDetailsById(Integer bhudharid);
public Map getDistricts(String statecode);
public Map getVillages();
public Map getMandals();
}
|
package in.vaksys.vivekpk.fragments;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
import in.vaksys.vivekpk.R;
import in.vaksys.vivekpk.activities.VerifyOtpActivity;
import in.vaksys.vivekpk.adapter.ListViewAdapter;
import in.vaksys.vivekpk.extras.AdapterCallback;
import in.vaksys.vivekpk.extras.MyApplication;
import in.vaksys.vivekpk.pojo.Coutrycode;
/**
* Created by dell980 on 5/2/2016.
*/
public class SignupFragment extends Fragment implements AdapterCallback {
EditText etCountryCode;
private Button btnContinue;
Dialog dialog;
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] code;
String[] countryName;
ArrayList<Coutrycode> arraylist = new ArrayList<Coutrycode>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_signup, container, false);
dialog = new Dialog(getContext());
code = new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
countryName = new String[]{"China", "India", "United States",
"Indonesia", "Brazil", "Pakistan", "Nigeria", "Bangladesh",
"Russia", "Japan"};
etCountryCode = (EditText) rootView.findViewById(R.id.et_code_signup);
btnContinue = (Button) rootView.findViewById(R.id.btn_continue);
etCountryCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ShowAlertDialogWithListview();
}
});
btnContinue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog confirm = new Dialog(getActivity());
confirm.requestWindowFeature(Window.FEATURE_NO_TITLE);
confirm.setContentView(R.layout.confirm_dialog);
Button btnSend = (Button) confirm.findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), VerifyOtpActivity.class));
}
});
confirm.show();
}
});
return rootView;
}
public void ShowAlertDialogWithListview() {
dialog.setTitle("Choose country Code");
dialog.setContentView(R.layout.country_list);
list = (ListView) dialog.findViewById(R.id.list);
for (int i = 0; i < countryName.length; i++) {
Coutrycode wp = new Coutrycode(code[i], countryName[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) dialog.findViewById(R.id.et_search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
@Override
public void onMethodCallback() {
dialog.dismiss();
SharedPreferences sharedPreferences = MyApplication.getInstance().getSharedPreferences("harsh", Context.MODE_PRIVATE);
//Toast.makeText(MyApplication.getInstance(), "yeyyyyy" + sharedPreferences.getString("value", "fuck"), Toast.LENGTH_LONG).show();
etCountryCode.setText(sharedPreferences.getString("value", ""));
}
}
|
package com.chenpeini.webflux.handler;
import com.chenpeini.webflux.params.DemoParam;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
/**
* @Desc:
* @Author: chenbo
* @Date: 2019/8/23 09:41
**/
@Component
public class DemoHandler {
public Mono<ServerResponse> get(ServerRequest request) {
MultiValueMap<String, String> multiValueMap = request.queryParams();
final Mono<DemoParam> paramMono = request.bodyToMono(DemoParam.class);
System.out.println("====" + paramMono.toString());
Integer age = paramMono.map(p -> p.getAge()).block();
return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON_UTF8)
.body(BodyInserters.fromObject(multiValueMap.get("name").get(0) + "--" + multiValueMap.get("age").get(0)));
}
}
|
package com.tencent.mm.ak;
import android.content.ContentValues;
import android.database.Cursor;
import com.tencent.mm.sdk.platformtools.x;
public final class e {
public int bWA = -2;
public long bYu;
int cGG = 0;
public int dHI;
public long dTK;
public String dTL = "";
public String dTM = "";
public String dTN = "";
public int dTO;
int dTP;
private String dTQ = "";
int dTR;
public long dTS;
int dTT;
public int dTU = 0;
public String dTV = "";
int dTW = 1;
private boolean dTX;
private boolean dTY;
private boolean dTZ;
private boolean dUa;
private boolean dUb;
private boolean dUc;
private boolean dUd;
private boolean dUe;
private boolean dUf;
private boolean dUg;
private boolean dUh;
private boolean dUi;
boolean dUj;
private boolean dUk;
boolean dUl;
private boolean dUm;
private boolean dUn;
private boolean dUo;
private boolean dUp;
public int offset;
int source;
public int status;
public final void lG(String str) {
this.dTQ = str;
this.dUn = true;
}
public final void setStatus(int i) {
this.status = i;
this.dUg = true;
}
public final void hJ(int i) {
this.dTT = i;
this.dUh = true;
}
public final void hK(int i) {
this.dTR = i;
this.dUe = true;
}
public final void bo(long j) {
this.dTS = j;
this.dUf = true;
}
public final void bp(long j) {
this.dTK = j;
this.dTX = true;
}
public final void ax(long j) {
if (this.bYu != j) {
this.dTY = true;
}
this.bYu = j;
}
public final void setOffset(int i) {
int i2 = 0;
if (this.offset != i) {
this.dTZ = true;
}
this.offset = i;
x.e("MicroMsg.Imgfo", "set offset : %d id:%d total:%d", Integer.valueOf(i), Long.valueOf(this.dTS), Integer.valueOf(this.dHI));
if (i >= this.dHI) {
i2 = 1;
}
hO(i2);
}
public final void hL(int i) {
this.dHI = i;
this.dUa = true;
}
public final void lH(String str) {
this.dTL = str;
this.dUb = true;
}
public final void lI(String str) {
this.dTM = str;
this.dUc = true;
}
public final void lJ(String str) {
this.dTN = str;
this.dUd = true;
}
public final void hM(int i) {
this.dTU = i;
this.dUi = true;
}
public final void hN(int i) {
this.dTP = i;
this.dUp = true;
}
public final boolean OM() {
return this.dHI != 0 && this.dHI == this.offset;
}
public final boolean ON() {
return this.dTU > 0;
}
public final void lK(String str) {
if ((this.dTV == null && str != null) || !(this.dTV == null || this.dTV.equals(str))) {
this.dUk = true;
}
this.dTV = str;
}
public final void d(Cursor cursor) {
this.dTK = (long) cursor.getInt(0);
this.bYu = cursor.getLong(1);
this.offset = cursor.getInt(2);
this.dHI = cursor.getInt(3);
this.dTL = cursor.getString(4);
this.dTN = cursor.getString(5);
this.dTR = cursor.getInt(6);
this.dTS = (long) cursor.getInt(7);
this.status = cursor.getInt(8);
this.dTT = cursor.getInt(9);
this.dTU = cursor.getInt(10);
this.source = cursor.getInt(11);
this.dTV = cursor.getString(12);
this.cGG = cursor.getInt(14);
this.dTW = cursor.getInt(15);
this.dTQ = cursor.getString(16);
this.dTO = cursor.getInt(17);
this.dTM = cursor.getString(18);
this.dTP = cursor.getInt(19);
}
public final void hO(int i) {
if (this.dTW != i) {
this.dUm = true;
}
this.dTW = i;
}
public final void hP(int i) {
this.dTO = i;
this.dUo = true;
}
public final ContentValues wH() {
ContentValues contentValues = new ContentValues();
if (this.dTX) {
contentValues.put("id", Long.valueOf(this.dTK));
}
if (this.dTY) {
contentValues.put("msgSvrId", Long.valueOf(this.bYu));
}
if (this.dTZ) {
contentValues.put("offset", Integer.valueOf(this.offset));
}
if (this.dUa) {
contentValues.put("totalLen", Integer.valueOf(this.dHI));
}
if (this.dUb) {
contentValues.put("bigImgPath", this.dTL);
}
if (this.dUc) {
contentValues.put("midImgPath", this.dTM);
}
if (this.dUd) {
contentValues.put("thumbImgPath", this.dTN);
}
if (this.dUe) {
contentValues.put("createtime", Integer.valueOf(this.dTR));
}
if (this.dUf) {
contentValues.put("msglocalid", Long.valueOf(this.dTS));
}
if (this.dUg) {
contentValues.put("status", Integer.valueOf(this.status));
}
if (this.dUh) {
contentValues.put("nettimes", Integer.valueOf(this.dTT));
}
if (this.dUi) {
contentValues.put("reserved1", Integer.valueOf(this.dTU));
}
if (this.dUj) {
contentValues.put("reserved2", Integer.valueOf(this.source));
}
if (this.dUk) {
contentValues.put("reserved3", this.dTV);
}
if (this.dUl) {
contentValues.put("hashdthumb", Integer.valueOf(this.cGG));
}
if (this.dUm) {
contentValues.put("iscomplete", Integer.valueOf(this.offset < this.dHI ? 0 : 1));
}
if (this.dUn) {
contentValues.put("origImgMD5", this.dTQ);
}
if (this.dUo) {
contentValues.put("compressType", Integer.valueOf(this.dTO));
}
if (this.dUp) {
contentValues.put("forwardType", Integer.valueOf(this.dTP));
}
return contentValues;
}
public final void OO() {
this.dTX = false;
this.dTY = false;
this.dTZ = false;
this.dUa = false;
this.dUb = false;
this.dUc = false;
this.dUd = false;
this.dUe = false;
this.dUf = false;
this.dUg = false;
this.dUh = false;
this.dUi = false;
this.dUj = false;
this.dUk = false;
this.dUl = false;
this.dUm = false;
this.dUn = false;
this.dUo = false;
this.dUp = false;
}
}
|
package com.umind.games;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TableRow;
import android.widget.GridLayout.LayoutParams;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class SeriesGame extends Activity {
public final static String START_OVER = "com.umind.games.START_OVER";
public Seria s = new Seria(0,100,4);
public TextView tvShowSeries;
public TextView tvShowSeriesGameDescription;
public Button btnShowNext;
public Button btnGoSeriesGame;
private List<Seria> mainGameSeriaList = new ArrayList<Seria>();
private ResultDisplay display = new ResultDisplay();
private Button[] numericButtons = new Button[0];
//private Integer currentResultLabel;
private Spinner spinner;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_series_game);
addItemsOnSpinner();
addListenerOnSpinnerItemSelection();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public void startOver(View view){
//Intent intent = new Intent(this, ShowGame.class);
//TextView textView = (TextView) findViewById(R.id.edit_message);
//intent.putExtra(START_OVER,textView.getText().toString());
//startActivity(intent);
}
public void addItemsOnSpinner(){
spinner = (Spinner) findViewById(R.id.chooseSeriesNumberSpnr);
List<Integer> list = new ArrayList<Integer>();
list.add(1); list.add(2); list.add(3); list.add(4);
list.add(5); list.add(6); list.add(7); //list.add(8);
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setSelection(3);
//TODO : set selection from last choise
}
public void generateSeriesForGame(int numberOfSeries){
int step = 0;
int start = 0;
int end = 100;
Integer max = 9;
Integer min = -9;
List<Integer> stepList = new ArrayList<Integer>();
for (int i = min; i <= max; i++){
if (i != 0 ) {stepList.add(i);}
}
for (int i=0; i < numberOfSeries; i++){
//randomize starting point, ending point, step
// create Seria object and add it to the mainGameSeriaList List
// 1. create random step in range [-9,9]
int n = (int)((double)(stepList.size() * Math.random()));
step = stepList.get(n);
stepList.remove(n);
if (step > 0 ){
start = 0;
end = 100;
}
else {
start = 100;
end = 0;
}
s = new Seria(start, end, step);
mainGameSeriaList.add(s);
} // end of foreach
}
public void addListenerOnSpinnerItemSelection() {
spinner = (Spinner) findViewById(R.id.chooseSeriesNumberSpnr);
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// this method is creating and drawing the game
public void goSeriesGame (View view){
spinner = (Spinner) findViewById(R.id.chooseSeriesNumberSpnr);
Integer number = (Integer) spinner.getSelectedItemPosition() +1;
tvShowSeries = (TextView) findViewById(R.id.mainGameView);
btnShowNext = (Button) findViewById(R.id.showNextBtn);
btnGoSeriesGame = (Button) findViewById(R.id.GoSeriesGameBtn);
tvShowSeriesGameDescription = (TextView) findViewById(R.id.descriptionGameView);
Toast.makeText(this,
"Selected " +
"\n"+ number +" random series selected",
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
btnGoSeriesGame.setVisibility(View.GONE);
//tvShowSeries.setVisibility(View.VISIBLE);
btnShowNext.setVisibility(View.VISIBLE);
tvShowSeriesGameDescription.setVisibility(View.VISIBLE);
/* ((Button) findViewById(R.id.num_btn_1)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_two)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_three)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_four)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_five)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_six)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_seven)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_eight)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_nine)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.bk_zero)).setVisibility(View.VISIBLE);
*/
// create buttons programatically and set listener
//creates Series with specific value for the game
generateSeriesForGame(spinner.getSelectedItemPosition()+1);
Log.i("SeriesGame.class.goSeriesGame","will create now keyboard");
createNumberKeyboard();
//places description of the game on the place
showSeriesGameDescription();
showFirstSeries();
}
@SuppressLint("ShowToast")
public void createNumberKeyboard()
{
Log.i("SeriesGame.class.createNumberKeyboard","started");
GridLayout gl = (GridLayout) findViewById(R.id.resultGridLayout);
//android.widget.TableRow.LayoutParams layoutParams = new .LayoutParams(LayoutParams.WRAP_CONTENT, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
//LayoutParams lparams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f);
for (int i=0; i< numericButtons.length; i++)
{
numericButtons[i] = new Button(getApplicationContext());
numericButtons[i].setTextColor(Color.parseColor("#2B5B96"));
numericButtons[i].setTextSize(20);
String name = "num_btn_"+i+"_txt"; //num_btn_1_txt
//TODO -- take button's number from from strings
numericButtons[i].setText(name);
//numericButtons[i].setHeight(100);
//numericButtons[i].setLayoutParams(param);
numericButtons[i].setPadding(15, 5, 15, 5);
gl.addView(numericButtons[i]);
Toast.makeText(getApplicationContext(), "added: " + numericButtons[i].getText()+" button", Toast.LENGTH_SHORT);
}
Log.i("SeriesGame.class.createNumberkeyboard","created and added keyboard");
}
// set on click listener for number buttons
public View.OnClickListener getOnClickDoSomething(final Button button) {
return new View.OnClickListener() {
public void onClick(View v) {
//button.setText(" ");
Toast.makeText(getApplicationContext(), "pressed: " + button.getText()+" button", Toast.LENGTH_SHORT);
}
};
}
public void showFirstSeries()
{
Log.i("SeriaGame.class.showFirstSeries","started");
Integer idNumber=1;
for (Seria s : mainGameSeriaList)
{
Log.i("SeriaGame.class.showFirstSeries","create tv for Seria "+idNumber);
TextView tv = (TextView) new TextView (this);
Log.i("SeriesGame.class.showFirstSeries","Seria s set to "+s.getFirstElement());
display.setTextOnTV(tv, idNumber, ((Integer) s.getFirstElement()).toString());
TextView empty = (TextView) new TextView(this);
empty.setBackgroundColor(Color.GRAY);
empty.setText(" ");
GridLayout gl = (GridLayout) findViewById(R.id.resultGridLayout);
gl.addView(empty);
gl.addView(tv);
TextView empty2 = (TextView) new TextView(this);
empty2.setBackgroundColor(Color.GRAY);
empty2.setText(" ");
gl.addView(empty2);
Log.i("SeriaGame.class.showFirstSeries","added view to resultGridLayout successfully");
idNumber++;
}
}
public void showSeriesGameDescription(){
tvShowSeriesGameDescription = (TextView) findViewById(R.id.descriptionGameView);
tvShowSeriesGameDescription.setTextSize( 20 ); //Float.valueOf((findViewById(R.string.textSizeForDescription).toString()) ) );
String line;
String prevLines;
for (Seria s : mainGameSeriaList) {
line = "\n" + s.getFirstElement() + " .. " + s.getStep() + " .. " + s.getLastElement();
prevLines = (String) tvShowSeriesGameDescription.getText();
tvShowSeriesGameDescription.setText(prevLines + line);
}
}
public void showNext(View view){
Log.i("ShowGame.class.showNext "," f:"+s.getFirstElement()+" step:"+s.getStep()+" curr:"+s.getCurrentElement());
tvShowSeries = (TextView) findViewById(R.id.mainGameView);
String vector = "";
for (Seria s : mainGameSeriaList) {
vector = vector + " " + s.getNextElement();
}
// draw the results
tvShowSeries.setText("( " +vector+ " )");
tvShowSeries.setTextSize(40);
tvShowSeries.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_series_game, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
package complexNumberProject;
import complexNumberArray.client.ComplexNumberArrayclient;
public class CoplexNumberArray {
private int[] real;
private int[] img;
public static int variableName = 45;
public CoplexNumberArray() {
}
public CoplexNumberArray(int[] real, int[] img) {
this.real = real;
this.img = img;
}
public int[] getReal() {
return real;
}
public void setReal(int[] real) {
this.real = real;
}
public int[] getImg() {
return img;
}
public void setImg(int[] img) {
this.img = img;
}
}
|
package com.plexobject.dp.sample.provider;
import java.util.Collection;
import com.plexobject.dp.domain.DataRowSet;
import com.plexobject.dp.domain.MetaField;
import com.plexobject.dp.domain.MetaFieldFactory;
import com.plexobject.dp.domain.Metadata;
import com.plexobject.dp.domain.QueryConfiguration;
import com.plexobject.dp.provider.BaseProvider;
import com.plexobject.dp.provider.DataProviderException;
import com.plexobject.dp.sample.dao.DaoLocator;
import com.plexobject.dp.sample.dao.Filter;
import com.plexobject.dp.sample.domain.Security;
import com.plexobject.dp.sample.marshal.SecurityMarshaller;
public class SymbolSearchProvider extends BaseProvider {
private static MetaField symbolQuery = MetaFieldFactory.createText(
"symbolQuery", Security.class.getSimpleName(), false);
private static Metadata parameterMeta = Metadata.from(symbolQuery);
private static Metadata optionalMeta = Metadata.from();
private static SecurityMarshaller marshaller = new SecurityMarshaller();
public SymbolSearchProvider() {
super("SymbolSearchProvider", parameterMeta, optionalMeta, marshaller
.getMetadata());
}
@Override
public void produce(DataRowSet parameter, DataRowSet response,
QueryConfiguration config) throws DataProviderException {
int nextRow = 0;
for (int i = 0; i < parameter.size(); i++) {
final String id = parameter.getValueAsText(symbolQuery, i)
.toUpperCase();
Collection<Security> securities = DaoLocator.securityDao
.filter(new Filter<Security>() {
@Override
public boolean accept(Security security) {
return security.getSymbol().contains(id);
}
});
//
for (Security security : securities) {
DataRowSet rowset = marshaller.marshal(security);
nextRow = addRowSet(response, rowset, nextRow);
}
}
}
}
|
/*
* GeoServer-Manager - Simple Manager Library for GeoServer
*
* Copyright (C) 2007,2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package it.geosolutions.geoserver.rest.decoder;
import it.geosolutions.geoserver.rest.decoder.utils.JDOMBuilder;
import it.geosolutions.geoserver.rest.encoder.feature.FeatureTypeAttribute;
import it.geosolutions.geoserver.rest.encoder.feature.GSAttributeEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.GSMetadataLinkInfoEncoder;
import it.geosolutions.geoserver.rest.encoder.metadatalink.ResourceMetadataLinkInfo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jdom.Element;
import org.jdom.Namespace;
/**
* Parse a resource (FeatureType or Coverage) returned as XML REST objects.
*
* @author etj
* @author Emmanuel Blondel - emmanuel.blondel1@gmail.com |
* emmanuel.blondel@fao.org
*/
public class RESTResource {
protected final Element rootElem;
public static RESTResource build(String response) {
Element elem = JDOMBuilder.buildElement(response);
return elem == null ? null : new RESTCoverage(elem);
}
public RESTResource(Element resource) {
this.rootElem = resource;
}
public String getName() {
return rootElem.getChildText("name");
}
public String getTitle() {
return rootElem.getChildText("title");
}
public String getNativeName() {
return rootElem.getChildText("nativeName");
}
public String getAbstract() {
return rootElem.getChildText("abstract");
}
public String getNameSpace() {
return rootElem.getChild("namespace").getChildText("name");
}
public String getStoreName() {
return rootElem.getChild("store").getChildText("name");
}
public String getStoreType() {
return rootElem.getChild("store").getAttributeValue("class");
}
public String getStoreUrl() {
Element store = rootElem.getChild("store");
Element atom = store.getChild("link",
Namespace.getNamespace("atom", "http://www.w3.org/2005/Atom"));
return atom.getAttributeValue("href");
}
public String getCRS() {
Element elBBox = rootElem.getChild("latLonBoundingBox");
return elBBox.getChildText("crs");
}
protected double getLatLonEdge(String edge) {
Element elBBox = rootElem.getChild("latLonBoundingBox");
return Double.parseDouble(elBBox.getChildText(edge));
}
public double getMinX() {
return getLatLonEdge("minx");
}
public double getMaxX() {
return getLatLonEdge("maxx");
}
public double getMinY() {
return getLatLonEdge("miny");
}
public double getMaxY() {
return getLatLonEdge("maxy");
}
public List<Map<FeatureTypeAttribute, String>> getAttributeList() {
List<Map<FeatureTypeAttribute, String>> attrsList = null;
final Element attrsRoot = rootElem.getChild("attributes");
final List<Element> attrs = attrsRoot.getChildren();
if (attrs != null) {
attrsList = new ArrayList<Map<FeatureTypeAttribute, String>>(attrs.size());
for (Element attr : attrs) {
Map<FeatureTypeAttribute, String> attrsMap = new HashMap<FeatureTypeAttribute, String>();
attrsList.add(attrsMap);
for (FeatureTypeAttribute at : FeatureTypeAttribute.values()) {
String key = at.toString();
attrsMap.put(at, attr.getChildText(key));
}
}
}
return attrsList;
}
public List<GSAttributeEncoder> getEncodedAttributeList() {
List<GSAttributeEncoder> attrsList = null;
final Element attrsRoot = rootElem.getChild("attributes");
final List<Element> attrs = attrsRoot.getChildren();
if (attrs != null) {
attrsList = new ArrayList<GSAttributeEncoder>(attrs.size());
for (Element attr : attrs) {
final GSAttributeEncoder attrEnc = new GSAttributeEncoder();
for (FeatureTypeAttribute at : FeatureTypeAttribute.values()) {
String key = at.toString();
attrEnc.setAttribute(at, attr.getChildText(key));
}
attrsList.add(attrEnc);
}
}
return attrsList;
}
/**
* Decodes the list of MetadataLinkInfo from the GeoServer Resource
*
* @author Emmanuel Blondel
*
* @return the list of GSMetadataLinkEncoder
*/
public List<GSMetadataLinkInfoEncoder> getEncodedMetadataLinkInfoList() {
List<GSMetadataLinkInfoEncoder> metaLinksList = null;
final Element metaLinksRoot = rootElem.getChild("metadataLinks");
final List<Element> metaLinks = metaLinksRoot.getChildren();
if (metaLinks != null) {
metaLinksList = new ArrayList<GSMetadataLinkInfoEncoder>(
metaLinks.size());
for (Element metaLink : metaLinks) {
final GSMetadataLinkInfoEncoder metaLinkEnc = new GSMetadataLinkInfoEncoder();
metaLinkEnc.setType(metaLink.getChildText(ResourceMetadataLinkInfo.type.name()));
metaLinkEnc.setMetadataType(metaLink.getChildText(ResourceMetadataLinkInfo.metadataType.name()));
metaLinkEnc.setContent(metaLink.getChildText(ResourceMetadataLinkInfo.content.name()));
metaLinksList.add(metaLinkEnc);
}
}
return metaLinksList;
}
// /**
// * @return the list of available attribute names
// */
// public List<String> getAttributeNames() {
// return getAttributes("name");
// }
//
// /**
// * @return a list of object which are String representation of Classes
// */
// public List<String> getAttributeBinding() {
// return getAttributes("binding");
// }
// /**
// * <attribute><br>
// * <name>NATION</name><br>
// * <minOccurs>0</minOccurs><br>
// * <maxOccurs>1</maxOccurs><br>
// * <nillable>true</nillable><br>
// * <binding>java.lang.Integer</binding><br>
// * <length>3</length><br>
// * </attribute><br>
// *
// * @param name
// * @return
// */
// private List<String> getAttributes(String name) {
// final Element attrsRoot = rootElem.getChild("attributes");
// final List<Element> attrs = attrsRoot.getChildren();
// List<String> attrNames = null;
// if (attrs != null) {
// attrNames = new ArrayList<String>(attrs.size());
// for (Element attr : attrs) {
// attrNames.add(attr.getChildText(name));
// }
// }
// return attrNames;
// }
}
|
package soft.chess.server.gameHall;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.List;
import soft.chess.dao.Dao;
import soft.chess.domain.Player;
import soft.chess.util.HallServerMsgUtil;
import soft.chess.util.JsonUtil;
public class QueryAllPlayersServer implements Runnable {
private DatagramPacket outpack;
private DatagramSocket socket;
private List<Player> players;
public QueryAllPlayersServer(DatagramPacket inpack,DatagramSocket socket) {
// TODO Auto-generated constructor stub
this.outpack=new DatagramPacket(new byte[0], 0,
inpack.getAddress(), inpack.getPort());
this.socket=socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
Dao dao=Dao.getInstance();
players=dao.queryPlayers();
String send_info=JsonUtil.ArrayToStr(players);
send_info=HallServerMsgUtil
.setAction(HallServerMsgUtil.QUERY_ALL_PLAYERS_ACTION, send_info);
outpack.setData(send_info.getBytes());
try {
socket.send(outpack);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package 문제풀이;
public class 문제2 {
public static void main(String[] args) {
// 1부터 1000까지 중 3씩 점프 만약 더한 값이 100이 넘으면 더하기 종료
// 5의 배수는 더하지 않습니다
int sum = 0;
int count = 0;
for (int i = 1; i <= 1000; i = i + 3) {
if (sum > 100) {
break; // for문 종룔
}
if (i % 5 == 0) {
continue; // 이번 횟수가 제외하고 for문은 계속 돈
}
sum = sum + i;
count++;
}
System.out.println(sum);
System.out.println(count);
}
}
|
package common.java.utils;
public class CommandLineArgExample {
public static void main(String[] args) {
if (args != null && args.length > 0) {
for (int i = 0; i < args.length; i++) {
String commandLineArg = args[i];
System.out.println("commandLineArg " + i + " : " + commandLineArg);
}
} else {
System.out.println("No command-line argument has been passed.");
}
}
}
|
package com.pingcap.tools.cdb.binlog.instance.core;
/**
* Created by iamxy on 2017/2/16.
*/
public interface CDBInstanceGenerator {
CDBInstance generate(String destination);
}
|
package pers.pbyang.myutil;
public class TradeUtil {
public static String trade_sql;
public static String TradeSql(String country, String chuanXing,
String daoYear1, String daoYear2, String liYear1, String liYear2) {
trade_sql = "select id, country,daoYear,daoMonth,daoDay,number,chuanXing,danWei,huoNum,junNum,liPort,zhPort,daoPort,afterPort,liNum,daoNum,liYear, liMonth,liDay from Trade1 where ";
if ((country != null) && (country != "")) {
trade_sql = trade_sql + "country =\"" + country + "\" and ";
}
if ((chuanXing != null) && (chuanXing != "")) {
trade_sql = trade_sql + "chuanXing =\"" + chuanXing + "\" and ";
}
if ((daoYear1 != null) && (daoYear1 != "")) {
trade_sql = trade_sql + "daoYear >=\"" + daoYear1 + "\" and ";
}
if ((daoYear2 != null) && (daoYear2 != "")) {
trade_sql = trade_sql + "daoYear <=\"" + daoYear2 + "\" and ";
}
if ((liYear1 != null) && (liYear1 != "")) {
trade_sql = trade_sql + "liYear >=\"" + liYear1 + "\" and ";
}
if ((liYear2 != null) && (liYear2 != "")) {
trade_sql = trade_sql + "liYear <=\"" + liYear2 + "\" and ";
}
trade_sql = trade_sql + "1=1";
return trade_sql;
}
public static void main(String[] args) {
System.out.println(TradeSql("C", "10", "1688","1711","1722", "1766"));
}
}
|
package in.swapnilsingh;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
League<Team<FootballPlayer>> footballLeague = new League<>("AFL");
Team<FootballPlayer> adelaideCrows = new Team<>("Adelaide Crows");
Team<FootballPlayer> melbourne = new Team<>("Melbourne");
Team<FootballPlayer> hawthorn = new Team<>("Hawthorn");
Team<FootballPlayer> freemantle = new Team<>("Freemantle");
Team<BaseballPlayer> baseballPlayerTeam = new Team<>("Chicago Cubs");
hawthorn.matchResult(freemantle, 1, 0);
hawthorn.matchResult(adelaideCrows, 3, 8);
adelaideCrows.matchResult(freemantle, 2, 1);
footballLeague.add(adelaideCrows);
footballLeague.add(melbourne);
footballLeague.add(hawthorn);
footballLeague.add(freemantle);
// footballLeague.add(baseballPlayerTeam);
footballLeague.showLeagueTable();
}
}
|
package com.cnk.travelogix.sapintegrations.chargeable.itemcharging.data;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for StateScheduleItemCode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="StateScheduleItemCode">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="blocked"/>
* <enumeration value="locked"/>
* <enumeration value="closed"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "StateScheduleItemCode")
@XmlEnum
public enum StateScheduleItemCode {
@XmlEnumValue("blocked")
BLOCKED("blocked"),
@XmlEnumValue("locked")
LOCKED("locked"),
@XmlEnumValue("closed")
CLOSED("closed");
private final String value;
StateScheduleItemCode(String v) {
value = v;
}
public String value() {
return value;
}
public static StateScheduleItemCode fromValue(String v) {
for (StateScheduleItemCode c: StateScheduleItemCode.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
|
package am.main.api;
import am.main.common.ConfigUtils;
import am.main.data.enums.Interface;
import am.main.data.enums.impl.AMS;
import am.main.exception.GeneralException;
import am.main.session.AppSession;
import am.main.spi.AMCode;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.text.MessageFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static am.main.common.ConfigParam.*;
import static am.main.data.enums.Interface.INITIALIZING_COMPONENT;
import static am.main.data.enums.impl.AME.*;
import static am.main.data.enums.impl.AMI.*;
import static am.main.data.enums.impl.AMP.AM_INITIALIZATION;
import static am.main.data.enums.impl.AMP.MESSAGE_HANDLER;
import static am.main.data.enums.impl.AMS.AM;
/**
* Created by ahmed.motair on 1/8/2018.
*/
@Singleton
public class MessageHandler {
@Inject private AppLogger logger;
private static final String CLASS = MessageHandler.class.getSimpleName();
private final AppSession appSession = new AppSession(AMS.AM, Interface.REST, MESSAGE_HANDLER);
private static MessageHandler instance;
private MessageHandler() {
}
public static MessageHandler getInstance() throws Exception{
if (instance == null){
synchronized(MessageHandler.class){
if (instance == null){
instance = new MessageHandler();
instance.load();
}
}
}
return instance;
}
private static Properties ERROR_MESSAGES = new Properties();
private static Properties INFO_MESSAGES = new Properties();
private static Properties WARNING_MESSAGES = new Properties();
@PostConstruct
private void load(){
String METHOD = "load";
AppSession session = new AppSession(AM, INITIALIZING_COMPONENT, AM_INITIALIZATION, CLASS, METHOD);
String componentName = COMPONENT.MESSAGE_HANDLER;
try {
logger.info(session, I_SYS_1, componentName);
ERROR_MESSAGES = ConfigUtils.readRemotePropertyFiles(session, logger, ERROR_MSG_CONFIG.FN_PATH);
logger.info(session, I_MH_1);
INFO_MESSAGES = ConfigUtils.readRemotePropertyFiles(session, logger, INFO_MSG_CONFIG.FN_PATH);
logger.info(session, I_MH_2);
WARNING_MESSAGES = ConfigUtils.readRemotePropertyFiles(session, logger, WARN_MSG_CONFIG.FN_PATH);
logger.info(session, I_MH_3);
logger.info(session, I_SYS_2, componentName);
} catch (Exception ex) {
logger.error(session, ex, E_SYS_1, componentName, ex.getMessage());
throw new IllegalStateException(session + E_SYS_1.getFullMsg(componentName, ex.getMessage()));
}
}
public String getMsg(AMCode amCode, Object ... args){
List<String> argList = new ArrayList<>();
for (Object arg :args)
argList.add(arg.toString());
return getMsg(amCode, argList);
}
public String getMsg(AMCode amCode, List<String> args) {
String METHOD = "getMsg";
AppSession session = appSession.updateSession(MESSAGE_HANDLER, CLASS, METHOD);
try {
logger.startDebug(session, amCode);
if (amCode == null)
throw new GeneralException(session, E_SYS_4);
logger.info(session, I_MH_8, amCode.getFullCode());
String message = getRawMsg(session, amCode);
message = formatMsg(session, message, args);
logger.info(session, I_MH_9, amCode.getFullCode());
logger.endDebug(session, message);
return message;
} catch(Exception ex){
throw new IllegalArgumentException(E_SYS_3.getFullMsg(amCode.getFullCode(), ex.getMessage()));
}
}
public String getRawMsg(AppSession appSession, AMCode amCode){
String METHOD = "getRawMsg";
AppSession session = appSession.updateSession(MESSAGE_HANDLER, CLASS, METHOD);
try {
logger.startDebug(session, amCode);
if (amCode == null)
throw new GeneralException(session, E_SYS_4);
logger.info(session, I_MH_4, amCode.getFullCode());
Properties propertiesFile = new Properties();
switch (amCode.getCodeType()){
case ERROR: propertiesFile = ERROR_MESSAGES; break;
case INFO: propertiesFile = INFO_MESSAGES; break;
case WARN: propertiesFile = WARNING_MESSAGES; break;
case CONFIGURATION: throw new GeneralException(session, E_MH_1);
}
String message = ConfigUtils.readValueFromPropertyFile(session, logger, propertiesFile,
amCode.getFullCode(), amCode.getCodeType().toString() + " Messages");
logger.info(session, I_MH_5, amCode.getFullCode());
logger.endDebug(session, message);
return message;
}catch (GeneralException ex){
if(ex.getErrorCode().equals(E_IO_8))
this.load();
throw new IllegalArgumentException(E_SYS_2.getFullMsg(amCode.getFullCode(), ex.getMessage()));
} catch(Exception ex){
throw new IllegalArgumentException(E_SYS_2.getFullMsg(amCode.getFullCode(), ex.getMessage()));
}
}
private String formatMsg(AppSession appSession, String message, List<String> args) throws Exception{
String METHOD = "formatMsg";
AppSession session = appSession.updateSession(MESSAGE_HANDLER, CLASS, METHOD);
try {
logger.startDebug(session, message, args);
logger.info(session, I_MH_6);
Matcher matcher = Pattern.compile("\\{[0-9]+\\}").matcher(message);
String _message = "";
Set<String> placeHolders = new HashSet<>();
while (matcher.find())
placeHolders.add(matcher.group());
if (placeHolders.size() == 0) {
if (args == null || args.size() == 0)
_message = message;
else
throw new GeneralException(session, E_MH_2);
} else if(args == null || placeHolders.size() != args.size())
throw new GeneralException(session, E_MH_4, (args != null ? args.toString() : "Null"), placeHolders.size());
else
_message = MessageFormat.format(message, args);
logger.info(session, I_MH_7);
logger.endDebug(session, _message);
return _message;
}catch (Exception ex){
if(ex instanceof GeneralException)
throw ex;
else
throw new GeneralException(session, ex, E_MH_5, message);
}
}
}
|
package database;
public class Bounty {
public int id;
public String title;
public String criteria;
public String description;
public double value;
public String expiration;
public Bounty(){
this.id = 0;
this.title = "";
this.criteria = "";
this.description = "";
this.value = 0;
this.expiration = "";
}
public Bounty(int id, String title, String criteria, String description, double value, String expiration)
{
this.id = id;
this.title = title;
this.criteria = criteria;
this.description = description;
this.value = value;
this.expiration = expiration;
}
public void setId(int id)
{
this.id = id;
}
public void setTitle(String title)
{
this.title = title;
}
public void setCriteria(String criteria)
{
this.criteria = criteria;
}
public void setDescription(String description)
{
this.description = description;
}
public void setValue(double value)
{
this.value = value;
}
public void setExpiration(String expiration)
{
this.expiration = expiration;
}
public int getId()
{
return id;
}
public String getTitle()
{
return title;
}
public String getCriteria()
{
return criteria;
}
public String getDescription()
{
return description;
}
public double getValue()
{
return value;
}
public String getExpiration()
{
return expiration;
}
}
|
package yincheng.gggithub.mvp.presenter;
import yincheng.gggithub.mvp.contract.PersonalContract;
/**
* Created by yincheng on 2018/6/14/18:11.
* github:luoyincheng
*/
public class PersonalPresenter extends RxPresenter<PersonalContract.View> implements
PersonalContract.Presenter {
}
|
package com.mctoybox.toybox.blocks;
import java.io.File;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import org.getspout.spoutapi.block.design.GenericCubeBlockDesign;
import org.getspout.spoutapi.material.block.GenericCuboidCustomBlock;
import org.getspout.spoutapi.player.SpoutPlayer;
import com.mctoybox.toybox.MainClass;
public class Stove extends GenericCuboidCustomBlock {
private MainClass mainClass;
public Stove(Plugin plugin) {
this(plugin, "Stove");
}
public Stove(Plugin plugin, String name) {
super(plugin, name);
this.mainClass = (MainClass) plugin;
this.setRotate(true);
String tempPath = mainClass.getDataFolder() + File.separator + "Resources" + File.separator + "Blocks" + File.separator + "Stove" + File.separator;
// TODO set up the design
this.setBlockDesign(new GenericCubeBlockDesign(mainClass, tempPath + "stove_front_on.png", 32));
}
@Override
public void onBlockDestroyed(World world, int x, int y, int z) {
mainClass.debugOutput("Stove destroyed!");
}
public boolean onBlockInteract(World world, int x, int y, int z, SpoutPlayer player) {
return true;
}
}
|
package com.coffeebeantech.social_login_example;
import org.brickred.socialauth.Profile;
import org.brickred.socialauth.android.DialogListener;
import org.brickred.socialauth.android.SocialAuthAdapter;
import org.brickred.socialauth.android.SocialAuthAdapter.Provider;
import org.brickred.socialauth.android.SocialAuthError;
import com.loopj.android.http.*;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends Activity {
// SocialAuth Component
SocialAuthAdapter adapter;
private Provider[] providers = new Provider[] {Provider.FACEBOOK, Provider.TWITTER, Provider.LINKEDIN};
// Android Components
Menu menu;
ImageButton facebookButton;
ImageButton twitterButton;
ImageButton linkedinButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create social-auth adapter
adapter = new SocialAuthAdapter(new ResponseListener());
// Add providers
adapter.addProvider(Provider.FACEBOOK, R.drawable.facebook);
adapter.addProvider(Provider.TWITTER, R.drawable.twitter);
adapter.addProvider(Provider.LINKEDIN, R.drawable.linkedin);
// Providers require setting user callback URL
adapter.addCallBack(Provider.TWITTER, "http://socialauth.in/socialauthdemo/socialAuthSuccessAction.do");
// Enable Provider
facebookButton = (ImageButton) findViewById(R.id.loginFacebook);
facebookButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
adapter.authorize(MainActivity.this, providers[0]);
}
});
twitterButton = (ImageButton) findViewById(R.id.loginTwitter);
twitterButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
adapter.authorize(MainActivity.this, providers[1]);
}
});
linkedinButton = (ImageButton) findViewById(R.id.loginLinkedin);
linkedinButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
adapter.authorize(MainActivity.this, providers[2]);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
this.menu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
private final class ResponseListener implements DialogListener {
@Override
public void onComplete(Bundle values) {
// Hardcoded data
final String appId = "???";
final String apiId = "???";
final String apiSecret = "???";
// Get name of provider after authentication
final String providerName = values.getString(SocialAuthAdapter.PROVIDER);
Log.d("SIDN", "Provider Name = " + providerName);
// Social-ID Now POST URL
final String sidnPostUrl = "https://api.socialidnow.com/v1/marketing/login/apps/"+appId+"/sign_ins/"+providerName;
// Social-ID Now request parameters
String accessToken = "";
String accessSecret = "";
accessToken = MainActivity.this.adapter.getCurrentProvider().getAccessGrant().getKey();
Log.d("SIDN", accessToken);
accessSecret = MainActivity.this.adapter.getCurrentProvider().getAccessGrant().getSecret();
if(accessSecret == null) accessSecret = "";
Log.d("SIDN", accessSecret);
RequestParams params = new RequestParams();
params.put("app_id", appId);
params.put("access_token", accessToken);
params.put("access_secret", accessSecret);
// Make request
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(apiId, apiSecret);
client.post(sidnPostUrl, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response)
{
Log.d("SIDN", response);
}
@Override
public void onFailure(Throwable e, String response)
{
Log.d("SIDN", response);
}
});
// Get profile data
Profile profileMap = MainActivity.this.adapter.getUserProfile();
String firstName = profileMap.getFirstName();
if(firstName == null) {
String[] tokens = profileMap.getFullName().split(" ");
if(tokens.length > 0) {
firstName = tokens[0];
}
}
Toast.makeText(MainActivity.this, "Hello " + firstName, Toast.LENGTH_LONG).show();
}
@Override
public void onError(SocialAuthError error) {
Log.d("SIDN", "Authentication Error: " + error.getMessage());
}
@Override
public void onCancel() {
Log.d("SIDN", "Authentication Cancelled");
}
@Override
public void onBack() {
Log.d("SIDN", "Dialog Closed by pressing Back Key");
}
}
}
|
package com.packers.movers.test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.Test;
@Test
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class UnitTest extends AbstractTestNGSpringContextTests {
}
|
package com.example.login;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
SQLiteDatabase db;
SQLiteOpenHelper openHelper;
EditText Phn,psd;
Button log,reg2;
Cursor cursor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login2);
openHelper= new Databasehelper(this);
db=openHelper.getReadableDatabase();
log=(Button) findViewById(R.id.button2);
reg2=(Button)findViewById(R.id.button3);
Phn=(EditText) findViewById(R.id.editText4);
psd=(EditText) findViewById(R.id.editText5);
reg2.setOnClickListener((new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
}}));
log.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Phnnmbr=Phn.getText().toString();
String pass=psd.getText().toString();
cursor=db.rawQuery("SELECT *FROM " + Databasehelper.TABLE_NAME + " WHERE " + Databasehelper.COL_1 + "=? AND " + Databasehelper.COL_3 + "=?" , new String[]{Phnnmbr,pass});
if (cursor != null) {
if(cursor.getCount()>0) {
cursor.moveToNext();
Toast.makeText(getApplicationContext(),"Login Successfull", Toast.LENGTH_LONG).show();
openActivity2();
}
else{
Toast.makeText(getApplicationContext(),"Login UnSuccessfull", Toast.LENGTH_LONG).show();
}
}
}
});
}
public void openActivity2(){
Intent intent= new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
|
/*
* Sparsh Bohra
* 16/11/2019
* TicTacToe
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class TicTacToe {
static ArrayList<Integer> plaPositions = new ArrayList<Integer>();
static ArrayList<Integer> cpuPositions = new ArrayList<Integer>();
public static void main(String[] args) {
//game board
char[][] playBoard = { {' ', '|', ' ', '|', ' '},
{'-', '+', '-', '+', '-'},
{' ', '|', ' ', '|', ' '},
{'-', '+', '-', '+', '-'},
{' ', '|', ' ', '|', ' '} };
//prints game board
printBoard(playBoard);
while(true) {
Scanner input = new Scanner (System.in);
System.out.print("Enter position (1-9): ");
//plaPos for player and cpuPos for cpu
int plaPos = input.nextInt();
while(plaPositions.contains(plaPos) || cpuPositions.contains(plaPositions)) {
System.out.println("Position taken. Choose another one.");
plaPos = input.nextInt();
}
//method to place piece
placeItem(playBoard, plaPos, "player");
//check winner
String result = findWinner();
if(result.length() > 0) {
System.out.println(result);
break;
}
//cpu plays are Random
Random rd = new Random();
int cpuPos = rd.nextInt(9) + 1;
while(plaPositions.contains(cpuPos) || cpuPositions.contains(cpuPos)) {
cpuPos = rd.nextInt(9) + 1;
}
placeItem(playBoard, cpuPos, "cpu");
//print final game board
printBoard(playBoard);
//check winner
result = findWinner();
if(result.length() > 0) {
System.out.println(result);
break;
}
}
}
//method to print game board
public static void printBoard(char[][] x) {
for (char[] row: x){
for (char col: row) {
System.out.print(col);
}
System.out.println();
}
}
//method to place piece
public static void placeItem(char[][] playBoard, int pos, String user) {
//default case
char piece = ' ';
//two players
if (user.equals("player")) {
piece = 'X';
plaPositions.add(pos);
}
else if (user.equals("cpu")) {
piece = 'O';
cpuPositions.add(pos);
}
switch(pos){
case 1:
playBoard[0][0] = piece;
break;
case 2:
playBoard[0][2] = piece;
break;
case 3:
playBoard[0][4] = piece;
break;
case 4:
playBoard[2][0] = piece;
break;
case 5:
playBoard[2][2] = piece;
break;
case 6:
playBoard[2][4] = piece;
break;
case 7:
playBoard[4][0] = piece;
break;
case 8:
playBoard[4][2] = piece;
break;
case 9:
playBoard[4][4] = piece;
break;
default:
break;
}
}
//method to check winner
public static String findWinner() {
//rows
List topRow = Arrays.asList(1, 2, 3);
List midRow = Arrays.asList(4, 5, 6);
List botRow = Arrays.asList(7, 8, 9);
//columns
List leftCol = Arrays.asList(1, 4, 7);
List midCol = Arrays.asList(2, 5, 8);
List rightCol = Arrays.asList(3, 6, 9);
//diagonals
List diag1 = Arrays.asList(1, 5, 9);
List diag2 = Arrays.asList(7, 5, 3);
List<List> winning = new ArrayList<List>();
winning.add(topRow);
winning.add(midRow);
winning.add(botRow);
winning.add(leftCol);
winning.add(midCol);
winning.add(rightCol);
winning.add(diag1);
winning.add(diag2);
for (List l : winning) {
if (plaPositions.containsAll(l)) {
return "Congrats! you won :)";
}
else if (cpuPositions.containsAll(l)) {
return "CPU wins! try again :(";
}
else if (plaPositions.size() + cpuPositions.size() == 9) {
return "That's a tie lmao :D";
}
}
return "";
}
}
|
package com.codegym.controller;
import com.codegym.model.Author;
import com.codegym.model.Blog;
import com.codegym.service.AuthorService;
import com.codegym.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class AuthorController {
@Autowired
private AuthorService authorService;
@Autowired
private BlogService blogService;
@GetMapping("/view-author/{id}")
public ModelAndView viewAuthor(@PathVariable Long id){
Author author = authorService.findById(id);
if (author == null) {
return new ModelAndView("/error.404");
}
Iterable<Blog> blogs = blogService.findByAllAuthor(author);
ModelAndView modelAndView = new ModelAndView("/author/view");
modelAndView.addObject("blog",blogs);
modelAndView.addObject("author",author);
return modelAndView;
}
@GetMapping("/create-author")
public ModelAndView showCreateAuthor(){
ModelAndView modelAndView = new ModelAndView("/author/create");
modelAndView.addObject("author",new Author());
return modelAndView;
}
@PostMapping("/create-author")
public ModelAndView saveAuthor(@ModelAttribute("author") Author author) {
authorService.save(author);
ModelAndView modelAndView = new ModelAndView("/author/create");
modelAndView.addObject("author",new Author());
modelAndView.addObject("message","Successfully!");
return modelAndView;
}
@GetMapping("/authors")
public ModelAndView listAuthor() {
Iterable<Author> authors = authorService.findAll();
ModelAndView modelAndView = new ModelAndView("/author/list");
modelAndView.addObject("author",authors);
return modelAndView;
}
@GetMapping("/edit-author/{id}")
public ModelAndView showEditForm(@PathVariable Long id) {
Author author = authorService.findById(id);
ModelAndView modelAndView = new ModelAndView("/author/edit");
modelAndView.addObject("author",author);
return modelAndView;
}
@PostMapping("/edit-author")
public ModelAndView updateAuthor(@ModelAttribute("author") Author author) {
authorService.save(author);
ModelAndView modelAndView = new ModelAndView("/author/edit");
modelAndView.addObject("author",author);
modelAndView.addObject("message","Successfully!");
return modelAndView;
}
@GetMapping("/delete-author/{id}")
public ModelAndView showDeleteForm(@PathVariable Long id) {
Author author = authorService.findById(id);
ModelAndView modelAndView = new ModelAndView("/author/delete");
modelAndView.addObject("author",author);
return modelAndView;
}
@PostMapping("/delete-author")
public String deleteAuthor(@ModelAttribute("author") Author author) {
authorService.remove(author.getId());
return "redirect:authors";
}
}
|
package com.zebra.pay.controller.auth;
import com.zebra.pay.controller.SimpleBaseController;
import com.zebra.pay.manager.admin.auth.SysUserManager;
import com.zebra.pay.po.auth.Role;
import com.zebra.pay.po.auth.SysUser;
import com.zebra.pay.utils.MD5Util;
import com.zebra.pay.utils.Page;
import com.zebra.pay.utils.spring.SpringSecurityUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 系统用户管理controller
*
* @author 2013159
*
*/
@Controller
@RequestMapping(value="/auth/sysUser")
public class SysUserMgrController extends SimpleBaseController<SysUser> {
@Autowired
private SysUserManager sysUserManager;
private static final Logger logger = Logger.getLogger(SysUserMgrController.class);
@RequestMapping(value="/main.do")
public String main(HttpServletResponse response,
HttpServletRequest request){
return "/auth/user/sysUser.jsp";
}
/**
* 列表页面
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/list.do")
public String List(HttpServletRequest request,
HttpServletResponse response,
Model model)throws Exception{
Page<SysUser> page = buildPage(request);
Map<String, Object> searchParams = buildParamsFromHttpRequest(request,page);
page = sysUserManager.searchResources(page,searchParams);
List<SysUser> users=page.getResults();
List<Role> selectedRoles = null;
for(SysUser user:users){
selectedRoles=sysUserManager.findRolesByUserId(user.getId());
user.setRoleList(selectedRoles);
}
page.setResults(users);
model.addAttribute("page", page);
return "/auth/user/list.jsp";
}
/**
* 新增页面
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/input.do")
public String input(HttpServletRequest request,
HttpServletResponse response,
Model model) {
Long id = 0L;
SysUser sysUser = null;
try {
String idStr = request.getParameter("id");
if(StringUtils.isNotBlank(idStr)){
id = Long.valueOf(idStr);
if(id>0){
sysUser = sysUserManager.findUserById(id,true,true);
}
}
} catch (Exception e) {
e.printStackTrace();
}
if(sysUser == null){
sysUser = new SysUser();
}
String admin = null;
if (SpringSecurityUtils.getCurrentUserLoginName().endsWith("admin")) {
admin = "0";
} else {
admin = "1";
}
model.addAttribute("sysUser", sysUser);
return "/auth/user/input.jsp";
}
/**
* 检测登录名是否可用
* @param request
* @param response
* @return
*/
@RequestMapping(value="/checkName.do")
public void checkName(HttpServletRequest request,
HttpServletResponse response) {
String newName = request.getParameter("loginName");
String oldName = request.getParameter("oldLoginName");
try {
boolean value = sysUserManager.checkName(newName,oldName);
response.getWriter().write(value+"");
response.getWriter().flush();
} catch (Exception e) {
throw new RuntimeException("请求处理异常");
}
}
/**
* 保存新增页面
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="/save.do")
public String save(HttpServletRequest request,
HttpServletResponse response,SysUser sysUser,
Model model) {
String passwordConfirm = request.getParameter("passwordConfirm");
String admin = request.getParameter("admin");
String error = "";
String msg = "";
if(sysUser==null){
error = "没有用户实体";
}else if(StringUtils.isBlank(admin)&&(StringUtils.isBlank(sysUser.getPassword())|| StringUtils.isBlank(passwordConfirm))) {
error = "密码和确认密码均不能为空";
}else if(StringUtils.isBlank(admin)&&(!sysUser.getPassword().equals(passwordConfirm))) {
error = "两次密码输入不一致";
}else {
sysUser.setEnabled(true);
if(StringUtils.isBlank(admin)){ //修改个人信息 ->保存
sysUser.setPassword(MD5Util.MD5Encode(sysUser.getPassword(), "UTF-8"));
}else {
if(sysUser.getId()==null || sysUser.getId()<=0){ //新增用户->保存
sysUser.setPassword(MD5Util.MD5Encode("111111", "UTF-8"));
}else { //修改用户 ->保存
SysUser sysUserOld = sysUserManager.findUserByLoginName(sysUser.getLoginName());
sysUser.setPassword(sysUserOld.getPassword());
}
}
sysUserManager.addOrUpdate(sysUser);
msg = "保存成功";
}
if(!StringUtils.isBlank(error))
model.addAttribute("error", error);
if(!StringUtils.isBlank(msg))
model.addAttribute("msg", msg);
model.addAttribute("sysUser", sysUser);
return "/auth/user/input.jsp";
}
/**
* 业务类型管理
* @param request
* @param response
* @return
* @throws Exception
*/
public String busiTypeMgr(HttpServletRequest request, HttpServletResponse response) throws Exception {
return "/auth/user/sysUserMgr.jsp";
}
/**
* 选择角色
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value="/findRolesByUserId.do")
public String findRolesByUserId(HttpServletRequest request,
HttpServletResponse response,Model model) {
Long id = 0L;
//查询用户没有选中所有的角色
List<Role> selectingRoles = null;
//查询已经选中的角色
List<Role> selectedRoles = null;
try {
id = Long.valueOf(request.getParameter("id"));
if(id>0){
selectedRoles = sysUserManager.findRolesByUserId(id);
}
selectingRoles = sysUserManager.findRolesNotForUserId(id);
} catch (Exception e) {
e.printStackTrace();
}
if(selectedRoles == null)
selectedRoles = new ArrayList<Role>();
model.addAttribute("selectingRoles", selectingRoles);
model.addAttribute("selectedRoles", selectedRoles);
model.addAttribute("id", id);
return "/auth/user/selectRole.jsp";
}
/**
* 保存角色的权限-AJAX
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value="/saveUserRoleRelationship.do")
@ResponseBody
public String saveUserRoleRelationship(HttpServletRequest request,
HttpServletResponse response) {
String msg = "";
String selectedRoles = request.getParameter("selectedRoles");
if(selectedRoles == null){
selectedRoles = "";
}
String[] selectedRolesArray = selectedRoles.split(",");
Long id = 0L;
try {
id = Long.valueOf(request.getParameter("id"));
sysUserManager.addUserRoles(id, selectedRolesArray);
msg = "保存成功";
} catch (Exception e) {
e.printStackTrace();
if(e.getMessage().equals("For input string: "+"\"\""))
msg="保存成功";
else {
msg = "保存失败";
}
}
return msg;
}
/**
* 初始化用户密码-AJAX
*
* @param request
* @param response
* @param model
* @return
*/
@RequestMapping(value="/initPassword.do")
@ResponseBody
public String initPassword(HttpServletRequest request,
HttpServletResponse response) {
String msg = "";
Long id = Long.valueOf(request.getParameter("id"));
if(id>0){
SysUser sysUser = sysUserManager.findUserById(id, false, false);
sysUser.setPassword(MD5Util.MD5Encode("111111", "UTF-8"));
sysUserManager.addOrUpdate(sysUser);
msg="初始化成功";
}else {
msg = "初始化失败";
}
return msg;
}
/**
*更新用户状态
* @param request
* @param response
* @return
*/
@RequestMapping(value="/updateStatus.do")
@ResponseBody
public String updateStatus(HttpServletRequest request,
HttpServletResponse response){
String msg="";
Long id=Long.valueOf(request.getParameter("id"));
String status=request.getParameter("status");
Boolean enable;
if(status.equals("true")){
enable=true;
}else {
enable=false;
}
if(id>0){
SysUser user=sysUserManager.findUserById(id, false, false);
user.setEnabled(enable);
sysUserManager.addOrUpdate(user);
msg="true";
}else {
msg="false";
}
return msg;
}
}
|
package com.serhii.cryptobook.chapter1;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import java.io.*;
import java.security.Key;
import java.security.SecureRandom;
public class SecretWriting {
public static void main(String[] args) throws Exception {
if (args.length < 2) {
System.out.println("Usage: SecretWriting -d|-e text");
return;
}
Key key;
try {
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("SecretKey.ser"));
key = (Key) objectInputStream.readObject();
objectInputStream.close();
} catch (FileNotFoundException e) {
KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
keyGenerator.init(new SecureRandom());
key = keyGenerator.generateKey();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("SecretKey.ser"));
objectOutputStream.writeObject(key);
objectOutputStream.close();
}
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
if (args[0].contains("e")) {
cipher.init(Cipher.ENCRYPT_MODE, key);
String inputString = args[1];
for (int i = 2; i < args.length; i++ ) {
inputString += " " + args[i];
}
byte[] inputChars = inputString.getBytes("UTF-8");
byte[] encodeChars = cipher.doFinal(inputChars);
BASE64Encoder base64Encoder = new BASE64Encoder();
String encodeString = base64Encoder.encode(encodeChars);
System.out.println(encodeString);
} else if (args[0].contains("d")) {
cipher.init(Cipher.DECRYPT_MODE, key);
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] encodeChars = base64Decoder.decodeBuffer(args[1]);
byte[] decodeChars = cipher.doFinal(encodeChars);
String decodeString = new String(decodeChars, "UTF-8");
System.out.println(decodeString);
}
}
}
|
package Management.HumanResources.test;
import Marketing.OrderCenterEntity.OrderCenter;
import Marketing.OrderEnity.Order;
import Marketing.OrderEnity.OrderCanInformation;
import Marketing.Promotion.Coupon;
import Marketing.Promotion.Sale.TwentyPercentOff;
import Presentation.Protocol.IOManager;
import Mediator.DepartmentMediator;
import Storage.StockCan;
import Storage.TransportationCan;
import java.util.ArrayList;
import java.util.Date;
/**
* TODO:本类应放在Department包内,由于现在没有此包,暂时放在这里,之后需要修改路径
* 运输部门单独的测试类
*
* @author 吴英豪
* @since 2021-10-26 12:02
*/
public class TransportDepartmentTest {
public static void main(String[] args) {
// init some values
DepartmentMediator departmentMediator = DepartmentMediator.getInstance();
String CanName = "黄桃罐头";
String customerAddress = "同济大学嘉定校区";
int count = 10;
int price = 200;
IOManager.getInstance().print(
"需要运输" + CanName + "到:"+customerAddress + ",数量为:" + count + ",单价为:" + price,
"需要運輸" + CanName + "到:"+customerAddress + ",數量为:" + count + ",單價为:" + price,
"need to transport" + CanName + "to"+customerAddress + "the count is:" + count + ",the price is:" + price
);
ArrayList<OrderCanInformation> orderCanInformationArrayList = new ArrayList<OrderCanInformation>();
orderCanInformationArrayList.add(new OrderCanInformation(CanName,count,price));
Coupon coupon = new Coupon(new TwentyPercentOff());
OrderCenter.getInstance().createOneOrder(
orderCanInformationArrayList, coupon, new Date(), customerAddress);
// 生成运输罐头
ArrayList<Order> orderList = departmentMediator.getPendingOrders();
for(Order order : orderList){
TransportationCan transportationCan = new TransportationCan(new Date(), customerAddress, order.getOrderId());
ArrayList<StockCan> stockCans = new ArrayList<StockCan>();
transportationCan.setStockCans(stockCans);
//运输罐头
departmentMediator.completeProductionOfOneOrder(order.getOrderId());
departmentMediator.transportCans(transportationCan);
}
}
}
|
import model.SimpleDice;
public class Test1 {
public static void main(String[] args) {
SimpleDice diceA = new SimpleDice(1);
SimpleDice diceB;
diceB = diceA;
diceB.setFaceValue(4);
System.out.println(diceA);
}
}
|
package mx.com.azaelmorales.yurtaapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import me.anwarshahriar.calligrapher.Calligrapher;
import mx.com.azaelmorales.yurtaapp.utilerias.Preferences;
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private BottomNavigationView bottomNavigationView;
private Toolbar toolbar;
private TextView txt_correo_panel;
private TextView txt_nombre_panel;
private ImageView imgFondo;
private TextView textViewCorreo;
private String correo;
private String nombre;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
/* FragmentManager fragmentManager=getSupportFragmentManager(); //fragment que inicia
fragmentManager.beginTransaction().replace(R.id.contenedor, new InicioFragment()).addToBackStack(null).commit();
getSupportActionBar().setTitle("Inicio");*/
imgFondo = (ImageView)findViewById(R.id.img_logofomdo);
int alphaAmount = 128; // Some value 0-255 where 0 is fully transparent and 255 is fully opaque
imgFondo.setAlpha(alphaAmount);
//pasar valores al segundo activity
/* Intent intent = getIntent();
Bundle b = intent.getExtras();
if(b!=null) {
correo = b.getString("CORREO");
nombre = b.getString("NOMBRE");
}*/
correo = Preferences.getPeferenceString(this,Preferences.PREFERENCE_EMPLEADO_CORREO);
nombre = Preferences.getPeferenceString(this,Preferences.PREFERENCE_EMPLEADO_NOMBRE);
}
/* @Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
getFragmentManager().popBackStack();
} else {
getFragmentManager().popBackStack();//No se porqué puse lo mismo O.o
}
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
txt_correo_panel= (TextView)findViewById(R.id.txt_panel_correo);
txt_nombre_panel = (TextView)findViewById(R.id.txt_panel_nombre);
txt_correo_panel.setText(correo);
txt_nombre_panel.setText(nombre);
Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this,"OpenSans-Regular.ttf",true);
return true;
}
/* @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentManager fragmentManager=getSupportFragmentManager();
if (id == R.id.nav_obras) {
Intent activity = new Intent(getApplicationContext(),ObrasActivity.class);
startActivity(activity);
} else if (id == R.id.nav_almacen) {
// fragmentManager.beginTransaction().replace(R.id.contenedor, new AlmacenFragment()).addToBackStack(null).commit();
//getSupportActionBar().setTitle("Almacen");
Intent intent = new Intent(getApplicationContext(),AlmacenActivity.class);
startActivity(intent);
}else if(id == R.id.nav_pedidos){
Intent intent = new Intent(getApplicationContext(),PedidosActivity.class);
startActivity(intent);
} else if (id == R.id.nav_empleado) {
Intent empleados_activity = new Intent(getApplicationContext(),EmpleadosActivity.class);
startActivity(empleados_activity);
} else if (id == R.id.nav_manual) {
} else if (id == R.id.nav_acerca ){
Intent activity = new Intent(getApplicationContext(),AboutActivity.class);
startActivity(activity);
}else if(id ==R.id.nav_cerrar_sesion){
Preferences.savePreferenceBoolean(HomeActivity.this,false,Preferences.PREFERENCE_ESTADO_SESION);
Intent intent = new Intent(HomeActivity.this,MainActivity.class);
startActivity(intent);
finish();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this,"OpenSans-Regular.ttf",true);
return true;
}
}
|
package com.storytime.client.lobby;
import de.novanic.eventservice.client.event.Event;
import de.novanic.eventservice.client.event.domain.Domain;
import de.novanic.eventservice.client.event.domain.DomainFactory;
public class UpdateLobbyUsersEvent implements Event {
private static final long serialVersionUID = 1L;
String username = "";
Domain domain = DomainFactory.getDomain("Lobby");
public String getUsername() {
return username;
}
public Domain getDomain() {
return domain;
}
public void setDomain(Domain domain) {
this.domain = domain;
}
public void setUsername(String username) {
this.username = username;
}
}
|
package com.aidn5.antigriefer.util;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IChatComponent;
public class McUtil {
public static void showMessage(String message) {
IChatComponent component = new ChatComponentText(message);
ChatStyle style = new ChatStyle();
style.setColor(EnumChatFormatting.YELLOW);
component.setChatStyle(style);
try {
Minecraft.getMinecraft().thePlayer.addChatMessage(component);
} catch (Exception e) {
// TODO: handle exception
}
}
public static void sendCommand(String command) {
Minecraft.getMinecraft().thePlayer.sendChatMessage(command);
}
}
|
package com.jayqqaa12.mobilesafe.service;
import java.util.ArrayList;
import java.util.List;
import android.app.ActivityManager;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import com.jayqqaa12.abase.annotation.view.FindEngine;
import com.jayqqaa12.abase.core.AbaseService;
import com.jayqqaa12.abase.core.Provider;
import com.jayqqaa12.abase.util.IntentUtil;
import com.jayqqaa12.abase.util.ManageUtil;
import com.jayqqaa12.abase.util.common.TAG;
import com.jayqqaa12.abase.util.media.KeyguardUtil;
import com.jayqqaa12.abase.util.sys.TaskUtil;
import com.jayqqaa12.mobilesafe.engine.space.AppLockEngine;
import com.jayqqaa12.mobilesafe.provider.AppLockProvider;
import com.jayqqaa12.mobilesafe.ui.space.lock.LockScreenActivity;
public class AppLockDogService extends AbaseService
{
@FindEngine
private AppLockEngine engine;
private Intent lockIntent;
private ActivityManager am;
private List<String> locks;
private List<String> passApps = new ArrayList<String>();
private MyBinder myBinder = new MyBinder();
@Override
public IBinder onBind(Intent intent)
{
return myBinder;
}
public class MyBinder extends Binder implements IAppLockDogService
{
public void callLock(String packname)
{
lock(packname);
}
public void callUnlock(String packname)
{
unlock(packname);
}
}
/**
* 重新开启对应用的保护
*
* @param packname
*/
private void lock(String packname)
{
if (passApps.contains(packname))
{
passApps.remove(packname);
}
}
@Override
public void onCreate()
{
super.onCreate();
getContentResolver().registerContentObserver(Uri.parse(Provider.CONTENT + AppLockProvider.AUTHORITIES), true, new MyObserver(new Handler()));
}
/**
* 临时停止对某个app的保护
*
* @param packname
*/
private void unlock(String packname)
{
passApps.add(packname);
}
@Override
protected void doTask()
{
locks = engine.getAllLocks();
lockIntent = new Intent(this, LockScreenActivity.class);
am = ManageUtil.getActivityManager();
while (engine.isOpenService())
{
try
{
String packname = TaskUtil.getTaskTopActivityPackName(am);
if (KeyguardUtil.isKeyguardRestricted())
{
if (passApps.size() > 0)
{
passApps.clear();
Log.i(TAG.SERVICE, "锁定的 程序 清空");
}
}
if (passApps.contains(packname)) continue;
if (locks.contains(packname))
{
lockIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i(TAG.SERVICE, packname + "这个被锁住了 哦");
lockIntent.putExtra("packname", packname);
startActivity(lockIntent);
}
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
private class MyObserver extends ContentObserver
{
public MyObserver(Handler handler)
{
super(handler);
}
@Override
public void onChange(boolean selfChange)
{
super.onChange(selfChange);
Log.i(TAG.SERVICE, "----------------------------------数据库内容变化了");
locks = engine.getAllLocks();
passApps.clear();
}
}
@Override
public void onDestroy()
{
IntentUtil.startService(this, MonitorService.class);
super.onDestroy();
}
}
|
package com.wincentzzz.project.template.springhack.services;
import com.wincentzzz.project.template.springhack.models.Doctor;
import org.springframework.data.domain.Page;
public interface DoctorService {
Page<Doctor> getAllDoctors(String doctorName, String specialization, Integer pageNumber);
Doctor getDoctor(Long id);
void addDoctor(Doctor patient);
void updateDoctor(Long id, Doctor doctor);
void deleteDoctor(Long id);
}
|
package com.youthchina.controller;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.io.IOException;
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class PdfByParagraph {
public String[] readParagraph(File file) throws IOException {
PDDocument document = PDDocument.load(file);
PDFTextStripper stripper = new PDFTextStripper();
stripper.setLineSeparator("");
stripper.setParagraphStart("/t");
stripper.setSortByPosition(true);
String resume = stripper.getText(document);
return resume.split(stripper.getParagraphStart());
}
@Test
public void test() throws IOException {
String path = "src/test/resources/Resume/夏锐思中文简历.pdf";
File file = new File(path);
String[] lines = readParagraph(file);
if (lines == null || lines.length == 0) {
Assert.fail();
}
for (int i = 0; i < lines.length; i++) {
System.out.println("line" + i + ":" + lines[i]);
}
}
}
|
package gr.athena.innovation.fagi.core.function;
import org.apache.jena.rdf.model.Literal;
/**
* Interface for a condition function that takes a single Literal parameter as input.
*
* @author nkarag
*/
public interface IFunctionOneParameter extends IFunction{
/**
* Evaluates the single Literal parameter function.
* @param value the input value.
* @return the evaluation result.
*/
public boolean evaluate(Literal value);
}
|
package sim.util;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import sim.ordemcompra.*;
public class OrdemCompraRelatorio extends RelatorioUtil {
@Override
public Collection preencheObjeto(Integer codigo) {
OrdemCompraRN ocRegra = new OrdemCompraRN();
List<OrdemCompra> lista = new ArrayList<OrdemCompra>();
lista.add(ocRegra.carregar(codigo));
return (Collection) lista ;
}
}
|
package com.naukri.imagecropper;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
import com.naukri.imagecropper.util.FileUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by akash.singla on 11/9/2015.
*/
public class Croper extends View {
private Point pointPosition = null;
private Point pointChange = null;
private Point pointStart = null;
private ImageCordinate imageCordinate = null;
private EdgeSelection edgeSelection = null;
private int selectedEdge = 0;
private Bitmap bitmap = null;
private int strokeWidth = 3;
private String readLocation = null;
private String writeLocation = null;
private static int MARGIN = 20;
private static float MIN_WIDTH = 100;
private static float MIN_HEIGHT = 100;
public Croper(Context context) {
super(context);
}
public Croper(Context context, AttributeSet attrs) {
super(context, attrs);
imageCordinate = new ImageCordinate();
pointPosition = new Point();
pointStart = new Point();
pointChange = new Point();
edgeSelection = new EdgeSelection();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(bitmap != null) {
// draw image.
drawImage(canvas);
// Un-Selected portion.
drawShadowEffect(canvas);
drawSelection(canvas);
}
}
/**
* Draw image.
*
* @param canvas
*/
private void drawImage(Canvas canvas) {
canvas.drawBitmap(bitmap, imageCordinate.startX, imageCordinate.startY, new Paint());
}
/**
* Draw Shadow effect
*
* @param canvas
*/
private void drawShadowEffect(Canvas canvas) {
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setAlpha(90);
canvas.drawRect(imageCordinate.startX, pointChange.bottom, imageCordinate.endX, imageCordinate.endY, paint);
canvas.drawRect(imageCordinate.startX, imageCordinate.startY, imageCordinate.endX, pointChange.top, paint);
canvas.drawRect(imageCordinate.startX, pointChange.top, pointChange.left, pointChange.bottom, paint);
canvas.drawRect(pointChange.right, pointChange.top, imageCordinate.endX, pointChange.bottom, paint);
}
/**
* Draw Image Selection
*
* @param canvas
*/
private void drawSelection(Canvas canvas) {
Paint paint = new Paint();
paint.setAlpha(0);
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(strokeWidth);
Paint paintRectangle = new Paint();
paintRectangle.setColor(Color.TRANSPARENT);
paintRectangle.setStrokeWidth(0);
// Draw selected portion of image.
canvas.drawRect(pointChange.left, pointChange.top, pointChange.right, pointChange.bottom, paint);
canvas.drawRect(pointChange.left + strokeWidth, pointChange.top + strokeWidth,
pointChange.right - strokeWidth, pointChange.bottom - strokeWidth, paintRectangle);
}
/**
* Get Croped bitmap image.
*
* @return Bitmap
*/
public void getImage() throws IOException {
int width = (int) (pointPosition.right - pointPosition.left);
int height = (int) (pointPosition.bottom - pointPosition.top);
Bitmap imageBitmap = Bitmap.createBitmap(bitmap, (int) (pointPosition.left - imageCordinate.startX),
(int) (pointPosition.top - imageCordinate.startY), width, height);
writeImage(imageBitmap);
}
/**
* Write image in writelocation path.
*
* @throws IOException
*/
private void writeImage(Bitmap imageBitmap) throws IOException {
FileOutputStream fileOutputStream = new FileOutputStream(new File(writeLocation));
imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
int action = event.getAction();
float getX = event.getX();
float getY = event.getY();
if (action == MotionEvent.ACTION_DOWN) {
if (!isTouchOnRectangle(getX, getY))
return false;
handleTouchActionDown(getX, getY);
} else if (action == MotionEvent.ACTION_MOVE) {
handleTouchActionMove(getX, getY);
} else if (action == MotionEvent.ACTION_UP) {
handleTouchActionUp();
}
return true;
}
private void handleTouchActionMove(float getX, float getY) {
float dx;
float dy;
// Get change in co-ordinate.
dx = (getX - pointStart.x);
dy = (getY - pointStart.y);
// For Move
if (selectedEdge == Edge.NO_EDGE && (isLeftRightScreen(dx) || isTopBottomScreen(dy))) {
handleMove(dx, dy);
}
// For Resizing.
else {
// check rectangle minimum size.
if (checkMin(dx, dy, selectedEdge)) {
// Left Bottom Corner.
handleLeftBottom(getSizeSquare(dx, dy), dy);
// Right Top Corner.
handleRightTop(getSizeSquare(dx, dy), dy, (int) imageCordinate.endX);
// Left Boundary.
handleLeft(dx);
// Right edge resizing.
handleRight(dx);
// Top Boundary resizing.
handleTop(dy);
// Bottom Boundary resizing.
handleBottom(dy);
}
}
invalidate();
}
/**
* Handle bottom edge for re-sizing.
*
* @param dy
*/
private void handleBottom(float dy) {
if (selectedEdge == Edge.BOTTOM && (((pointPosition.right + dy) <= imageCordinate.endX) &&
((pointPosition.bottom + dy) <= imageCordinate.endY))) {
pointChange.right = (pointPosition.right + dy);
pointChange.bottom = (pointPosition.bottom + dy);
edgeSelection.bottom = true;
} else if (selectedEdge == Edge.BOTTOM && edgeSelection.bottom) {
// rectangle touch the right screen edge, then stop resizing.
if ((pointPosition.right + dy) > imageCordinate.endX) {
float diff = (imageCordinate.endX - pointPosition.right);
pointChange.right = pointPosition.right + diff;
pointChange.bottom = pointPosition.bottom + diff;
edgeSelection.bottom = false;
}
// rectangle touch the bottom screen edge, then stop resizing.
else if (((pointPosition.bottom + dy) > imageCordinate.endY)) {
float diff = (imageCordinate.endY - pointPosition.bottom);
pointChange.right = pointPosition.right + diff;
pointChange.bottom = pointPosition.bottom + diff;
edgeSelection.bottom = false;
}
}
}
/**
* Handle top for resizing.
*
* @param dy
*/
private void handleTop(float dy) {
if (selectedEdge == Edge.Top && (((pointPosition.top + dy) >= imageCordinate.startY) &&
((pointPosition.left + dy) >= imageCordinate.startX))) {
pointChange.top = (pointPosition.top + dy);
pointChange.left = (pointPosition.left + dy);
edgeSelection.top = true;
} else if (selectedEdge == Edge.Top && edgeSelection.top) {
// rectangle touch the top screen edge, then stop resizing.
if (((pointPosition.top + dy) < imageCordinate.startY)) {
float diff = pointPosition.top - imageCordinate.startY;
pointChange.top = imageCordinate.startY;
pointChange.left = pointPosition.left - diff;
edgeSelection.top = false;
}
// rectangle touch the left screen edge, then stop resizing.
if ((pointPosition.left + dy) < imageCordinate.startX) {
float diff = pointPosition.left - imageCordinate.startX;
pointChange.top = pointPosition.top - diff;
pointChange.left = imageCordinate.startX;
edgeSelection.top = false;
}
}
}
/**
* Hanlde right edge for resizing.
*
* @param dx
*/
private void handleRight(float dx) {
if (selectedEdge == Edge.RIGHT && (((pointPosition.right + dx) <= imageCordinate.endX) &&
(((pointPosition.bottom + dx)) <= imageCordinate.endY))) {
pointChange.right = (pointPosition.right + dx);
pointChange.bottom = (pointPosition.bottom + dx);
edgeSelection.right = true;
} else if (selectedEdge == Edge.RIGHT && edgeSelection.right) {
// rectangle touch the right screen edge, then stop resizing.
if (((pointPosition.right + dx) > imageCordinate.endX)) {
float diff = imageCordinate.endX - pointPosition.right;
pointChange.right = imageCordinate.endX;
pointChange.bottom = pointPosition.bottom + diff;
edgeSelection.right = false;
}
// rectangle touch the bottom screen edge, then stop resizing.
if ((((pointPosition.bottom + dx)) > imageCordinate.endY)) {
float diff = imageCordinate.endY - pointPosition.bottom;
pointChange.bottom = imageCordinate.endY;
pointChange.right = pointPosition.right + diff;
edgeSelection.right = false;
}
}
}
/**
* Handle left edge for resizing.
*
* @param dx
*/
private void handleLeft(float dx) {
if (selectedEdge == Edge.LEFT && (((pointPosition.left + dx) >= imageCordinate.startX) &&
((pointPosition.top + dx) >= imageCordinate.startY))) {
pointChange.left = (pointPosition.left + dx);
pointChange.top = (pointPosition.top + dx);
edgeSelection.left = true;
} else if (selectedEdge == Edge.LEFT && edgeSelection.left) {
// rectangle touch the Left screen edge, then stop resizing. //
if (((pointPosition.left + dx) <= imageCordinate.startX)) {
float diff = pointPosition.left - imageCordinate.startX;
pointChange.left = imageCordinate.startX;
pointChange.top = pointPosition.top - diff;
edgeSelection.left = false;
}
// rectangle touch the top screen edge, then stop resizing.
if (((pointPosition.top + dx) < imageCordinate.startY)) {
float diff = pointPosition.top - imageCordinate.startY;
pointChange.top = imageCordinate.startY;
pointChange.left = pointPosition.left - diff;
edgeSelection.left = false;
}
}
}
/**
* Handle top right corner for resizing.
*
* @param sizeSquare
* @param dy
* @param i
*/
private void handleRightTop(float sizeSquare, float dy, int i) {
if (selectedEdge == Edge.RIGHT_TOP && (((pointPosition.top + dy) >= imageCordinate.startY)
&& ((pointPosition.right - dy) <= i))) {
float dz = sizeSquare;
pointChange.top = (pointPosition.top + dy);
pointChange.right = (pointPosition.right - dy);
edgeSelection.rightTop = true;
} else if (selectedEdge == Edge.RIGHT_TOP && edgeSelection.rightTop) {
// rectangle touch the top screen edge, then stop resizing.
if (((pointPosition.top + dy) < imageCordinate.startY)) {
float diff = pointPosition.top - imageCordinate.startY;
pointChange.top = imageCordinate.startY;
pointChange.right = pointPosition.right + diff;
edgeSelection.rightTop = false;
}
// rectangle touch the right screen edge, then stop resizing.
if (((pointPosition.right - dy) > i)) {
float diff = imageCordinate.endX - pointPosition.right;
pointChange.right = i;
pointChange.top = pointPosition.top - diff;
edgeSelection.rightTop = false;
}
}
}
/**
* Handle left bottom corner for resizing.
*
* @param sizeSquare
* @param dy
*/
private void handleLeftBottom(float sizeSquare, float dy) {
if (selectedEdge == Edge.LEFT_BOTTOM && ((((pointPosition.left - dy)) >= imageCordinate.startX) &&
(((pointPosition.bottom + dy)) <= imageCordinate.endY))) {
float dz = sizeSquare;
pointChange.left = (pointPosition.left - dy);
pointChange.bottom = (pointPosition.bottom + dy);
edgeSelection.leftBottom = true;
} else if (selectedEdge == Edge.LEFT_BOTTOM && edgeSelection.leftBottom) {
// rectangle touch the left screen edge, then stop resizing.
if ((((pointPosition.left - dy)) < imageCordinate.startX)) {
float diff = pointPosition.left - imageCordinate.startX;
pointChange.left = imageCordinate.startX;
pointChange.bottom = (pointPosition.bottom + diff);
edgeSelection.leftBottom = false;
}
// rectangle touch the bottom screen edge, then stop resizing.
if ((((pointPosition.bottom + dy)) > imageCordinate.endY)) {
float diff = imageCordinate.endY - pointPosition.bottom;
pointChange.bottom = imageCordinate.endY;
pointChange.left = pointPosition.left - diff;
edgeSelection.leftBottom = false;
}
}
}
/**
* Handle move
*
* @param dx
* @param dy
*/
private void handleMove(float dx, float dy) {
if (isLeftRightScreen(dx)) {
pointChange.left = (pointPosition.left + dx);
pointChange.right = (pointPosition.right + dx);
}
if (isTopBottomScreen(dy)) {
pointChange.top = (pointPosition.top + dy);
pointChange.bottom = (pointPosition.bottom + dy);
}
}
/**
* Handle touch UpAction: when user take finger from screen.
*/
private void handleTouchActionUp() {
selectedEdge = 0;
// set position variable.
pointPosition.left = pointChange.left;
pointPosition.right = pointChange.right;
pointPosition.top = pointChange.top;
pointPosition.bottom = pointChange.bottom;
// set size of rectangle
pointPosition.width = pointPosition.right - pointPosition.left;
pointPosition.height = pointPosition.bottom - pointPosition.top;
}
/**
* Handle Touch DownAction : when user start touch the screen.
*
* @param getX
* @param getY
*/
private void handleTouchActionDown(float getX, float getY) {
// Store user starting touch co-ordinate.
pointStart.x = getX;
pointStart.y = getY;
// If User select on any edge/ boundary.
if ((((pointChange.bottom - MARGIN) < getY) && ((pointChange.bottom + MARGIN) > getY)) &&
(((pointChange.left - MARGIN) < getX) && ((pointChange.left + MARGIN) > getX))) {
selectedEdge = Edge.LEFT_BOTTOM;
} else if ((((pointChange.top - MARGIN) < getY) && ((pointChange.top + MARGIN) > getY)) &&
(((pointChange.right - MARGIN) < getX) && ((pointChange.right + MARGIN) > getX))) {
selectedEdge = Edge.RIGHT_TOP;
} else if (((pointChange.left + MARGIN) > getX && (pointChange.left - MARGIN) < getX)) {
selectedEdge = Edge.LEFT;
} else if (((pointChange.right - MARGIN) < getX && (pointChange.right + MARGIN) > getX)) {
selectedEdge = Edge.RIGHT;
} else if (((pointChange.top - MARGIN) < getY && (pointChange.top + MARGIN) > getY)) {
selectedEdge = Edge.Top;
} else if (((pointChange.bottom - MARGIN) < getY && (pointChange.bottom + MARGIN) > getY)) {
selectedEdge = Edge.BOTTOM;
}
}
/**
* Check for minimum rectangel size.
*
* @param dx
* @param dy
* @param edge
* @return
*/
private boolean checkMin(float dx, float dy, int edge) {
switch (edge) {
case Edge.Top:
if (handleMinLeftTop(dx, dy))
return true;
break;
case Edge.LEFT:
if (handleMinLeftTop(dx, dy)) return true;
break;
case Edge.RIGHT:
if (handleMinRightBottom(dx, dy)) return true;
break;
case Edge.BOTTOM:
if (handleMinRightBottom(dx, dy)) return true;
break;
case Edge.LEFT_BOTTOM:
if (handleMinLeftBottom(dx, dy)) return true;
break;
case Edge.RIGHT_TOP:
if (handleMinRightTop(dx, dy)) return true;
break;
}
return false;
}
/**
* check minimum rectangle size when user touch on top or left edge.
*
* @param dx
* @param dy
* @return
*/
private boolean handleMinRightTop(float dx, float dy) {
if ((pointPosition.right - pointPosition.left + dx) >= MIN_WIDTH &&
((pointPosition.bottom - pointPosition.top - dy) >= MIN_HEIGHT))
return true;
else {
pointChange.right = (pointPosition.left + MIN_WIDTH);
pointChange.top = (pointPosition.bottom - MIN_WIDTH);
}
return false;
}
/**
* check minimum rectangle size when user touch on left and bottom corner.
*
* @param dx
* @param dy
* @return
*/
private boolean handleMinLeftBottom(float dx, float dy) {
if ((pointPosition.right - pointPosition.left - dx) >= MIN_WIDTH &&
((pointPosition.bottom - pointPosition.top + dy) >= MIN_HEIGHT))
return true;
else {
pointChange.left = (pointPosition.right - MIN_WIDTH);
pointChange.bottom = (pointPosition.top + MIN_WIDTH);
}
return false;
}
/**
* check minimum rectangle size when user touch on right or bottom edge.
*
* @param dx
* @param dy
* @return
*/
private boolean handleMinRightBottom(float dx, float dy) {
if (((pointPosition.right + dx) - (pointPosition.left)) >= MIN_WIDTH &&
(((pointPosition.bottom + dy) - pointPosition.top) >= MIN_HEIGHT)) {
return true;
} else {
pointChange.right = (pointPosition.left + MIN_WIDTH);
pointChange.bottom = (pointPosition.top + MIN_WIDTH);
}
return false;
}
/**
* check minimum rectangle size when user touch on left and top corner.
*
* @param dx
* @param dy
* @return
*/
private boolean handleMinLeftTop(float dx, float dy) {
if ((pointPosition.right - pointPosition.left - dx) >= MIN_WIDTH && ((pointPosition.bottom - pointPosition.top - dy) >= MIN_HEIGHT))
return true;
else {
pointChange.left = (pointPosition.right - MIN_WIDTH);
pointChange.top = (pointPosition.bottom - MIN_WIDTH);
}
return false;
}
/**
* Get Square size of rectangle.
*
* @param X
* @param Y
* @return
*/
private float getSizeSquare(float X, float Y) {
float squareX = (X * X);
float squareY = (Y * Y);
float Z = (float) Math.sqrt((squareX + squareY));
return Z;
}
/**
* @param diffX
* @return
*/
private boolean isLeftRightScreen(float diffX) {
boolean inScreen = true;
float leftEdge = pointPosition.left + diffX;
float rightEdge = (pointPosition.right + diffX);
if (leftEdge < imageCordinate.startX) {
inScreen = false;
pointChange.left = imageCordinate.startX;
pointChange.right = (imageCordinate.startX + pointPosition.width);
requestLayout();
}
if (rightEdge > imageCordinate.endX) {
inScreen = false;
pointChange.left = imageCordinate.endX - pointPosition.width;
pointChange.right = imageCordinate.endX;
requestLayout();
}
return inScreen;
}
/**
* @param diffY
* @return
*/
private boolean isTopBottomScreen(float diffY) {
boolean inScreen = true;
float topEdge = pointPosition.top + diffY;
float bottomEdge = (pointPosition.bottom + diffY);
if (topEdge < imageCordinate.startY) {
inScreen = false;
pointChange.top = imageCordinate.startY;
pointChange.bottom = (imageCordinate.startY + pointPosition.height);
requestLayout();
}
if (bottomEdge > imageCordinate.endY) {
inScreen = false;
pointChange.bottom = imageCordinate.endY;
pointChange.top = imageCordinate.endY - pointPosition.height;
requestLayout();
}
return inScreen;
}
/**
* Check user touch in rectangle area or not.
*
* @param x
* @param y
* @return
*/
private boolean isTouchOnRectangle(float x, float y) {
boolean isTouchOnRectangle = false;
if (((pointChange.left - MARGIN) <= x)
&& ((pointChange.right + MARGIN) >= x)
&& ((pointChange.top - MARGIN) <= y)
&& ((pointChange.bottom + MARGIN) >= y)
) {
isTouchOnRectangle = true;
}
return isTouchOnRectangle;
}
/**
* Get file read and write location.
*
* @param readLocation
* @param writeLocation
*/
public void setLocation(String readLocation, String writeLocation) {
this.readLocation = readLocation;
this.writeLocation = writeLocation;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// try {
setRectangleSize(w, h);
// }
// catch (FileNotFoundException e) {
// e.printStackTrace();
// Toast.makeText(getContext(), "Image not found at specified loation", Toast.LENGTH_SHORT).show();
// }
}
/**
* Set rectangle size.
*/
private void setRectangleSize(int width, int height)
{
try {
bitmap = FileUtil.decodeSampledBitmapFromResource(readLocation, width, height);
} catch (IOException e) {
e.printStackTrace();
}
if(bitmap == null)
{
Activity cropperActivity = (Activity) getContext();
cropperActivity.setResult(Activity.RESULT_CANCELED);
cropperActivity.finish();
}
else {
imageCordinate.width = bitmap.getWidth();
imageCordinate.height = bitmap.getHeight();
boolean isSizeGreater = false;
// check image size is greated than screen size or not.
if (imageCordinate.width > getWidth() || imageCordinate.height > getHeight()) {
isSizeGreater = true;
}
// if image size is greated than screen size, then reduce the image size according the aspect ratio of image.
if (isSizeGreater) {
// ratioY = screenHeight / Image Height.
float ratioY = (getHeight() / imageCordinate.height);
// ratioX = screenWidth / Image Width;
float ratioX = (getWidth() / imageCordinate.width);
// get min ration, so image can fit in screen.
float aspectRatio = Math.min(ratioX, ratioY);
// calculate new image size.
imageCordinate.width = (aspectRatio * imageCordinate.width);
imageCordinate.height = (aspectRatio * imageCordinate.height);
// resize image bitmap according to new size.
bitmap = Bitmap.createScaledBitmap(bitmap, (int) imageCordinate.width, (int) imageCordinate.height, false);
}
// get Image starting X,Y co-ordinate.
imageCordinate.startX = ((getWidth() - imageCordinate.width) / 2);
imageCordinate.startY = ((getHeight() - imageCordinate.height) / 2);
imageCordinate.endX = (imageCordinate.startX + imageCordinate.width);
imageCordinate.endY = (imageCordinate.startY + imageCordinate.height);
float size = imageCordinate.height;
if (imageCordinate.height > imageCordinate.width) {
size = imageCordinate.width;
}
int sideSpace = (int) (size * 0.10f);
size = (size - (2 * sideSpace));
MIN_HEIGHT = size / 5;
MIN_WIDTH = size / 5;
MARGIN = (int) (size / 20);
// set changable values.
pointChange.left = imageCordinate.startX + sideSpace;
pointChange.top = imageCordinate.startY + sideSpace;
pointChange.right = pointChange.left + size;
pointChange.bottom = pointChange.top + size;
// set position variables
pointPosition.left = pointChange.left;
pointPosition.right = pointChange.right;
pointPosition.bottom = pointChange.bottom;
pointPosition.top = pointChange.top;
// set height and width of rectangle.
pointPosition.width = size;
pointPosition.height = size;
}
}
}
|
package com.trainingmarket.bean;
public class UserBean {
private String email = null;
private String user = null;
private String telNum = null;
private String password = null;
private String name = null;
private String sex = null;
private String photo = null;
private String birthday = null;
private String height = null;
private String weight = null;
public void setEmail(String email){
this.email = email;
}
public String getEmail(){
return this.email;
}
public void setUser(String user){
this.user = user;
}
public String getUser(){
return this.user;
}
public void setTelNum(String telNum){
this.telNum = telNum;
}
public String getTelNum(){
return this.telNum;
}
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return this.password;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setSex(String sex){
this.sex = sex;
}
public String getSex(){
return this.sex;
}
public void setPhoto(String photo){
this.photo = photo;
}
public String getPhoto(){
return this.photo;
}
public void setBirthday(String birthday){
this.birthday = birthday;
}
public String getBirthday(){
return this.birthday;
}
public void setHeight(String height){
this.height = height;
}
public String getHeight(){
return this.height;
}
public void setWeight(String weight){
this.weight = weight;
}
public String getWeight(){
return this.weight;
}
}
|
public class Main {
public static void main(String[] args) {
// Detta är en lektionsuppgift, hamnade i hemläxor då jag inte tänkte särskilt mycket när jag skapade filen.
lol();
min(2, 4);
count(4);
kelvin(20);
ageControl(99);
stair(4);
}
/**
* Task 1, prints "HAHAHAHAHAHAHA"
*/
public static void lol() {
System.out.println("HAHAHAHAHAHAHA");
}
/**
* Prints the smallest value out of a and b.
* @param a - An integer
* @param b - An integer
* @return Returns the smallest value of a and b.
*/
public static int min(int a, int b) {
if(a < b){
return a;
}
else {
return b;
}
}
/**
*
* @param n
*/
public static void count(int n){
for(int i = 1; i <= n; i++){
System.out.println(i);
}
}
/**
*
* @param celsius
* @return
*/
public static double kelvin(double celsius){
double kelvin = celsius + 273.15;
return kelvin;
}
/**
* Don't judge me please, this is what the task tolddd me to do.
* @param age
*/
public static void ageControl(int age){
if(0 < age && age <= 5) {
System.out.println("Småbarn får inte göra något.");
}
else if(6 <= age && age <= 12) {
System.out.println("Du får spela Fortnite.");
}
else if(13 <= age && age <= 14){
System.out.println("Du är tonåring.");
}
else if(15 <= age && age <= 17){
System.out.println("Du får köra moppe.");
}
else if(18 <= age && age <= 20){
System.out.println("Du får köra bil.");
}
else if(21 <= age && age <= 64){
System.out.println("Du får vuxenstraff om du gör något dumt.");
}
else if(65 <= age && age <= 99){
System.out.println("Du är pensionär.");
}
else if(100 < age){
System.out.println("R.I.P?");
}
}
/**
*
* @param steps
*/
public static void stair(int steps){
for(int i = 1; i <= steps; i++) {
for(int j = 0; j < i; j++) {
System.out.print("X");
}
System.out.println();
}
}
}
|
package com.tencent.mm.plugin.remittance.model;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.ja;
import com.tencent.mm.protocal.c.jb;
import com.tencent.mm.sdk.platformtools.x;
public final class f extends l implements k {
private e diJ;
private b eAN;
public jb mwZ;
public f(String str, String str2, String str3, int i, com.tencent.mm.bk.b bVar, String str4) {
a aVar = new a();
aVar.dIG = new ja();
aVar.dIH = new jb();
aVar.dIF = 1680;
aVar.uri = "/cgi-bin/mmpay-bin/busif2factqry";
aVar.dII = 0;
aVar.dIJ = 0;
this.eAN = aVar.KT();
ja jaVar = (ja) this.eAN.dID.dIL;
jaVar.myl = str3;
jaVar.rcD = str;
jaVar.rcE = str2;
jaVar.rcI = i;
jaVar.rkr = bVar;
jaVar.rcF = str4;
x.i("MicroMsg.NetSceneBusiF2fActQry", "NetSceneBusiF2fPayCheck, f2fId: %s, transId: %s, amount: %s", new Object[]{str, str2, Integer.valueOf(i)});
}
public final int getType() {
return 1680;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.eAN, this);
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.i("MicroMsg.NetSceneBusiF2fActQry", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str});
this.mwZ = (jb) ((b) qVar).dIE.dIL;
x.i("MicroMsg.NetSceneBusiF2fActQry", "ret_code: %s, ret_msg: %s", new Object[]{Integer.valueOf(this.mwZ.hwV), this.mwZ.hwW});
if (this.diJ != null) {
this.diJ.a(i2, i3, str, this);
}
}
}
|
package com.test;
public class Student {
public String getName() {
return name;
}
public String getSubject() {
return subject;
}
public double getMark() {
return mark;
}
public String name=null;
public String subject=null;
public double mark=0.0;
public Student(String name,String subject ,double mark)
{
this.name=name;
this.subject=subject;
this.mark=mark;
}
@Override
public String toString()
{
return "\n name ="+name+",subject ="+subject+",mark ="+mark;
}
}
|
/**
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
*/
//cpp version : (recursive)
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
int lLength = maxDepth(root->left);
int rLength= maxDepth(root->right);
if(lLength>rLength)
return lLength+1;
else
return rLength+1;
}
//non recursive :
int maxDepth(TreeNode *root)
{
if(root == NULL)
return 0;
int res = 0;
queue<TreeNode *> q;
q.push(root);
while(!q.empty())
{
++ res;
for(int i = 0, n = q.size(); i < n; ++ i)
{
TreeNode *p = q.front();
q.pop();
if(p -> left != NULL)
q.push(p -> left);
if(p -> right != NULL)
q.push(p -> right);
}
}
return res;
}
|
package de.shm.fangbuch;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private double longtitude = 0;
private double latitude = 0;
private LocationManager locationManager;
private LocationListener locationListener;
@Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
@Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 500, locationListener);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addFishFragment();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longtitude = location.getLongitude();
Log.d("MAIN_ACTIVITY",location.toString());
Weather weather = (Weather) getSupportFragmentManager().findFragmentByTag(Weather.WEATHER_FRAGMENT);
if(weather != null) {
weather.upDateLocation(longtitude, latitude);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},MY_);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 300000, 500, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if( location!= null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
} else {
latitude = 0;
longtitude = 0;
}
startFragment();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_add){
addFishFragment();
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void startFragment(){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Start start= Start.newInstance(longtitude,latitude);
transaction.replace(R.id.fragment_container,start,"start_fragment");
transaction.commit();
}
private void addFishFragment(){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
AddFish addFish = AddFish.newInstance(longtitude,latitude);
transaction.replace(R.id.fragment_container,addFish);
transaction.addToBackStack(null);
transaction.commit();
}
}
|
package com.hjs.study.model;
import com.google.gson.annotations.SerializedName;
public class Stock {
public Stock(String stockCode, String stockName){
this.stockCode = stockCode;
this.stockName = stockName;
}
/*public Stock(String selectDiv, String stockCode, String stockName, String tradeFlag, String tradeDate, String tradeTime, String tradePrice, String profitRate,
String fluctuationRate, String elapsedDays, String includeDttm, String excluded, String analCount, String hasNewAnalYn, String qnaCount, String hasNewQnaYn){
this.selectDiv = selectDiv;
this.stockCode = stockCode;
this.stockName = stockName;
this.tradeFlag = tradeFlag;
this.tradeDate = tradeDate;
this.tradeTime = tradeTime;
this.tradePrice = tradePrice;
this.profitRate = profitRate;
this.fluctuationRate = fluctuationRate;
this.elapsedDays = elapsedDays;
this.includeDttm = includeDttm;
this.excluded = excluded;
this.analCount = analCount;
this.hasNewAnalYn = hasNewAnalYn;
this.qnaCount = qnaCount;
this.hasNewQnaYn = hasNewQnaYn;
}*/
@SerializedName("selectDiv")
private String selectDiv;
@SerializedName("stockCode")
private String stockCode;
@SerializedName("stockName")
private String stockName;
@SerializedName("tradeFlag")
private String tradeFlag;
@SerializedName("tradeDate")
private String tradeDate;
@SerializedName("tradeTime")
private String tradeTime;
@SerializedName("tradePrice")
private String tradePrice;
@SerializedName("profitRate")
private String profitRate;
@SerializedName("fluctuationRate")
private String fluctuationRate;
@SerializedName("elapsedDays")
private String elapsedDays;
@SerializedName("includeDttm")
private String includeDttm;
@SerializedName("excluded")
private String excluded;
@SerializedName("analCount")
private String analCount;
@SerializedName("hasNewAnalYn")
private String hasNewAnalYn;
@SerializedName("qnaCount")
private String qnaCount;
@SerializedName("hasNewQnaYn")
private String hasNewQnaYn;
public String getSelectDiv() {
return selectDiv;
}
public void setSelectDiv(String selectDiv) {
this.selectDiv = selectDiv;
}
public String getStockCode() {
return stockCode;
}
public void setStockCode(String stockCode) {
this.stockCode = stockCode;
}
public String getStockName() {
return stockName;
}
public void setStockName(String stockName) {
this.stockName = stockName;
}
public String getTradeFlag() {
return tradeFlag;
}
public void setTradeFlag(String tradeFlag) {
this.tradeFlag = tradeFlag;
}
public String getTradeDate() {
return tradeDate;
}
public void setTradeDate(String tradeDate) {
this.tradeDate = tradeDate;
}
public String getTradeTime() {
return tradeTime;
}
public void setTradeTime(String tradeTime) {
this.tradeTime = tradeTime;
}
public String getTradePrice() {
return tradePrice;
}
public void setTradePrice(String tradePrice) {
this.tradePrice = tradePrice;
}
public String getProfitRate() {
return profitRate;
}
public void setProfitRate(String profitRate) {
this.profitRate = profitRate;
}
public String getFluctuationRate() {
return fluctuationRate;
}
public void setFluctuationRate(String fluctuationRate) {
this.fluctuationRate = fluctuationRate;
}
public String getElapsedDays() {
return elapsedDays;
}
public void setElapsedDays(String elapsedDays) {
this.elapsedDays = elapsedDays;
}
public String getIncludeDttm() {
return includeDttm;
}
public void setIncludeDttm(String includeDttm) {
this.includeDttm = includeDttm;
}
public String getExcluded() {
return excluded;
}
public void setExcluded(String excluded) {
this.excluded = excluded;
}
public String getAnalCount() {
return analCount;
}
public void setAnalCount(String analCount) {
this.analCount = analCount;
}
public String getHasNewAnalYn() {
return hasNewAnalYn;
}
public void setHasNewAnalYn(String hasNewAnalYn) {
this.hasNewAnalYn = hasNewAnalYn;
}
public String getQnaCount() {
return qnaCount;
}
public void setQnaCount(String qnaCount) {
this.qnaCount = qnaCount;
}
public String getHasNewQnaYn() {
return hasNewQnaYn;
}
public void setHasNewQnaYn(String hasNewQnaYn) {
this.hasNewQnaYn = hasNewQnaYn;
}
}
|
package cn.canlnac.onlinecourse.data.repository;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import cn.canlnac.onlinecourse.data.ApplicationTestCase;
import cn.canlnac.onlinecourse.data.entity.RegisterEntity;
import cn.canlnac.onlinecourse.data.entity.mapper.ChatListEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.CommentListEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.CourseListEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.FollowerEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.LearnRecordListEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.LoginEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.MessageEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.MessageListEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.ProfileEntityDataMapper;
import cn.canlnac.onlinecourse.data.entity.mapper.UserEntityDataMapper;
import cn.canlnac.onlinecourse.data.repository.datasource.UserDataStore;
import cn.canlnac.onlinecourse.data.repository.datasource.UserDataStoreFactory;
import rx.Observable;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verify;
/**
* 用户储存测试用例.
*/
public class UserDataRepositoryTest extends ApplicationTestCase {
private UserDataRepository userDataRepository;
@Mock private UserDataStoreFactory mockUserDataStoreFactory;
@Mock private UserDataStore mockUserDataStore;
@Mock private UserEntityDataMapper mockUserEntityDataMapper;
@Mock private LoginEntityDataMapper mockLoginEntityDataMapper;
@Mock private ProfileEntityDataMapper mockProfileEntityDataMapper;
@Mock private MessageListEntityDataMapper mockMessageListEntityDataMapper;
@Mock private MessageEntityDataMapper mockMessageEntityDataMapper;
@Mock private LearnRecordListEntityDataMapper mockLearnRecordListEntityDataMapper;
@Mock private FollowerEntityDataMapper messageFollowerEntityDataMapper;
@Mock private ChatListEntityDataMapper chatListEntityDataMapper;
@Mock private CourseListEntityDataMapper courseListEntityDataMapper;
@Mock private CommentListEntityDataMapper commentListEntityDataMapper;
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
userDataRepository = new UserDataRepository(
mockUserDataStoreFactory,
mockLoginEntityDataMapper,
mockProfileEntityDataMapper,
mockMessageListEntityDataMapper,
mockMessageEntityDataMapper,
mockLearnRecordListEntityDataMapper,
messageFollowerEntityDataMapper,
chatListEntityDataMapper,
courseListEntityDataMapper,
commentListEntityDataMapper
);
given(mockUserDataStoreFactory.create()).willReturn(mockUserDataStore);
}
/**
* 测试注册
*/
@Test
public void testUserCase() {
RegisterEntity registerEntity = new RegisterEntity();
registerEntity.setUserId(1);
given(mockUserDataStore.register("username", "password")).willReturn(Observable.just(1));
userDataRepository.register("username", "password");
verify(mockUserDataStoreFactory).create();
verify(mockUserDataStore).register("username", "password");
}
}
|
package MyTest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Author: fangxueshun
* Description:
* Date: 2017/6/16
* Time: 18:20
*/
public class SearchFIle {
static String path = "D:\\workspace\\code\\news-crawler\\crawler-feeler\\crawler-feeler-text\\src\\main\\java\\com\\onemt\\news\\crawler\\feeler\\text\\processor";
static String encoding = "utf-8";
static String logPath = "C:\\Users\\Administrator\\Desktop\\临时\\default (7)";
public static void main(String[] args) throws Exception {
File file = new File(logPath);
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), encoding));
String line = null;
while ((line = reader.readLine()) != null) {
if (line.contains("Download file success:"))
System.out.println("\""+line.split("Download file success:")[1]+"\"");
}
reader.close();
// File[] files = file.listFiles();
// for(File file1:files){
// if(!file1.isDirectory()){
// String name = file1.getName();
// String content = ReadWriteFileWithEncode.read(file1.getPath(),encoding);
// if(content.contains(".setCharset(\"UTF-8\")")){
// System.out.println("UPDATE crawler_media_category AS p set p.charset = 'UTF-8' WHERE p.processor = "+name.replace(".java",""));
// }
//// else {
//// System.out.println(name+":null");
//// }
// }
// }
}
}
|
package sos.pojo.dto;
public class UserEmployee extends Person {
private String username,password;
private Branch branch;
public UserEmployee(){}
public UserEmployee(String name, String surname, String phone,
String username, String password, Branch branch) {
super(name, surname, phone);
this.username = username;
this.password = password;
this.branch = branch;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Branch getBranch() {
return branch;
}
public void setBranch(Branch branch) {
this.branch = branch;
}
}
|
package ru.rchol.springgo.modelwork;
import org.springframework.stereotype.Component;
import ru.rchol.springgo.model.Visitors;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
import java.util.List;
@Component
@Transactional
public class VisitorsDAOImpl {
@PersistenceContext
private EntityManager entityManager;
public VisitorsDAOImpl() {
}
public List<Visitors> getAllVisitors(){
return entityManager.createQuery("from Visitors", Visitors.class).getResultList();
}
public void addVisitor(Visitors visitors){
entityManager.persist(visitors);
}
}
|
package cse360assign3;
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculatorTest {
@Test
public void testCalculator() {
Calculator test = new Calculator();
assertNotNull(test);
}
@Test
public void testGetTotal() {
Calculator test = new Calculator();
assertEquals(0, test.getTotal());
}
@Test
public void testAdd() {
Calculator test = new Calculator();
test.add(5);
assertEquals(5, test.getTotal());
}
@Test
public void testSubtract() {
Calculator test = new Calculator();
test.subtract(3);
assertEquals(-3, test.getTotal());
}
@Test
public void testMultiply() {
Calculator test = new Calculator();
test.multiply(6);
assertEquals(0, test.getTotal());
test.add(2);
test.multiply(6);
assertEquals(12, test.getTotal());
}
@Test
public void testDivide() {
Calculator test = new Calculator();
test.divide(0);
assertEquals(0, test.getTotal());
test.add(24);
test.divide(12);
assertEquals(2, test.getTotal());
}
@Test
public void testGetHistory() {
Calculator test = new Calculator();
assertEquals("0", test.getHistory());
test.add(20);
test.subtract(5);
test.multiply(2);
test.divide(5);
test.add(2);
assertEquals("0 + 20 - 5 * 2 / 5 + 2", test.getHistory());
}
}
|
package hotelBooking;
class PageObjects {
static String LANDING_PAGE_HEADER = "jumbotron";
static String BOOKING_FORM = "bookings";
static String FIRST_NAME_LABEL = "#bookings > div:nth-child(1) > div:nth-child(1) > h3";
static String SURNAME_LABEL = "#bookings > div:nth-child(1) > div:nth-child(2) > h3";
static String PRICE_LABEL = "#bookings > div:nth-child(1) > div:nth-child(3) > h3";
static String DEPOSIT_LABEL = "#bookings > div:nth-child(1) > div:nth-child(4) > h3";
static String CHECK_IN_DATE_LABEL = "#bookings > div:nth-child(1) > div:nth-child(5) > h3";
static String CHECK_OUT_DATE_LABEL = "#bookings > div:nth-child(1) > div:nth-child(6) > h3";
static String FIRST_NAME_TEXTFIELD = "firstname";
static String SURNAME_TEXT_FIELD = "lastname";
static String PRICE_TEXTFIELD = "totalprice";
static String DEPOSIT_TEXTFIELD = "depositpaid";
static String DEPOSIT_FALSE = "#depositpaid > option:nth-child(2)";
static String CHECKIN_TEXTFIELD = "checkin";
static String CHECKOUT_TEXTFIELLD = "checkout";
static String SAVE_BUTTON = "#form > div > div:nth-child(7) > input[type=button]";
static String DELETE_BUTTON = "Delete";
static String CHECK_IN_PREVIOUS_MONTH = "#ui-datepicker-div > div > a.ui-datepicker-prev.ui-corner-all > span";
static String CHECK_IN_NEXT_MONTH = "#ui-datepicker-div > div > a.ui-datepicker-next.ui-corner-all > span";
static String CHECK_IN_DAY = "#ui-datepicker-div > table > tbody > tr:nth-child(5) > td:nth-child(6) > a";
static String CHECK_OUT_PREVIOUS_MONTH = "#ui-datepicker-div > div > a.ui-datepicker-prev.ui-corner-all > span";
static String CHECK_OUT_NEXT_MONTH = "#ui-datepicker-div > div > a.ui-datepicker-next.ui-corner-all > span";
static String CHECK_OUT_DAY ="#ui-datepicker-div > table > tbody > tr:nth-child(5) > td:nth-child(7) > a";
static String NAME_ENTRY = "div:nth-child(1) > p";
static String NEW_ENTRY_DELETE = "div:nth-child(7) > input:nth-child(1)";
static String RECORDS = "row";
static String BUTTONS = "input[type='button']";
}
|
package com.shopify.api.lotte.delivery;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
@Data
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class LotteDeliveryResultList {
private String status; // success /
private String message; // Invalid Token Error
private String code; // EGTA4011 /
private List<LotteDeliveryResult> rtnList = new ArrayList<>();
//------------------------
public int size() {
return rtnList.size();
}
public LotteDeliveryResult get(int idx) {
if ( idx < rtnList.size() ) {
return rtnList.get(idx);
} else {
return null;
}
}
}
|
package com.cxjd.nvwabao.fragment.findFunctions.OneHundred;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.TextView;
import com.cxjd.nvwabao.R;
/**
* 100种病症不宜食物 -- R
*/
public class S extends Fragment {
//网格布局
GridLayout gridLayout1;
GridLayout gridLayout2;
GridLayout gridLayout3;
GridLayout gridLayout4;
GridLayout gridLayout5;
//定义网格中的数据
String[] s1 = new String[]{
"韭菜","洋葱","大蒜","辣椒","羊肉","狗肉","牛肉","桂圆","红参","鹿角胶","核桃","榴莲","鱼类","海产品","白酒","洋葱","生姜","花椒"
};
String[] s2 = new String[]{
"菠菜","燕麦片","巧克力","油菜","空心菜","葱","酸菜","竹笋","草莓","茭白","肥肉","动物内脏","啤酒","黄油","羊肉","狗肉","鳝鱼","鳗鱼","黄鱼","金枪鱼","沙丁鱼","虾","螃蟹","蚌肉"
};
String[] s3 = new String[]{
"豆类","肥肉","芥末","咖啡","辣椒","年糕","浓茶","巧克力","大蒜","洋葱","油炸食品","玉米"
};
String[] s4 = new String[]{
"生姜","辣椒","胡椒","芥末","咖喱","花椒","葱","白酒","咖啡","浓茶","巧克力","葡萄酒","肥肉","动物油","动物内脏"
};
String[] s5 = new String[]{
"肥肉","动物油","动物内脏","蛋黄","油炸食品","糖果","冰淇淋","巧克力","奶油蛋糕","饼干","果汁"
};
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one_hundred_s,container,false);
//寻找gridLayout布局
gridLayout1 = view.findViewById(R.id.onehundred_s_1);
gridLayout2 = view.findViewById(R.id.onehundred_s_2);
gridLayout3 = view.findViewById(R.id.onehundred_s_3);
gridLayout4 = view.findViewById(R.id.onehundred_s_4);
gridLayout5 = view.findViewById(R.id.onehundred_s_5);
//调用网格初始化方法
initGridLayout(gridLayout1,s1);
initGridLayout(gridLayout2,s2);
initGridLayout(gridLayout3,s3);
initGridLayout(gridLayout4,s4);
initGridLayout(gridLayout5,s5);
return view;
}
/**
* 为网格布局初始化
* @param gridLayout 网格布局
* @param strings 网格中的数据
*/
private void initGridLayout(GridLayout gridLayout,String[] strings) {
//为网格赋值
for(int i=0; i< strings.length; i++){
TextView textView = new TextView(this.getContext());
textView.setText(strings[i]);
//设置字体大小
textView.setTextSize(15);
textView.setBackground(getResources().getDrawable(R.drawable.one_hundred_gridlayout_backgroud));
//居中显示
textView.setGravity(Gravity.CENTER);
//指定该组件所在的行
GridLayout.Spec rowSpec = GridLayout.spec(i / 4);
//指定该组件所在的列
GridLayout.Spec columnSpec = GridLayout.spec(i % 4);
GridLayout.LayoutParams params = new GridLayout.LayoutParams(rowSpec,columnSpec);
//指定该组件占满父组件
params.setGravity(Gravity.FILL);
gridLayout.addView(textView,params);
}
}
}
|
import java.util.Scanner;
public class FtoC {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int min=scan.nextInt();
int max=scan.nextInt();
int step=scan.nextInt();
while(min<=max){
System.out.print(min+" ");
System.out.print(fc(min)+"\n");
min+=step;
}
}
public static int fc(int f){
return (5*(f-32))/9;
}
}
|
package com.hason.dtp.core.utils.result;
import com.hason.dtp.core.exception.ErrorResult;
import java.io.Serializable;
/**
* 接口返回的结果
*
* @author Huanghs
* @since 2.0
* @date 2017/11/8
*/
public class Result<T> implements Serializable {
/** 数据 */
private T data;
/** 错误消息 */
private ErrorResult error;
public boolean success() {
return error == null;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public ErrorResult getError() {
return error;
}
public void setError(ErrorResult error) {
this.error = error;
}
}
|
package com.wt.jiaduo.dto.jpa;
// Generated 2018-4-3 10:51:07 by Hibernate Tools 5.2.8.Final
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
/**
* SysRolePermission generated by hbm2java
*/
@Entity
@Table(name = "sys_role_permission", catalog = "jiaduo")
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id")
public class SysRolePermission implements java.io.Serializable {
private Integer id;
private SysRole sysRole;
private SysPermission sysPermission;
private Date createDate;
@ManyToOne()
@JoinColumn(name = "sys_role_id")
public SysRole getSysRole() {
return sysRole;
}
public void setSysRole(SysRole sysRole) {
this.sysRole = sysRole;
}
@ManyToOne()
@JoinColumn(name = "sys_permission_id")
public SysPermission getSysPermission() {
return sysPermission;
}
public void setSysPermission(SysPermission sysPermission) {
this.sysPermission = sysPermission;
}
public SysRolePermission() {
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date", length = 19)
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
|
package fun.witt.lambda;
import org.junit.Test;
import java.util.stream.IntStream;
public class MinDemoTest {
@Test
public void fun() {
int[] ints = {12, 12, 312, 412, 15, 235};
int min = IntStream.of(ints)
.parallel() //并行计算
.min()
.getAsInt();
System.out.println(min);
}
}
|
package com.nitish.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import com.nitish.model.EmployeeModel;
import com.nitish.model.UserModel;
import com.nitish.services.UserService;
@Controller
public class ViewController {
@Autowired
private UserService userService;
@Autowired
private RestTemplate restTemplate;
// ....................................................login page handler..................................
@RequestMapping("/")
public String loginPageHandler(HttpServletRequest request) {
System.out.print("Inside Home page resolver !!!");
return "index";
}
// ....................................................signup page handler.................................
@RequestMapping("/signup")
public String signupPageHandler(HttpServletRequest request) {
System.out.println("Inside Signup page resolver !!!");
return "signup";
}
// ....................................................home page handler...................................
@RequestMapping("/home")
public String homePageHandler( HttpServletRequest request, Model model) {
System.out.println("Inside Home page resolver !!!");
try {
ResponseEntity<EmployeeModel[]> response = restTemplate.getForEntity("http://localhost:9090/employees", EmployeeModel[].class);
EmployeeModel[] employees= response.getBody();
model.addAttribute("employees", employees);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Error:-" + e.getMessage());
}
return "home";
}
// ....................................................create page handler...................................
@RequestMapping("/create")
public String createPageHandler( HttpServletRequest request) {
System.out.println("Inside Create page resolver !!!");
return "create";
}
// ....................................................update page handler.................................
@RequestMapping("/update")
public String updateEmployeeHandler(HttpServletRequest request, Model model, @RequestParam String Id) {
System.out.println("Inside Update page resolver !!!");
try {
// System.out.println("\n inside try..");
ResponseEntity<EmployeeModel> response = restTemplate.getForEntity("http://localhost:9090/employees/get/"+Id, EmployeeModel.class);
// System.out.println("inside try 2..");
EmployeeModel employee= response.getBody();
// System.out.println("Current employee= "+ employee+" ..... ");
model.addAttribute("current_employee", employee);
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Error:-" + e.getMessage());
}
return "update";
}
// ......................................................handler method for signin.............................
@RequestMapping(path = "/processSignin", method = RequestMethod.POST)
public String handleSigninForm(@ModelAttribute UserModel user, Model model, HttpServletRequest request) {
System.out.println(" Inside signin handler ");
boolean u = this.userService.findUser(user);
if (!u) {
HttpSession session = request.getSession();
session.setAttribute("name", user.getUserid());
session.setAttribute("success", "You have loggedin successfully");
// redirecting to home page
return "redirect:/home";
}
HttpSession session = request.getSession();
session.setAttribute("error", "User Id or password not matching");
// redirecting to index page
return "index";
}
// ........................................................handler method for signup.........................
@RequestMapping(path = "/processSignup", method = RequestMethod.POST)
public String handleSignupForm(@ModelAttribute UserModel user, Model model, HttpServletRequest request) {
this.userService.createUser(user);
HttpSession session = request.getSession();
session.setAttribute("success", "User created successfully !!!");
// redirecting to home page
return "index";
}
// .........................................................handler method for updating user................
@RequestMapping(path = "/processCreate", method = RequestMethod.POST)
public String handleCreateForm(@ModelAttribute EmployeeModel empl, Model model, HttpServletRequest request) {
try {
// System.out.println("EMP= "+empl);
empl.setId(5000);
HttpHeaders headers = new HttpHeaders();//creating headers to store data
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<EmployeeModel> entity = new HttpEntity<EmployeeModel>(empl, headers);
restTemplate.postForEntity("http://localhost:9090/", entity, EmployeeModel.class).getBody();
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Error:-" + e.getMessage());
}
HttpSession session = request.getSession();
session.setAttribute("success", "New employee added successfully !!!");
// redirecting to home page
return "redirect:/home";
}
// .........................................................handler method for updating user................
@RequestMapping(path = "/processUpdate", method = RequestMethod.POST)
public String handleUpdateForm(@ModelAttribute EmployeeModel empl, Model model, HttpServletRequest request) {
try {
// System.out.println("EMP= "+empl);
HttpHeaders headers = new HttpHeaders();//creating headers to store data
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<EmployeeModel> entity = new HttpEntity<EmployeeModel>(empl, headers);
restTemplate.postForEntity("http://localhost:9090/", entity, EmployeeModel.class).getBody();
HttpSession session = request.getSession();
session.setAttribute("success", "Employee details updated successfully !!!");
}
catch(Exception e) {
e.printStackTrace();
System.out.println("Error:-" + e.getMessage());
}
// redirecting to home page
return "redirect:/home";
}
// .........................................................logout method for logout........................
@RequestMapping(path = "/processLogout", method = RequestMethod.GET)
public String logoutHandler(HttpServletRequest request) {
HttpSession session= request.getSession();
session.invalidate();
System.out.println("Name= "+ request.getAttribute("name"));
return "redirect:/index";
}
}
|
package com.yuan.unit;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* 公共工具类
*
* @author YUAN
*/
public class CommUtils {
public static boolean checkUserName(String name)
{
boolean flag = true;
return flag;
}
public static boolean checkepsd(String name)
{
boolean flag = true;
return flag;
}
// 验证是否是正确的json格式
@SuppressWarnings("unused")
public static boolean isJson(String str)
{
try {
JSONObject temp = new JSONObject(str);
JSONArray jsonArray = temp.getJSONArray("STR");
List<?> list = JsonUtils.getList(str);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* 检查离开时间是否正确
*
* @return
*/
@SuppressLint("SimpleDateFormat")
public static String checkLeaveTime() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
String str = formatter.format(curDate);
return str;
}
@SuppressWarnings("deprecation")
public static void addViewToWindow(Context context, View view) {
addViewToWindow(context, view, LayoutParams.FILL_PARENT, Gravity.BOTTOM);
}
public static void addViewToWindow(Context context, View view, int height, int gravity) {
try {
WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.width = LayoutParams.MATCH_PARENT;
params.height = height;
params.format = PixelFormat.TRANSPARENT;
params.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
params.gravity = gravity;
((Activity) context).getWindowManager().addView(view, params);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int findStringInlist(List<?> list, String mapItem, String str)
{
int pos = -1;
for (int i = 0; i < list.size(); i++)
{
Map<?, ?> map = (Map<?, ?>) list.get(i);
if (map.get(mapItem).equals(str))
{
return i;
}
}
return pos;
}
public final static void dumpSystemInfo() {
StringBuilder buf = new StringBuilder();
buf.append("====================Dump System Information================================\n");
buf.append(String.format("DEBUG=%s", SystemInfo.DEBUG));
buf.append('\n');
buf.append(String.format("versionCode=%d", SystemInfo.versionCode));
buf.append('\n');
buf.append(String.format("versionName=%S", SystemInfo.versionName));
buf.append('\n');
buf.append(String.format("deviceId=%S", SystemInfo.deviceId));
buf.append('\n');
buf.append(String.format("density=%S", SystemInfo.density));
buf.append('\n');
buf.append(String.format("densityDpi=%S", SystemInfo.densityDpi));
buf.append('\n');
buf.append(String.format("widthPixels=%S", SystemInfo.widthPixels));
buf.append('\n');
buf.append(String.format("heightPixels=%S", SystemInfo.heightPixels));
buf.append('\n');
buf.append("====================END Dump System Information============================\n");
BLog.d("SYSTEMINFO", buf.toString());
}
}
|
import lejos.nxt.ColorSensor;
import lejos.nxt.LCD;
import lejos.nxt.Motor;
import lejos.nxt.SensorPort;
public class Control {
Time time;
Steering steering;
Colorsensor colorsensor;
Printer printer;
Pilot pilot;
Ultrasensori ultrasensori;
int pilotType;
public void setobjects(Time t, Steering s, Colorsensor v, Printer pr,
Pilot pi, Ultrasensori us) {
this.steering = s;
this.time = t;
this.colorsensor = v;
this.pilot = pi;
this.printer = pr;
this.ultrasensori = us;
// starting Pilot type
this.pilotType = 1;
}
// Ohjelman sammutus metodi
public void shutdown() {
Robotti.setStop();
}
// Palauttaa pysäytys booleain arvon
public boolean getStop() {
return Robotti.stop;
}
//
// Pilot
//
public void Pilot() {
pilot.Run(pilotType);
}
public void setPilot(int type) {
this.pilotType = type;
}
//
// Printer
//
public void Printstring(String s, int x, int y) {
printer.printstring(s, x, y);
}
public void Printint(int a, int x, int y){
printer.printint(a, x, y);
}
//
// Timer
//
public void timer() {
// time.timer();
}
//
// Ultrasensor
//
public int sense() {
return ultrasensori.etaisyys();
}
//
// Colorsensor
//
public int getLight(){
return colorsensor.getLight();
}
public void setBlackLight() {
colorsensor.setBlackLight();
}
public int getBlackLight() {
return colorsensor.getBlackLight();
}
public void setWhiteLight() {
colorsensor.setWhiteLight();
}
public int getWhiteLight() {
return colorsensor.getWhiteLight();
}
//
// Steering
//
public void turnRight() {
steering.turnRight();
}
public void turnLeft() {
steering.turnLeft();
}
public void forward() {
steering.forward();
}
}
|
package br.ufc.quixada.dadm.variastelas;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Ignore;
import android.arch.persistence.room.PrimaryKey;
@Entity(tableName = "contato")
public class Contato {
@PrimaryKey(autoGenerate = true)
private int cid;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "endereco")
private String endereco;
@ColumnInfo(name = "telefone")
private String telefone;
@Ignore
public Contato(String name, String endereco, String telefone) {
this.name = name;
this.endereco = endereco;
this.telefone = telefone;
}
public Contato() {
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
@Override
public String toString() {
return "Contato{" +
"cid=" + cid +
", name='" + name +
", endereco='" + endereco +
", telefone='" + telefone +
'}';
}
}
|
package com.vilio.nlbs.commonMapper.dao;
import com.vilio.nlbs.commonMapper.pojo.NlbsLoginInfo;
public interface NlbsLoginInfoMapper {
int deleteByPrimaryKey(Integer id);
int insert(NlbsLoginInfo record);
int insertSelective(NlbsLoginInfo record);
NlbsLoginInfo selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(NlbsLoginInfo record);
int updateByPrimaryKey(NlbsLoginInfo record);
}
|
package pl.jrkn.legacyofthevoidapi.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import pl.jrkn.legacyofthevoidapi.model.character.Character;
public interface CharacterRepository extends JpaRepository<Character, Long> {
}
|
package br.com.fiap.jpa.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
@Entity
@Table(name="T_ITEM_PEDIDO")
@SequenceGenerator(name="item", sequenceName="SQ_T_ITEM_NOTA", allocationSize =1)
public class ItemPedido {
@Id
@GeneratedValue(generator="item", strategy=GenerationType.SEQUENCE)
@Column(name="cd_item_pedido")
private int codigo;
@Column(name="nr_quantidade", nullable=false)
private int quantidade;
@Column(name="vl_preco",nullable=false)
private double valor;
@ManyToOne
@JoinColumn(name="cd_pedido")
private Pedido pedido;
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
}
|
/*
* [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.catalog.model.CatalogVersionModel;
import de.hybris.platform.category.model.CategoryModel;
import de.hybris.platform.cms2.model.pages.AbstractPageModel;
import de.hybris.platform.cms2.model.restrictions.CMSCategoryRestrictionModel;
import java.util.Arrays;
import java.util.Collection;
public class CMSCategoryRestrictionModelBuilder
{
private final CMSCategoryRestrictionModel model;
private CMSCategoryRestrictionModelBuilder()
{
model = new CMSCategoryRestrictionModel();
}
private CMSCategoryRestrictionModelBuilder(CMSCategoryRestrictionModel model)
{
this.model = model;
}
protected CMSCategoryRestrictionModel getModel()
{
return this.model;
}
public static CMSCategoryRestrictionModelBuilder aModel()
{
return new CMSCategoryRestrictionModelBuilder();
}
public static CMSCategoryRestrictionModelBuilder fromModel(CMSCategoryRestrictionModel model)
{
return new CMSCategoryRestrictionModelBuilder(model);
}
public CMSCategoryRestrictionModelBuilder withCatalogVersion(CatalogVersionModel model)
{
getModel().setCatalogVersion(model);
return this;
}
public CMSCategoryRestrictionModelBuilder withUid(String uid)
{
getModel().setUid(uid);
return this;
}
public CMSCategoryRestrictionModelBuilder withName(String name)
{
getModel().setName(name);
return this;
}
public CMSCategoryRestrictionModelBuilder withRecursive(Boolean isRecursive)
{
getModel().setRecursive(isRecursive);
return this;
}
public CMSCategoryRestrictionModelBuilder withCategories(Collection<CategoryModel> categories)
{
getModel().setCategories(categories);
return this;
}
public CMSCategoryRestrictionModelBuilder withPages(AbstractPageModel... pages)
{
getModel().setPages(Arrays.asList(pages));
return this;
}
public CMSCategoryRestrictionModel build()
{
return this.getModel();
}
}
|
package com.tencent.mm.plugin.shake.ui;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.tencent.mm.bg.d;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.shake.b.f;
import com.tencent.mm.sdk.platformtools.bi;
class ShakeMsgListUI$4 implements OnItemClickListener {
final /* synthetic */ ShakeMsgListUI mZP;
ShakeMsgListUI$4(ShakeMsgListUI shakeMsgListUI) {
this.mZP = shakeMsgListUI;
}
public final void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
f fVar = (f) ShakeMsgListUI.b(this.mZP).getItem(i);
if (!bi.oW(fVar.field_tag)) {
h.mEJ.k(11316, ShakeMsgListUI.g(this.mZP) + "," + fVar.field_tag);
Intent intent = new Intent();
intent.putExtra("rawUrl", fVar.field_tag);
d.b(this.mZP.mController.tml, "webview", ".ui.tools.WebViewUI", intent);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package boletin10;
import javax.swing.JOptionPane;
/**
*
* @author Arasa
*/
public class Juego {
public void adivinar(){
int num = Integer.parseInt(JOptionPane.showInputDialog("Numero a adivinar"));
int conta =0;
while(num>=1&&num<=50&&conta<6){
int num2= Integer.parseInt(JOptionPane.showInputDialog("Prueba un numero"));
if (num2<num){
System.out.println("Es mayor");
}
else if(num2>num){
System.out.println("Es menor");
}
else if(num2==num){
System.out.println("Has acertado");
break;
}
conta++;
}
if (conta==6){
System.out.println("Pierdes");
}
}
//borrado el main
}
|
package com.linda.framework.rpc.aio;
import java.nio.channels.CompletionHandler;
public class SocketAcceptHandler<V, A> implements CompletionHandler<V, A> {
@Override
public void completed(V result, A attachment) {
}
@Override
public void failed(Throwable exc, A attachment) {
}
}
|
package uk.gov.hmcts.befta.util;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ReflectionUtils {
public static Object deepGetFieldInObject(Object object, String fieldPath) throws Exception {
if (object == null) {
return null;
}
if (fieldPath == null || fieldPath.length() == 0) {
throw new IllegalArgumentException("Field path must be non-empty String.");
}
final String regex = "(?<!\\\\)(?:\\\\\\\\)*\\."; // i.e. look for '.' but not the escaped version '\.'
String[] rawFields = fieldPath.split(regex);
// unescape fields
List<String> fields = Arrays.stream(rawFields)
.map(field -> field.replace("\\.", "."))
.collect(Collectors.toList());
Object fieldValue = retrieveFieldInObject(object, fields.get(0));
for (int i = 1; i < fields.size(); i++) {
fieldValue = retrieveFieldInObject(fieldValue, fields.get(i));
}
return fieldValue;
}
public static Object retrieveFieldInObject(Object object, String fieldName) throws Exception {
if (object == null)
return null;
if (fieldName == null || fieldName.length() == 0)
throw new IllegalArgumentException("fieldName must be non-empty String.");
int fieldIndex = -1;
if (fieldName.contains("[")) {
fieldIndex = Integer.parseInt(fieldName.substring(fieldName.indexOf("[") + 1, fieldName.length() - 1));
fieldName = fieldName.substring(0, fieldName.indexOf("["));
}
String getterName = "get" + StringUtils.firstLetterToUpperCase(fieldName);
Throwable thrown = null;
Object valueFound = null;
try {
Method method = object.getClass().getMethod(getterName);
valueFound = method.invoke(object);
} catch (Throwable t) {
thrown = t;
}
if (object instanceof Map)
valueFound = ((Map<?, ?>) object).get(fieldName);
else if (thrown != null)
throw new NoSuchFieldException(fieldName + " not retrievable from " + object + ".");
return getValueToReturnFrom(valueFound, fieldIndex);
}
private static Object getValueToReturnFrom(Object valueFound, int fieldIndex) {
if (fieldIndex < 0)
return valueFound;
else {
if (valueFound instanceof List<?>)
return ((List<?>) valueFound).get(fieldIndex);
else if (valueFound instanceof Object[])
return ((Object[]) valueFound)[fieldIndex];
else if (valueFound instanceof Iterable<?>) {
Iterator<?> itr = ((Iterable<?>) valueFound).iterator();
int i = 0;
while (itr.hasNext()) {
Object element = itr.next();
if (i == fieldIndex)
return element;
i++;
}
throw new RuntimeException(
"Element " + fieldIndex + " not available. Size of the containing object is " + i + ".");
}
else {
throw new RuntimeException(
"Element " + fieldIndex + " not addressable on " + valueFound + ".");
}
}
}
public static class DummyPlaceHolder {
}
@SuppressWarnings({ "rawtypes" })
public static boolean mapContains(Map<?, ?> big, Map<?, ?> small) {
if (big == null)
return small == null;
else if (small == null)
throw new IllegalArgumentException("Small cannot be null when big is not.");
if (small.size() > big.size())
return false;
for (Object key : small.keySet()) {
Object smallValue = small.get(key);
Object bigValue = big.get(key);
if (smallValue instanceof Map) {
boolean valueContained = mapContains((Map) bigValue, (Map) smallValue);
if (!valueContained)
return false;
} else if (small != null) {
boolean valueEquals = smallValue.equals(bigValue);
if (!valueEquals)
return false;
}
}
return true;
}
}
|
package com.msh;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import javax.servlet.http.HttpServletRequest;
/**
* Created by IntelliJ IDEA.
* User: mshaikh4
* Date: 30-08-2021
* Time: 18:00
* Year: 2021
* Project: micronauth-demo
* Package: com.msh
*/
@Controller("/home")
public class HomeController {
@Get()
public String homeLoc(HttpServletRequest httpServletRequest){
return String.format("Welcome %s to Micronaut at %s ", httpServletRequest.getRemoteAddr(),
httpServletRequest.getLocalAddr()) ;
}
}
|
package com.tencent.mm.bt;
import android.content.ContentResolver;
import android.database.CharArrayBuffer;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.net.Uri;
import android.os.Bundle;
import android.util.SparseArray;
import com.tencent.mm.bt.a.a;
import com.tencent.mm.bt.a.f;
import java.util.HashMap;
public final class d implements Cursor, com.tencent.mm.bt.a.d {
private static Cursor tds;
public static Cursor cnR() {
if (tds == null) {
tds = new d();
}
return tds;
}
public final void unregisterDataSetObserver(DataSetObserver dataSetObserver) {
}
public final void unregisterContentObserver(ContentObserver contentObserver) {
}
public final void setNotificationUri(ContentResolver contentResolver, Uri uri) {
}
public final Bundle respond(Bundle bundle) {
return null;
}
public final boolean requery() {
return false;
}
public final void registerDataSetObserver(DataSetObserver dataSetObserver) {
}
public final void registerContentObserver(ContentObserver contentObserver) {
}
public final boolean moveToPrevious() {
return false;
}
public final boolean moveToPosition(int i) {
return false;
}
public final boolean moveToNext() {
return false;
}
public final boolean moveToLast() {
return false;
}
public final boolean moveToFirst() {
return false;
}
public final boolean move(int i) {
return false;
}
public final boolean isNull(int i) {
return false;
}
public final boolean isLast() {
return false;
}
public final boolean isFirst() {
return false;
}
public final boolean isClosed() {
return false;
}
public final boolean isBeforeFirst() {
return false;
}
public final boolean isAfterLast() {
return true;
}
public final boolean getWantsAllOnMoveCalls() {
return false;
}
public final String getString(int i) {
return null;
}
public final short getShort(int i) {
return (short) 0;
}
public final int getPosition() {
return 0;
}
public final long getLong(int i) {
return 0;
}
public final int getInt(int i) {
return 0;
}
public final float getFloat(int i) {
return 0.0f;
}
public final Bundle getExtras() {
return null;
}
public final double getDouble(int i) {
return 0.0d;
}
public final int getCount() {
return 0;
}
public final String[] getColumnNames() {
return null;
}
public final String getColumnName(int i) {
return null;
}
public final int getColumnIndexOrThrow(String str) {
return 0;
}
public final int getColumnIndex(String str) {
return 0;
}
public final int getColumnCount() {
return 0;
}
public final byte[] getBlob(int i) {
return null;
}
public final void deactivate() {
}
public final void copyStringToBuffer(int i, CharArrayBuffer charArrayBuffer) {
}
public final void close() {
}
public final int getType(int i) {
return 0;
}
public final boolean Dx(int i) {
return false;
}
public final boolean cm(Object obj) {
return false;
}
public final a Dy(int i) {
return null;
}
public final a cn(Object obj) {
return null;
}
public final SparseArray[] cnS() {
return null;
}
public final HashMap cnT() {
return null;
}
public final boolean cnU() {
return false;
}
public final boolean a(Object obj, a aVar) {
return false;
}
public final void lo(boolean z) {
}
public final void a(f.a aVar) {
}
public final void Dz(int i) {
}
public final Uri getNotificationUri() {
return null;
}
public final void setExtras(Bundle bundle) {
}
}
|
package day43JavaRecap;
public class practice2 {
public static void main(String[] args) {
staticKeyword1.printName();//static method cen ba called through the class name
staticKeyword1 obj1=new staticKeyword1();//inorder to call the insta method I need to create an object
System.out.println(obj1.InsName);//Filiz
obj1.printName2();
practice2.printName();//Semra
printName();//Semra
staticKeyword1.printName();//from statickeyword class
//calling static variable
System.out.println(staticKeyword1.StaName);
System.out.println(obj1.InsName);//Filiz, can not be called throguh the class
}
public static void printName() {
System.out.println("Semra");
}
}
|
package com.example.todolist.Di.Modules;
import androidx.lifecycle.ViewModel;
import com.example.todolist.AddGroups.AddGroupViewModel;
import com.example.todolist.AddTasks.AddTaskViewModel;
import com.example.todolist.Di.Keys.ViewModelKey;
import com.example.todolist.Main.GroupsViewModel;
import com.example.todolist.entry.EntryViewModel;
import com.example.todolist.tasks.TasksViewModel;
import dagger.Binds;
import dagger.Module;
import dagger.multibindings.IntoMap;
@Module
public abstract class ViewModelModule {
@Binds
@ViewModelKey(AddGroupViewModel.class)
@IntoMap
abstract ViewModel provideAddTaskGroupViewModel(AddGroupViewModel addGroupViewModel);
@Binds
@ViewModelKey(AddTaskViewModel.class)
@IntoMap
abstract ViewModel provideAddTaskViewModel(AddTaskViewModel addTaskViewModel);
@Binds
@ViewModelKey(GroupsViewModel.class)
@IntoMap
abstract ViewModel provideGroupsViewModel(GroupsViewModel groupsViewModel);
@Binds
@ViewModelKey(EntryViewModel.class)
@IntoMap
abstract ViewModel provideEntryViewModel(EntryViewModel entryViewModel);
@Binds
@ViewModelKey(TasksViewModel.class)
@IntoMap
abstract ViewModel provideTasksViewModel(TasksViewModel tasksViewModel);
}
|
package onemount.com;
import java.util.Scanner;
public class App
{
public static int[][] inputMatrix() {
Scanner sc = new Scanner(System.in);
System.out.println("Số dòng : ");
int r = sc.nextInt();
System.out.println("Số cột: ");
int c = sc.nextInt();
int[][] arr = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
System.out.format("a[%d][%d] = ", i,j);
arr[i][j] = sc.nextInt();
}
}
return arr;
}
public static int inputNumber() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter x number : ");
int x = sc.nextInt();
return x;
}
public static int[][] generateMatrix(int r, int c, int min, int max) {
int[][] arr = new int[r][c];
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
arr[i][j] = (int) Math.floor(Math.random() * (max - min) + min);
}
}
return arr;
}
public static void main( String[] args )
{
// int[][] inputStr = inputMatrix();
int[][] inputStr = generateMatrix(4,4,1,10);
// Bai_1
Exercises_18_08.printMatrix(inputStr);
// int x = inputNumber();
// System.out.println("Sum input matrix : " + Excersises.sumElements(inputStr));
// System.out.println("=============");
// System.out.println("Matrix contains x is : " + Excersises.findXInMatrix(inputStr, x));
// System.out.println("=============");
// System.out.println("Max value in matrix is : " + Exercises_18_08.findMaxInMatrix(inputStr));
// System.out.println("=============");
// System.out.println("Matrix contains prime value is : " + Exercises_18_08.isContainPrimeNumber(inputStr));
// System.out.println("=============");
// Bài 4 a
// int row = inputNumber();
// System.out.println("Sum elements by row are : " + Exercises_18_08.sumRowElements(inputStr, row));
// System.out.println("=============");
// int col = inputNumber();
// System.out.println("Sum elements by col are : " + Exercises_18_08.sumColElements(inputStr, col));
// System.out.println("=============");
// Bài 4 b
// System.out.println("Sum elements main cross are : " + Exercises_18_08.sumMainCross(inputStr));
// System.out.println("=============");
// System.out.println("Sum elements sub cross are : " + Exercises_18_08.sumSubCross(inputStr));
// System.out.println("=============");
// Bài 4 c
// System.out.println("Sum ele a haft above main cross are : " + Exercises_18_08.sumAHaftAboveOfMainCross(inputStr));
// System.out.println("=============");
// System.out.println("Sum ele a haft below main cross are : " + Exercises_18_08.sumAHaftBelowOfMainCross(inputStr));
// System.out.println("=============");
// Bài 4 d
// System.out.println("Sum ele a haft above sub cross are : " + Exercises_18_08.sumAHaftAboveOfSubCross(inputStr));
// System.out.println("=============");
System.out.println("Sum ele a haft below sub cross are : " + Exercises_18_08.sumAHaftBelowOfSubCross(inputStr));
System.out.println("=============");
}
}
|
package jour28;
public class Dog extends Mammal{
public boolean sadik =true;
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
}
public void bark() {
System.out.println("Kopekler havlar");
}
Dog(){
super(); // istege bagli koysak da olur koymasak da
//this() ayni class icindeki parametresiz constructor u cagirmak icin kullanilir
System.out.println("Dog parametresiz constructor");
}
protected void eat() {
System.out.println("Dog kemik yer");
}
}
|
/*
* Copyright (C) 2015 Miquel Sas
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.qtplaf.library.swing.core;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.JComboBox;
import com.qtplaf.library.app.Session;
import com.qtplaf.library.database.Field;
import com.qtplaf.library.database.Value;
import com.qtplaf.library.swing.EditContext;
import com.qtplaf.library.swing.EditField;
/**
* A combo box aimed to edit fields with possible values.
*
* @author Miquel Sas
*/
public class JComboBoxField extends JComboBox<JComboBoxField.Item> implements EditField {
/**
* The associated edit context.
*/
private EditContext editContext;
/**
* Items of the combo box.
*/
class Item extends Value {
/**
* Constructor.
*
* @param v The origin value.
*/
Item(Value v) {
super(v);
}
/**
* Returns the string representation.
*
* @return The string representation.
*/
@Override
public String toString() {
if (getLabel() != null) {
return getLabel();
}
return toStringFormatted(getSession().getLocale());
}
/**
* Get the origin value.
*/
@Override
public Value getValue() {
return new Value(this);
}
/**
* Check if the argument object isequal to this item.
*
* @return A boolean indicating if the argument object isequal to this item.
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Value))
return false;
Value v = (Value) o;
return super.equals(v);
}
}
/**
* Constructor.
*
* @param editContext The edit context.
*/
public JComboBoxField(EditContext editContext) {
super();
this.editContext = editContext;
Field field = new Field(editContext.getField());
if (field.isBoolean()) {
field.addPossibleValues(getBooleanValues(getEditContext().isFilter()));
}
List<Value> possibleValues = field.getPossibleValues();
removeAll();
for (Value possibleValue : possibleValues) {
addItem(new Item(possibleValue));
}
setToolTipText(field.getToolTip());
setValue(editContext.getValue(), false);
setPreferredSize(getPreferredDisplaySize());
setMaximumSize(getPreferredDisplaySize());
setMinimumSize(getPreferredDisplaySize());
setEditable(false);
setBackground(Color.WHITE);
updateUI();
}
/**
* Returns this edit control preferred display size, according to the field properties.
*
* @return The preferred display size.
*/
public Dimension getPreferredDisplaySize() {
Dimension size = new Dimension();
Field field = editContext.getField();
Locale locale = getSession().getLocale();
// Get the height from the parent JComboBox.
size.height = getPreferredSize().height;
// Get the maximum length of the list of values.
String maxText = "";
for (int i = 0; i < getItemCount(); i++) {
Item item = getItemAt(i);
String text = item.toStringFormatted(locale);
if (text.length() > maxText.length()) {
maxText = text;
}
}
FontMetrics metrics = getFontMetrics(getFont());
size.width = SwingUtils.getPreferredFieldWidth(metrics, field, locale) + 50;
return size;
}
/**
* Returns the list of values when the field is boolean.
*
* @param filter A boolean that indicates if this edit field is used in a filter form.
* @return The list of values.
*/
private List<Value> getBooleanValues(boolean filter) {
List<Value> values = new ArrayList<>();
if (filter) {
Value valueEmpty = new Value((Boolean) null);
valueEmpty.setLabel("");
values.add(valueEmpty);
}
Value valueYes = new Value(true);
valueYes.setLabel(getTokenYes());
values.add(valueYes);
Value valueNo = new Value(false);
valueNo.setLabel(getTokenNo());
values.add(valueNo);
return values;
}
/**
* Returns the <i>yes</i> token.
*
* @return The token.
*/
private String getTokenYes() {
return getSession().getString("tokenYes");
}
/**
* Returns the <i>no</i> token.
*
* @return The token.
*/
private String getTokenNo() {
return getSession().getString("tokenNo");
}
/**
* Returns the associated edit context.
*
* @return The edit context.
*/
@Override
public EditContext getEditContext() {
return editContext;
}
/**
* Returns the working session.
*
* @return The working session.
*/
public Session getSession() {
return editContext.getSession();
}
/**
* Clear the control with its default data.
*/
@Override
public void clear() {
setValue(getEditContext().getField().getDefaultValue());
}
/**
* Get the value from the component, not the record.
*
* @return The value.
*/
@Override
public Value getValue() {
Item item = (Item) getSelectedItem();
Value value;
if (item == null) {
if (getEditContext().getField().isBoolean()) {
value = getEditContext().getField().getDefaultValue();
if (getEditContext().isFilter()) {
value.setNull();
}
} else {
value = getEditContext().getField().getDefaultValue();
}
} else {
if (getEditContext().getField().isBoolean()) {
if (item.equals("")) {
value = getEditContext().getField().getDefaultValue();
value.setNull();
} else if (item.equals(getTokenNo())) {
value = new Value(false);
} else {
value = new Value(true);
}
} else {
value = item.getValue();
}
}
return value;
}
/**
* Update the value in the component, not the record.
*
* @param value The value to set.
*/
@Override
public void setValue(Value value) {
setValue(value, true);
}
@Override
public void setValue(Value value, boolean fireValueActions) {
Value previousValue = getValue();
// Set the selected item.
Item item;
if (getEditContext().getField().isBoolean()) {
if (value.isNull()) {
item = new Item(new Value(""));
} else if (value.getBoolean()) {
item = new Item(new Value(getTokenYes()));
} else {
item = new Item(new Value(getTokenNo()));
}
} else {
item = new Item(value);
}
boolean selectedIndexSet = false;
for (int i = 0; i < getItemCount(); i++) {
if (item.equals(getItemAt(i))) {
setSelectedIndex(i);
selectedIndexSet = true;
break;
}
}
if (getItemCount() > 0 && !selectedIndexSet) {
setSelectedIndex(0);
}
// Fire value actions if required.
if (fireValueActions) {
getEditContext().fireValueActions(this, previousValue, value);
}
}
/**
* Fire state changed.
*/
@Override
protected void fireItemStateChanged(ItemEvent e) {
super.fireItemStateChanged(e);
if (e.getID() == ItemEvent.ITEM_STATE_CHANGED) {
Item previousItem = null;
if (e.getStateChange() == ItemEvent.DESELECTED) {
previousItem = (Item)e.getItem();
}
if (e.getStateChange() == ItemEvent.SELECTED) {
Item currentItem = (Item)e.getItem();
getEditContext().fireValueActions(this,previousItem,currentItem);
}
}
}
/**
* Returns the component that will process the events of this edit field.
*
* @return The {@link Component}.
*/
@Override
public Component getComponent() {
return this;
}
/**
* Returns a string representation of this edit field.
*
* @return A string representation.
*/
@Override
public String toString() {
return SwingUtils.toString(this);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.example.codetribe1.constructionappsuite.dto;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* @author aubreyM
*/
public class ProjectSiteTaskStatusDTO implements Serializable, Comparable<ProjectSiteTaskStatusDTO> {
private static final long serialVersionUID = 1L;
private Integer projectSiteTaskStatusID;
private Date dateUpdated;
private Date statusDate;
private TaskStatusDTO taskStatus;
private TaskDTO task;
private Integer projectSiteTaskID;
private Integer companyStaffID;
private String projectSiteName, projectName, staffName;
private List<SubTaskStatusDTO> subTaskStatusList;
public ProjectSiteTaskStatusDTO() {
}
public List<SubTaskStatusDTO> getSubTaskStatusList() {
return subTaskStatusList;
}
public void setSubTaskStatusList(List<SubTaskStatusDTO> subTaskStatusList) {
this.subTaskStatusList = subTaskStatusList;
}
public TaskDTO getTask() {
return task;
}
public void setTask(TaskDTO task) {
this.task = task;
}
public Integer getCompanyStaffID() {
return companyStaffID;
}
public void setCompanyStaffID(Integer companyStaffID) {
this.companyStaffID = companyStaffID;
}
public Date getDateUpdated() {
return dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
public Date getStatusDate() {
return statusDate;
}
public void setStatusDate(Date statusDate) {
this.statusDate = statusDate;
}
public String getProjectSiteName() {
return projectSiteName;
}
public void setProjectSiteName(String projectSiteName) {
this.projectSiteName = projectSiteName;
}
public String getProjectName() {
return projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getStaffName() {
return staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public Integer getProjectSiteTaskStatusID() {
return projectSiteTaskStatusID;
}
public void setProjectSiteTaskStatusID(Integer projectSiteTaskStatusID) {
this.projectSiteTaskStatusID = projectSiteTaskStatusID;
}
public TaskStatusDTO getTaskStatus() {
return taskStatus;
}
public void setTaskStatus(TaskStatusDTO taskStatus) {
this.taskStatus = taskStatus;
}
public Integer getProjectSiteTaskID() {
return projectSiteTaskID;
}
public void setProjectSiteTaskID(Integer projectSiteTaskID) {
this.projectSiteTaskID = projectSiteTaskID;
}
@Override
public String toString() {
return "com.boha.monitor.data.ProjectSiteTaskStatus[ projectSiteTaskStatusID=" + projectSiteTaskStatusID + " ]";
}
/**
* Compares this object to the specified object to determine their relative
* order.
*
* @param another the object to compare to this instance.
* @return a negative integer if this instance is less than {@code another};
* a positive integer if this instance is greater than
* {@code another}; 0 if this instance has the same order as
* {@code another}.
* @throws ClassCastException if {@code another} cannot be converted into something
* comparable to {@code this} instance.
*/
@Override
public int compareTo(ProjectSiteTaskStatusDTO another) {
if (this.statusDate.before(another.statusDate)) {
return -1;
}
if (this.statusDate.after(another.statusDate)) {
return 1;
}
return 0;
}
}
|
package com.hxzy.mapper;
import com.hxzy.common.vo.PageSearch;
import com.hxzy.entity.Data;
import java.util.List;
public interface DataMapper {
int insert(Data record);
Data selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Data record);
int updateByPrimaryKey(Data record);
/**
* 根据类型查询数据
* @param types
* @return
*/
List<Data> selectTypes(int types);
List<Data> search(PageSearch searchVO);
int existsName(Data data);
}
|
package com.tencent.mm.ui.statusbar;
import android.os.Build.VERSION;
import android.view.View;
import android.widget.FrameLayout.LayoutParams;
import com.tencent.mm.ui.MMActivity;
public abstract class DrawStatusBarActivity extends MMActivity {
private b gue = null;
protected void initSwipeBack() {
super.initSwipeBack();
if (getSwipeBackLayout() != null && getSwipeBackLayout().getChildCount() > 0) {
View childAt = getSwipeBackLayout().getChildAt(0);
getSwipeBackLayout().removeView(childAt);
this.gue = new b(this);
this.gue.addView(childAt, new LayoutParams(-1, -1));
getSwipeBackLayout().addView(this.gue);
getSwipeBackLayout().setContentView(this.gue);
}
}
public int getStatusBarColor() {
return this.mController.cqm();
}
public final void lF(int i) {
super.lF(i);
if (VERSION.SDK_INT >= 21 && getWindow() != null) {
a.c(this.mController.contentView, getWindow().getStatusBarColor(), d.c(getWindow()));
}
}
}
|
package com.ibeiliao.pay.idgen.impl.dao;
import com.ibeiliao.pay.datasource.MyBatisDao;
import com.ibeiliao.pay.idgen.impl.entity.IdSerialPO;
import org.apache.ibatis.annotations.Param;
/**
* t_id_serial 的接口
* @author linyi 2016/7/7.
*/
@MyBatisDao
public interface IdSerialDao {
/**
* 读取ID记录
* @param idName ID名称
* @return 返回ID记录或null
*/
IdSerialPO get(String idName);
/**
* 保存数据
*
* @param po 要保存的对象
*/
void insert(IdSerialPO po);
/**
* 更新 value 字段的值
* @param idName ID名称
* @param newValue 新的值
* @param oldValue 旧的值
* @return 返回更新的行数
*/
int updateValue(@Param("idName") String idName, @Param("newValue") long newValue, @Param("oldValue") long oldValue);
}
|
package de.lise.terradoc.core.state;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class StateReader {
private final Gson gson;
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
public StateReader() {
gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
}
public TerraformState read(InputStream in) throws IOException {
try(InputStreamReader reader = new InputStreamReader(in, DEFAULT_CHARSET)){
return read(reader);
}
}
public TerraformState read(Reader reader) {
return gson.fromJson(reader, TerraformState.class);
}
}
|
package com.zhouyi.business.common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.zhouyi.business.core.common.Config;
@Component
public class WebConfigurer extends WebMvcConfigurerAdapter{
@Autowired
private Config config;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**").addResourceLocations("file:///"+config.getUploadPath()+"/");
}
}
|
package controleur;
import java.awt.Desktop;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import javax.swing.*;
import modele.ControleConnexion;
import vue.*;
public class ControleurVueIdentif extends WindowAdapter implements ActionListener {
private final String NOM_UTILISATEUR = "gestion";
private final String MOT_DE_PASSE = "gestion12345";
private JButton btnValider, btnQuitter, menuAide;
private JTextField nomUtilisateur;
private JPasswordField motDePasse;
private VueIdentification vue;
private Connection connexionBd;
public ControleurVueIdentif( VueIdentification vue ) {
this.vue = vue;
nomUtilisateur = (JTextField) this.vue.getContentPane().getComponent( 2 );
motDePasse = (JPasswordField) this.vue.getContentPane().getComponent( 4 );
btnValider = (JButton) this.vue.getContentPane().getComponent( 5 );
btnQuitter = (JButton) this.vue.getContentPane().getComponent( 6 );
menuAide = this.vue.getMenuAide();
}
@Override
public void actionPerformed( ActionEvent evenement ) {
if ( evenement.getSource() == btnValider ) {
if ( nomUtilisateur.getText().equals( NOM_UTILISATEUR )
&& String.valueOf( motDePasse.getPassword() ).equals( MOT_DE_PASSE ) ) {
ControleConnexion.connexionBd();
connexionBd = ControleConnexion.getLaConnexion();
if ( connexionBd != null ) {
VueChoixTraitements vueChoixTraitements = new VueChoixTraitements();
vueChoixTraitements.setVisible( true );
vue.dispose();
}
} else {
JOptionPane.showMessageDialog( null, "Le nom d'utilisateur ou le mot de passe est incorrecte" );
}
} else if ( evenement.getSource() == menuAide ) {
try {
File fichierAide = new File( "src/aide_en_ligne/aide.chm" );
Desktop.getDesktop().open( fichierAide );
} catch ( IOException ex ) {
}
} else if ( evenement.getSource() == btnQuitter ) {
confirmationQuitter();
}
}
public void windowClosing( WindowEvent e ) {
confirmationQuitter();
}
private void confirmationQuitter() {
int confirmation = JOptionPane.showConfirmDialog( null, "Voulez-vous vraiment quitter le programme ?",
"Quitter le programme", JOptionPane.YES_NO_OPTION );
if ( confirmation == JOptionPane.YES_OPTION ) {
vue.dispose();
ControleConnexion.fermerSession();
}
}
}
|
package com.stem.controller;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.stem.core.ImageDealImpl;
@Controller
@RequestMapping("anno")
public class SystemController {
@RequestMapping("/error")
public String error(){
return "";
}
@RequestMapping("/nologin")
public String noLogin(){
return "fore/home";
}
@RequestMapping("/img")
public void sendImage(String path, HttpServletResponse response){
ImageDealImpl deal = new ImageDealImpl();
byte[] data = deal.fetch(path);
try {
OutputStream os = response.getOutputStream();
IOUtils.write(data, os);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package app.controller;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import app.model.Customer;
import app.mytools.DBUtil;
public class CustomerDAO {
private static EntityManager em = DBUtil.getEntityManagerFactory().createEntityManager();
public static String save(Customer cust) {
EntityTransaction trans = em.getTransaction();
trans.begin();
em.persist(cust);
trans.commit();
return "confirmation";
}
public static Customer getCustByEmail(String email) {
Customer cust = null;
try{
cust = (Customer) em.createNamedQuery("Customer.getCustomerByEmail").setParameter("email", email).getSingleResult();
System.out.println("ID: " + cust.getCustomerId());
return cust;
} catch (Exception e) {
return null;
}
}
}
|
//注意需要一个变量记住上一个访问过的元素的值
class Solution {
public int removeDuplicates(int[] nums) {
int size = nums.length;
if(size == 0){
return 0;
}
int index = 0;
int lastVal = -1;
for(int i = 0; i < size; i++){
if(i == 0 || nums[i] != lastVal){
lastVal = nums[i];
swap(nums, index, i);
index++;
}
}
return index;
}
private void swap(int[] nums, int j, int i){
if(i != j){
int tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
}
}
}
|
package com.psl.flashnotes.Idao;
import com.psl.flashnotes.bean.NotesViews;
public interface INotesViewsDAO {
public NotesViews retrieveUser(int userId,int noteId);
//public void updateView(int userId);
}
|
package com.scnuweb.action;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import com.scnuweb.entity.Exam;
import com.scnuweb.entity.ExamItem;
import com.scnuweb.entity.User;
import com.scnuweb.service.ExamItemService;
import com.scnuweb.service.ExamService;
import com.scnuweb.service.UserService;
import com.scnuweb.util.JsonRetObj;
import com.scnuweb.util.MD5;
import com.scnuweb.util.MyJson;
import com.scnuweb.util.StaticVar;
@Controller
@RequestMapping("admin")
public class AdminController {
@Autowired
private UserService userService;
@Autowired
private ExamService examService;
@Autowired
private ExamItemService examItemService;
@RequestMapping("index")
public String admin(ModelMap modelMap,HttpServletRequest request) {
return "admin";
}
@RequestMapping("candidate_manage")
public String candidateManage(ModelMap modelMap,HttpServletRequest request,User search) {
List<User> candidateList = null;
if(search!=null) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("userType", StaticVar.USER_TYPE_CANDIDATE);
if(search.getNo()!=null&&search.getNo().trim().length()>0)map.put("no", search.getNo().trim());
if(search.getUsername()!=null&&search.getUsername().trim().length()>0)map.put("username", search.getUsername().trim());
if(search.getTrueName()!=null&&search.getTrueName().trim().length()>0)map.put("trueName", search.getTrueName().trim());
if(search.getUnit()!=null&&search.getUnit().trim().length()>0)map.put("unit", search.getUnit().trim());
modelMap.put("search", search);
candidateList = userService.getUsersByParams(map);
} else {
candidateList = userService.getAllCandidates();
modelMap.put("search", new User());
}
modelMap.put("candidateList", candidateList);
return "candidate_manage";
}
@RequestMapping("add_candidate")
public String addCandidate(ModelMap modelMap) {
return "add_candidate";
}
@RequestMapping("add_candidate_submit")
public String addCandidateSubmit(ModelMap modelMap,User user) {
user.setUserType(StaticVar.USER_TYPE_CANDIDATE);
user.setPassword(MD5.getMD5(user.getPassword().getBytes()));
userService.addUser(user);
return "redirect:/admin/candidate_manage.html";
}
@RequestMapping("edit_candidate")
public String updateCandidate(ModelMap modelMap,Long userId) {
User user = userService.getUserById(userId);
modelMap.put("candidate", user);
return "edit_candidate";
}
@RequestMapping("edit_candidate_submit")
public String updateCandidateSubmit(ModelMap modelMap,User user) {
if(user.getPassword()==null||user.getPassword().trim().length()<1) {
User oringinalUser = userService.getUserById(user.getId());
user.setPassword(oringinalUser.getPassword());
} else user.setPassword(MD5.getMD5(user.getPassword().getBytes()));
user.setUserType(StaticVar.USER_TYPE_CANDIDATE);
userService.updateUser(user);
return "redirect:/admin/candidate_manage.html";
}
@RequestMapping("delete_candidate")
public String deleteCandidate(ModelMap modelMap,HttpServletRequest request,Long userId) {
userService.deleteUser(userId);
return "redirect:/admin/candidate_manage.html";
}
@RequestMapping("check_is_username_valid")
public String checkIsUsernameValid(ModelMap modelMap,HttpServletRequest request,String username) {
String ret = null;
if(username==null||username.trim().length()<4||username.trim().length()>16)ret = "false";
else {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("username", username);
if((userService.getUsersByParams(paramMap)).size()>0)ret = "false";
else ret = "true";
}
modelMap.put("info", ret);
return "json";
}
@RequestMapping("delete_candidates")
public String deleteCandidates(ModelMap modelMap,HttpServletRequest request,String deleteList) {
userService.deleteUsers(deleteList);
modelMap.put("info", "true");
return "json";
}
@RequestMapping("exam_manage")
public String examManage(ModelMap modelMap,HttpServletRequest request) {
List<Exam> examList = examService.getAllExams();
Date nowDate = new Date();
modelMap.put("examList", examList);
modelMap.put("nowDate", nowDate);
return "exam_manage";
}
@RequestMapping("add_exam")
public String addExam(ModelMap modelMap,HttpServletRequest request,User search) {
List<User> candidateList = null;
if(search!=null) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("userType", StaticVar.USER_TYPE_CANDIDATE);
if(search.getNo()!=null&&search.getNo().trim().length()>0)map.put("no", search.getNo().trim());
if(search.getUsername()!=null&&search.getUsername().trim().length()>0)map.put("username", search.getUsername().trim());
if(search.getTrueName()!=null&&search.getTrueName().trim().length()>0)map.put("trueName", search.getTrueName().trim());
if(search.getUnit()!=null&&search.getUnit().trim().length()>0)map.put("unit", search.getUnit().trim());
modelMap.put("search", search);
candidateList = userService.getUsersByParams(map);
} else {
candidateList = userService.getAllCandidates();
modelMap.put("search", new User());
}
modelMap.put("candidateList", candidateList);
return "add_exam";
}
@RequestMapping("add_exam_submit")
public String addExamSubmit(ModelMap modelMap,HttpServletRequest request,String examName,String startTime,String endTime) {
boolean flag = true;
JsonRetObj retObj = new JsonRetObj();
if(examName==null||examName.length()<1)flag = false;
if(startTime==null||startTime.length()<1)flag = false;
if(endTime==null||endTime.length()<1)flag = false;
if(!flag) {
retObj.setStatus(false);
retObj.setInfo("请完成必填项");
} else {
Exam exam = new Exam();
exam.setExamName(examName);
try {
SimpleDateFormat format = new SimpleDateFormat(StaticVar.UNIVERSIAL_TIME_FORMAT);
Date startDate = format.parse(startTime);
Date endDate = format.parse(endTime);
if(startDate.getTime()>=endDate.getTime()) {
retObj.setStatus(false);
retObj.setInfo("请填写有效的开始和结束时间");
} else {
exam.setStartTime(startDate);
exam.setEndTime(endDate);
examService.addExam(exam);
retObj.setStatus(true);
retObj.setInfo("保存成功");
retObj.setRetId(exam.getId());
}
} catch (Exception e) {
// TODO: handle exception
retObj.setStatus(false);
retObj.setInfo("请填写有效的时间");
}
}
modelMap.put("info", MyJson.toJson(retObj));
return "json";
}
@RequestMapping("edit_exam_submit")
public String editExamSubmit(ModelMap modelMap,HttpServletRequest request,Long examId,String examName,String startTime,String endTime) {
boolean flag = true;
JsonRetObj retObj = new JsonRetObj();
if(examName==null||examName.length()<1)flag = false;
if(startTime==null||startTime.length()<1)flag = false;
if(endTime==null||endTime.length()<1)flag = false;
if(!flag) {
retObj.setStatus(false);
retObj.setInfo("请完成必填项");
} else {
Exam exam = examService.getExamById(examId);
exam.setExamName(examName);
try {
SimpleDateFormat format = new SimpleDateFormat(StaticVar.UNIVERSIAL_TIME_FORMAT);
Date startDate = format.parse(startTime);
Date endDate = format.parse(endTime);
if(startDate.getTime()>=endDate.getTime()) {
retObj.setStatus(false);
retObj.setInfo("请填写有效的开始和结束时间");
} else {
exam.setStartTime(startDate);
exam.setEndTime(endDate);
examService.updateExam(exam);
retObj.setStatus(true);
retObj.setInfo("保存成功");
retObj.setRetId(exam.getId());
}
} catch (Exception e) {
// TODO: handle exception
retObj.setStatus(false);
retObj.setInfo("请填写有效的时间");
}
}
modelMap.put("info", MyJson.toJson(retObj));
return "json";
}
@RequestMapping("edit_exam")
public String editExam(ModelMap modelMap,HttpServletRequest request,Long examId,User search) {
List<User> candidateList = null;
if(search!=null) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("userType", StaticVar.USER_TYPE_CANDIDATE);
if(search.getNo()!=null&&search.getNo().trim().length()>0)map.put("no", search.getNo().trim());
if(search.getUsername()!=null&&search.getUsername().trim().length()>0)map.put("username", search.getUsername().trim());
if(search.getTrueName()!=null&&search.getTrueName().trim().length()>0)map.put("trueName", search.getTrueName().trim());
if(search.getUnit()!=null&&search.getUnit().trim().length()>0)map.put("unit", search.getUnit().trim());
modelMap.put("search", search);
candidateList = userService.getUsersByParams(map);
} else {
candidateList = userService.getAllCandidates();
modelMap.put("search", new User());
}
Exam exam = examService.getExamById(examId);
modelMap.put("candidateList", candidateList);
modelMap.put("exam", exam);
return "edit_exam";
}
@RequestMapping("delete_exam")
public String deleteExam(ModelMap modelMap,HttpServletRequest request,Long deleteId) {
examService.delete(deleteId);
return "redirect:/admin/exam_manage.html";
}
@RequestMapping("get_candidate_list")
public String getCandidateList(ModelMap modelMap,HttpServletRequest request,User search) {
List<User> retList = userService.getCandidateListItem(search);
modelMap.put("info", MyJson.toJson(retList));
return "json";
}
@RequestMapping("get_exam_item_list")
public String getExamItemList(ModelMap modelMap,HttpServletRequest request) {
List<ExamItem> examItemList = examItemService.getAllExamItems();
modelMap.put("info", MyJson.toJson(examItemList));
return "json";
}
@RequestMapping("import_candidate_list")
public String importCandidate(ModelMap modelMap,HttpServletRequest request,Long examId,String candidateList) {
examService.importCandidate(examId, candidateList);
modelMap.put("info", "true");
return "json";
}
@RequestMapping("import_exam_item_list")
public String importExamItemList(ModelMap modelMap,HttpServletRequest request,Long examId,String examItemList) {
examService.importExamItem(examId, examItemList);
modelMap.put("info", "true");
return "json";
}
@RequestMapping("delete_candidate_from_exam")
public String deleteCandidateFromExam(ModelMap modelMap,HttpServletRequest request,Long examId,Long candidateId) {
examService.deleteCandidate(examId, candidateId);
modelMap.put("info", "true");
return "json";
}
@RequestMapping("get_exam_candidate_list")
public String getExamCandidateList(ModelMap modelMap,HttpServletRequest request,Long examId) {
Exam exam = examService.getExamById(examId);
List<User> candiateList = exam.getCandidates();
List<Long> retList = new ArrayList<>();
for(User user:candiateList) {
retList.add(user.getId());
}
modelMap.put("info", MyJson.toJson(retList));
return "json";
}
@RequestMapping("get_exam_exam_item_list")
public String getExamExamItemList(ModelMap modelMap,HttpServletRequest request,Long examId) {
Exam exam = examService.getExamById(examId);
List<ExamItem> examItemList = exam.getExamItems();
List<Long> retList = new ArrayList<>();
for(ExamItem examItem:examItemList) {
retList.add(examItem.getId());
}
modelMap.put("info", MyJson.toJson(retList));
return "json";
}
@RequestMapping("delete_exam_item_from_exam")
public String deleteExamItemFromExam(ModelMap modelMap,HttpServletRequest request,Long examId,Long examItemId) {
examService.deleteExamItem(examId, examItemId);
modelMap.put("info", "true");
return "json";
}
@RequestMapping("logout")
public String logout(ModelMap modelMap,HttpServletRequest request) {
request.getSession(true).setAttribute("currentUser", null);
return "redirect:/login";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.