text
stringlengths 10
2.72M
|
|---|
package com.stryksta.swtorcentral.util;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.stryksta.swtorcentral.models.RssItem;
public class RssParseHandler extends DefaultHandler {
private ArrayList<RssItem> rssItems;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingDescription;
private boolean parsingDate;
private StringBuffer currentTitleSb;
private StringBuffer currentDescriptionSb;
private StringBuffer currentDateSb;
String LinkType;
String LinkRel;
String category;
public RssParseHandler() {
rssItems = new ArrayList<RssItem>();
}
public ArrayList<RssItem> getItems() {
return rssItems;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if ("entry".equals(qName)) {
currentItem = new RssItem();
} else if ("title".equals(qName)) {
parsingTitle = true;
currentTitleSb = new StringBuffer();
} else if ("summary".equals(qName)) {
parsingDescription = true;
currentDescriptionSb = new StringBuffer();
} else if ("updated".equals(qName)) {
parsingDate = true;
currentDateSb = new StringBuffer();
} else if ("link".equals(qName)) {
LinkType = attributes.getValue("rel");
LinkRel = attributes.getValue("href");
} else if ("category".equals(qName)) {
category = attributes.getValue("term");
//Log.d("SWTORCentral", category.toString());
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if ("entry".equals(qName)) {
rssItems.add(currentItem);
currentItem = null;
} else if ("title".equals(qName)) {
parsingTitle = false;
if (currentItem != null)
currentItem.setTitle(currentTitleSb.toString());
} else if ("summary".equals(qName)) {
parsingDescription = false;
if (currentItem != null)
currentItem.setDescription(currentDescriptionSb.toString());
} else if ("updated".equals(qName)) {
parsingDate = false;
if (currentItem != null)
currentItem.setPubDate(currentDateSb.toString());
} else if ("category".equals(qName)) {
if (currentItem != null)
currentItem.setCategory(category.toString());
//Log.d("SWTORCentral", category.toString());
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (parsingTitle) {
if (currentItem != null)
currentTitleSb.append(new String(ch, start, length));
} else if (parsingDescription) {
if (currentItem != null)
currentDescriptionSb.append(new String(ch, start, length));
} else if (parsingDate) {
if (currentItem != null)
currentDateSb.append(new String(ch, start, length));
}
if (currentItem != null) {
if (LinkType.equals("alternate")) {
currentItem.setLink(LinkRel);
} else if (LinkType.equals("enclosure")){
currentItem.setImage(LinkRel);
}
}
}
}
|
import java.util.ArrayList;
import java.util.Random;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
/**
* @author Anders Hagward
* @author Fredrik Hillnertz
* @version 2010-05-06
*/
public abstract class PowerUp extends Rectangle implements Movable {
private static final long serialVersionUID = 3337170896734989953L;
public static int EXTEND = 0, RETRACT = 1, ADD_BALL = 2, PSPEED = 3,
MSPEED = 4, LASER = 5, PLIFE = 6, MLIFE = 7, FIREBALL = 8;
protected int duration;
protected float xSpeed;
protected float ySpeed;
protected Image image;
protected PowerUp(float x, float y, Image image) {
super(x, y, image.getWidth(), image.getHeight());
xSpeed = 0;
ySpeed = 0.15f;
this.image = image;
}
public abstract void effect(LevelHandler level) throws SlickException;
@Override
public void move(int delta) {
y += ySpeed * delta;
}
@Override
public void setXSpeed(float xSpeed) {
return;
}
@Override
public void setYSpeed(float ySpeed) {
this.ySpeed = ySpeed;
}
@Override
public float getXSpeed() {
return xSpeed;
}
@Override
public float getYSpeed() {
return ySpeed;
}
@Override
public void incrementXSpeed(float increment) {
return;
}
@Override
public void incrementYSpeed(float increment) {
ySpeed += increment;
}
public void draw() {
image.draw(x, y);
}
public static String powerUpImageName(int i) {
switch (i) {
case 0:
return "ExtendRacket.png";
case 1:
return "RetractRacket.png";
case 2:
return "multiplyballs.png";
case 3:
return "speed+.png";
case 4:
return "speed-.png";
case 5:
return "lasers.png";
case 6:
return "life+.png";
case 7:
return "life-.png";
case 8:
return "fireballs.png";
}
return null;
}
public static PowerUp randomPowerUp(Block block) throws SlickException {
float xPos = block.getX();
float yPos = block.getY();
int r = block.getPowerUp();
if (r < 0) {
Random rand = new Random();
if (rand.nextInt(4) != 0)
return null;
r = rand.nextInt(9);
}
switch (r) {
case 0:
return new ExtendRacket(xPos, yPos);
case 1:
return new RetractRacket(xPos, yPos);
case 2:
return new AddBall(xPos, yPos);
case 3:
return new Speed(xPos, yPos, 1);
case 4:
return new Speed(xPos, yPos, -1);
case 5:
return new PewPewLasers(xPos, yPos);
case 6:
return new Life(xPos, yPos, 1);
case 7:
return new Life(xPos, yPos, -1);
case 8:
return new Fireballs(xPos, yPos);
}
return null;
}
public static class RetractRacket extends PowerUp {
private static final long serialVersionUID = -2425503375922462872L;
public RetractRacket(float xPos, float yPos) throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("RetractRacket.png"));
}
@Override
public void effect(LevelHandler level) throws SlickException {
level.getRacket().decreaseSize();
}
}
public static class ExtendRacket extends PowerUp {
private static final long serialVersionUID = -4958823379809789717L;
public ExtendRacket(float xPos, float yPos) throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("ExtendRacket.png"));
}
@Override
public void effect(LevelHandler level) throws SlickException {
level.getRacket().increaseSize();
}
}
public static class AddBall extends PowerUp {
private static final long serialVersionUID = -6550943363444882422L;
public AddBall(float xPos, float yPos) throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("multiplyballs.png"));
}
@Override
public void effect(LevelHandler level) throws SlickException {
ArrayList<Ball> balls = level.getBalls();
if (balls.size() > 0) {
Ball origBall = balls.get(0);
Ball newBall = new Ball(origBall.getX(), origBall.getY());
newBall.setXSpeed(-origBall.getXSpeed());
newBall.setYSpeed(origBall.getYSpeed());
Ball newBall2 = new Ball(origBall.getX(), origBall.getY());
newBall2.setXSpeed(origBall.getXSpeed());
newBall2.setYSpeed(-origBall.getYSpeed());
balls.add(newBall);
balls.add(newBall2);
}
}
}
public static class Speed extends PowerUp {
private static final long serialVersionUID = -8861061013150381349L;
private float multiplier;
public Speed(float xPos, float yPos, int dir) throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("speed+.png"));
if (dir > 0) {
multiplier = 1.5f;
} else {
multiplier = 0.5f;
image = ResourceLoader.getInstance().getImage("speed-.png");
}
}
@Override
public void effect(LevelHandler level) {
ArrayList<Ball> balls = level.getBalls();
for (Ball ball : balls) {
ball.setXSpeed(multiplier * ball.getXSpeed());
ball.setYSpeed(multiplier * ball.getYSpeed());
}
ArrayList<PowerUp> pus = level.getPowerUps();
for (PowerUp pu : pus) {
pu.setYSpeed(multiplier * pu.getYSpeed());
}
}
}
public static class PewPewLasers extends PowerUp {
private static final long serialVersionUID = -1339389505069960388L;
private float shots = 20;
private Racket racket;
private ArrayList<Ball> balls;
public PewPewLasers(float xPos, float yPos) throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("lasers.png"));
}
@Override
public void effect(LevelHandler level) throws SlickException {
balls = level.getBalls();
racket = level.getRacket();
racket.addLasers(this);
}
public void shot() throws SlickException {
shots--;
if (shots == 0)
racket.removeLasers();
balls.add(new LaserShot());
}
class LaserShot extends Ball {
private static final long serialVersionUID = 8834007952965136151L;
public LaserShot() throws SlickException {
super(racket.getCenterX(), racket.getY() - 20);
this.image = ResourceLoader.getInstance().getImage(
"lasershot.png");
setXSpeed(0f);
setYSpeed(-.2f);
balls.add(this);
}
@Override
public void setYSpeed(float ySpeed) {
if (ySpeed == -this.getYSpeed())
this.ySpeed = 0;
else
this.ySpeed = ySpeed;
}
}
}
public static class Life extends PowerUp {
private static final long serialVersionUID = -804012507251184235L;
private int plusMinus;
public Life(float xPos, float yPos, int plusMinus)
throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("life+.png"));
this.plusMinus = plusMinus;
if (plusMinus < 0)
image = ResourceLoader.getInstance().getImage("life-.png");
}
@Override
public void effect(LevelHandler level) throws SlickException {
if (plusMinus < 0)
level.getPlayer().decreaseLives();
else
level.getPlayer().increaseLives();
}
}
public static class Fireballs extends PowerUp {
private static final long serialVersionUID = -6934067609858958243L;
private ArrayList<Ball> balls;
private ArrayList<Ball> extraBalls;
private ArrayList<Effect> animations;
public Fireballs(float xPos, float yPos) throws SlickException {
super(xPos, yPos,
ResourceLoader.getInstance().getImage("fireballs.png"));
}
@Override
public void effect(LevelHandler level) throws SlickException {
this.balls = level.getBalls();
this.extraBalls = level.getExtraBalls();
this.animations = level.getAnimations();
Ball ball = balls.get(0);
float xSpeed = ball.getXSpeed();
float ySpeed = ball.getYSpeed();
float xPos = ball.getCenterX();
float yPos = ball.getCenterY();
ball.setXSpeed(0);
ball.setYSpeed(0);
Fireball fireball = new Fireball(xPos, yPos);
fireball.setXSpeed(xSpeed);
fireball.setYSpeed(ySpeed);
balls.add(fireball);
}
class Fireball extends Ball {
private static final long serialVersionUID = -5400086564573984130L;
private int hits = 6;
public Fireball(float centerPointX, float centerPointY)
throws SlickException {
super(centerPointX, centerPointY);
this.image = ResourceLoader.getInstance().getImage(
"fireball.png");
}
@Override
public void setXSpeed(float xSpeed) {
if (xSpeed == -this.xSpeed) {
hits--;
ArrayList<Ball> newBalls = null;
try {
newBalls = creatBalls();
createEffect();
} catch (SlickException e) {
}
extraBalls.addAll(newBalls);
}
this.xSpeed = xSpeed;
if (hits <= 0)
removeFireball();
}
@Override
public void setYSpeed(float ySpeed) {
if (ySpeed == -this.ySpeed) {
hits--;
ArrayList<Ball> newBalls = null;
try {
newBalls = creatBalls();
createEffect();
} catch (SlickException e) {
}
extraBalls.addAll(newBalls);
}
this.ySpeed = ySpeed;
if (hits <= 0)
removeFireball();
}
private void removeFireball() {
Ball ball = new Ball(this.x, this.y);
ball.setXSpeed(this.xSpeed);
ball.setYSpeed(this.ySpeed);
this.xSpeed = 0;
this.ySpeed = 0;
extraBalls.add(ball);
}
private ArrayList<Ball> creatBalls() throws SlickException {
float x = this.getCenterX();
float y = this.getCenterY();
ArrayList<Ball> balls = new ArrayList<Ball>();
class InvisibleBall extends Ball {
private static final long serialVersionUID = -1950391023146557602L;
public InvisibleBall(float x, float y)
throws SlickException {
super(x, y);
this.image = ResourceLoader.getInstance().getImage(
"invisibleball.png");
}
@Override
public void setXSpeed(float x) {
this.xSpeed = 0;
}
@Override
public void setYSpeed(float y) {
this.ySpeed = 0;
}
@Override
public void setX(float x) {
}
@Override
public void setY(float y) {
}
}
InvisibleBall ball1 = new InvisibleBall(x - 30, y - 14);
InvisibleBall ball2 = new InvisibleBall(x - 30, y);
InvisibleBall ball3 = new InvisibleBall(x - 30, y + 14);
InvisibleBall ball4 = new InvisibleBall(x, y - 14);
InvisibleBall ball5 = new InvisibleBall(x, y + 14);
InvisibleBall ball6 = new InvisibleBall(x + 30, y - 14);
InvisibleBall ball7 = new InvisibleBall(x + 30, y);
InvisibleBall ball8 = new InvisibleBall(x + 30, y + 14);
balls.add(ball1);
balls.add(ball2);
balls.add(ball3);
balls.add(ball4);
balls.add(ball5);
balls.add(ball6);
balls.add(ball7);
balls.add(ball8);
for (Ball ball : balls)
ball.setYSpeed(0);
return balls;
}
private void createEffect() throws SlickException {
animations.add(new Effect.FireSplash(x - 30, y - 14));
}
}
}
}
|
package inheritance.service;
public class Car extends MotorVehicle {
int discountRate;
public Car(String modelName,int modelNumber,int modelPrice,int discountRate) {
this(discountRate);
this.modelName=modelName;
this.modelNumber=modelNumber;
this.modelPrice=modelPrice;
}
public Car(int discountRate) {
this.discountRate = discountRate;
}
// public Car(String modelName, int modelNumber, int modelPrice, int discountRate) {
// super(modelName, modelNumber, modelPrice);
// this.discountRate = discountRate;
// }
public void discount() {
float dR = (float) (discountRate / 100.00);
float discount = modelPrice * dR;
System.out.println("discount is : " + discount);
}
public void display() {
super.display();
// System.out.println("Car Name : " + modelName);
// System.out.println("Car Model : " + modelNumber);
// System.out.println("Car Price : " + modelPrice);
System.out.println("discount Rate : " + 20);
}
}
|
package com.a1tSign.techBoom.service.admin;
public interface AdminService {
void makeAdmin(String username);
void makeUser(String username);
void createNewRole(String role);
void updateRole(String role, String newName);
void deleteRole(String role);
}
|
package com;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author anthony_xu
* @version $$Id: bkpartner-parent, v 0.1 2018/05/14 15:09 anthony_xu Exp $$
*/
@SpringBootApplication
@MapperScan("com.netty.dao.mapper")
public class Main {
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
|
///**
// * Paintroid: An image manipulation application for Android.
// * Copyright (C) 2010-2013 The Catrobat Team
// * (<http://developer.catrobat.org/credits>)
// *
// * This program is free software: you can redistribute it and/or modify
// * it under the terms of the GNU Affero 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 Affero General Public License for more details.
// *
// * You should have received a copy of the GNU Affero General Public License
// * along with this program. If not, see <http://www.gnu.org/licenses/>.
// */
//
//package org.catrobat.paintroid.test.junit.main;
//
//import org.catrobat.paintroid.MainActivity;
//import org.catrobat.paintroid.test.junit.stubs.TopBarStub;
//import org.catrobat.paintroid.test.utils.PrivateAccess;
//
//import android.test.ActivityInstrumentationTestCase2;
//
//public class MainActivityTests extends ActivityInstrumentationTestCase2<MainActivity> {
//
// private static final String PRIVATE_ACCESS_STATUSBAR_NAME = "mTopBar";
//
// MainActivity mainActivity;
// TopBarStub statusbarStub;
//
// public MainActivityTests() {
// super(MainActivity.class);
// }
//
// @Override
// public void setUp() throws Exception {
// mainActivity = this.getActivity();
// statusbarStub = new TopBarStub(mainActivity, false);
// PrivateAccess.setMemberValue(MainActivity.class, mainActivity, PRIVATE_ACCESS_STATUSBAR_NAME, statusbarStub);
// }
//
// // status bar is already tested
// // @UiThreadTest
// // public void testShouldSetNewToolOnToolbar() throws SecurityException, IllegalArgumentException,
// // NoSuchFieldException, IllegalAccessException {
// // Intent data = new Intent();
// // int brushIndex = -1;
// // for (int index = 0; index < ToolType.values().length; index++) {
// // if (ToolType.values()[index] == ToolType.BRUSH) {
// // brushIndex = index;
// // break;
// // }
// // }
// // data.putExtra("EXTRA_SELECTED_TOOL", brushIndex);
// //
// // int reqToolsDialogCode = (Integer) PrivateAccess.getMemberValue(MenuFileActivity.class, mainActivity,
// // "REQ_TOOLS_DIALOG");
// // mainActivity.onActivityResult(reqToolsDialogCode, Activity.RESULT_OK, data);
// //
// // assertEquals(1, statusbarStub.getCallCount("setTool"));
// // Tool tool = (Tool) statusbarStub.getCall("setTool", 0).get(0);
// // assertTrue(tool instanceof DrawTool);
// // }
//
// // figure out how to test this thing
// //
// // public void testShouldInitializeMemberFields() throws SecurityException,
// // IllegalArgumentException,
// // NoSuchFieldException, IllegalAccessException {
// // Bundle bundle = new Bundle();
// // mainActivity.onCreate(bundle);
// // SurfaceView drawingSurfaceView = (SurfaceView)
// // PrivateAccess.getMemberValue(MainActivity.class, mainActivity,
// // "drawingSurface");
// // assertNotNull(drawingSurfaceView);
// //
// // DrawingSurfacePerspective drawingSurfacePerspective = (DrawingSurfacePerspective)
// // PrivateAccess.getMemberValue(
// // MainActivity.class, mainActivity, "drawingSurfacePerspective");
// // assertNotNull(drawingSurfacePerspective);
// //
// // OnTouchListener drawingSurfaceListener = (OnTouchListener)
// // PrivateAccess.getMemberValue(MainActivity.class,
// // mainActivity, "drawingSurfaceListener");
// // assertNotNull(drawingSurfaceView);
// // }
// }
|
package com.infotec.registro;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DetalledocRepo {
Connection con = null;
public DetalledocRepo(){
Properties prop= new Properties();
String propFilename="config.properties";
String urldb="";
String usrname="";
String paswd="";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFilename);
if (inputStream != null) {
try {
prop.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
urldb= prop.getProperty("db");
usrname= prop.getProperty("usr");
paswd= prop.getProperty("pwd");
try {
Class.forName("org.mariadb.jdbc.Driver");
con = DriverManager.getConnection(urldb, usrname, paswd);
System.out.println("Conexion exitosa");
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e);
}
}
public List<Detalledoc> getDetalleDoc( int idUsr) {
List<Detalledoc> detdoc = new ArrayList<>();
String idUsuario=Integer.toString(idUsr);
String sql="SELECT detalle.*, tarea.nomtarea, evento.estado FROM detalle, evento, tarea WHERE detalle.fecha_fin IS NULL AND detalle.idtarea=tarea.idtarea AND detalle.idevento=evento.idevento AND ( detalle.idusro = " + idUsuario + " OR detalle.idusrd = " + idUsuario + " )";
try {
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql);
InformacionRepo irepo = new InformacionRepo();
while (rs.next()) {
int idEventoQuery=rs.getInt("idevento");
Detalledoc d = new Detalledoc();
d.setIdEvento(idEventoQuery);
d.setAsunto(rs.getString("asunto"));
d.setEstadoProceso(rs.getString("estado"));
d.setEstadoTarea(rs.getString("nomtarea"));
d.setFolio(rs.getString("folio"));
d.setComentarios(rs.getString("comentarios"));
d.setIdTarea (rs.getInt("idtarea"));
d.setDocumentos(irepo.getInformacion(idEventoQuery));
detdoc.add(d);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e);
}
if (detdoc.isEmpty()) {
Detalledoc d = new Detalledoc();
d.setErrorMsg("No hay elementos que cumplan con los criterios de búsqueda");
detdoc.add(d);
}
return detdoc;
}
public Detalledoc getOneDetalleDoc( int idUsr, int idEvento) {
String idUsuario=Integer.toString(idUsr);
String idEve=Integer.toString(idEvento);
Detalledoc d = new Detalledoc();
String sql="SELECT detalle.*, tarea.nomtarea, evento.estado FROM detalle, evento, tarea WHERE detalle.fecha_fin IS NULL AND detalle.idtarea=tarea.idtarea AND detalle.idevento=evento.idevento AND ( detalle.idusro = " + idUsuario + " OR detalle.idusrd = " + idUsuario + " ) AND detalle.idevento=" + idEve;
try {
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(sql);
InformacionRepo irepo = new InformacionRepo();
while (rs.next()) {
int idEventoQuery=rs.getInt("idevento");
d.setIdEvento(idEventoQuery);
d.setAsunto(rs.getString("asunto"));
d.setEstadoProceso(rs.getString("estado"));
d.setEstadoTarea(rs.getString("nomtarea"));
d.setFolio(rs.getString("folio"));
d.setComentarios(rs.getString("comentarios"));
d.setIdTarea (rs.getInt("idtarea"));
d.setDocumentos(irepo.getInformacion(idEventoQuery));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e);
}
if (d.getIdTarea()==0) {
d.setErrorMsg("No existe informacón con los criterios de búsqueda seleccionados");
}
return d;
}
}
|
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.json.JSONObject;
public class Client {
static String IP = "140.113.62.101";
static int port = 9605;
static String destinationIP = "140.113.87.160";
static int destinationPort = 5566;
static DatagramSocket clientSocket;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
clientSocket = new DatagramSocket();
int head = 3000, tail = 60000;
int guessPort;
int count = 1;// 計數器
System.out.println("#set up");
System.out.println("UDP Client listening on " + IP + ":" + port);
System.out.println();
// s1
while (true) {
System.out.println("#" + count);
count++;
JSONObject jsn = new JSONObject();
guessPort = (head + tail) / 2;
if (head == tail)
break;
jsn.put("guess", guessPort);
System.out.println("send " + jsn.toString());
String receiveStr = udpConnection(jsn.toString(),
destinationIP, destinationPort);
JSONObject resultJsn = new JSONObject(receiveStr);
String result = resultJsn.getString("result");
System.out.println("receive " + resultJsn.toString());
if (result.equals("bingo!")) {
break;
} else if (result.equals("smaller")) {
tail = guessPort - 1;
} else if (result.equals("larger")) {
head = guessPort + 1;
} else {
}
}
System.out.println("#" + count);
// s2
JSONObject jsn = new JSONObject();
jsn.put("student_id", "0440062");
System.out.println("send " + jsn.toString());
String receiveStr = udpConnection(jsn.toString(), destinationIP,
guessPort);
JSONObject resultJsn = new JSONObject(receiveStr);
System.out.println("receive " + resultJsn.toString());
clientSocket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static String udpConnection(String sendStr, String ipAddress, int port) {
String receiveStr = null;
try {
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
DatagramPacket sendPacket;
DatagramPacket receivePacket;
sendData = sendStr.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName(ipAddress), port);
clientSocket.send(sendPacket);
receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
receiveStr = new String(receivePacket.getData());
} catch (Exception e) {
e.printStackTrace();
}
return receiveStr;
}
}
|
package com.cos.oauth2jwt.web.dto.post;
import org.springframework.web.multipart.MultipartFile;
import com.cos.oauth2jwt.domain.post.Post;
import com.cos.oauth2jwt.domain.user.User;
import lombok.Data;
@Data
public class PostReqDto {
private MultipartFile file;
private String caption;
private String tags;
public Post toEntity(String postImageUrl, User userEntity) {
return Post.builder()
.caption(caption)
.postImageUrl(postImageUrl)
.user(userEntity)
.build();
}
}
|
package cn.czfshine.network.p2p.client.DO;
import lombok.Data;
/**
* @author:czfshine
* @date:2019/4/18 12:44
*/
@Data
public class BlockDO {
private String filename;
private String seq;
private String source;
private String state;
private String size;
public BlockDO() {
}
public BlockDO(String filename, String seq, String source, String state, String size) {
this.filename = filename;
this.seq = seq;
this.source = source;
this.state = state;
this.size = size;
}
}
|
package com.example.university.filters;
import com.example.university.commands.CommandManager;
import com.example.university.utils.Path;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* Filter which performs authorization of the user to access resources of the
* application.
*/
public class AuthFilter implements Filter {
private static final Logger LOG = LogManager.getLogger(AuthFilter.class);
private static final String ERROR_GENERAL_ERROR = "error_message.general_error";
// accessible by all users
private final Set<String> accessibleCommands;
// accessible only by logged-in users
private final Set<String> commonCommands;
// accessible only by user
private final Set<String> userCommands;
// accessible only by admin
private final Set<String> adminCommands;
public AuthFilter() {
accessibleCommands = new HashSet<>();
commonCommands = new HashSet<>();
userCommands = new HashSet<>();
adminCommands = new HashSet<>();
accessibleCommands.add("login");
accessibleCommands.add("viewFaculty");
accessibleCommands.add("viewAllFaculties");
accessibleCommands.add("userRegistration");
accessibleCommands.add("confirmRegistration");
accessibleCommands.add("setSessionLanguage");
// common commands
commonCommands.add("logout");
commonCommands.add("viewProfile");
commonCommands.add("editProfile");
// user commands
userCommands.add("applyFaculty");
// admin commands
adminCommands.add("adminRegistration");
adminCommands.add("editFaculty");
adminCommands.add("addFaculty");
adminCommands.add("deleteFaculty");
adminCommands.add("addSubject");
adminCommands.add("editSubject");
adminCommands.add("viewAllSubjects");
adminCommands.add("viewSubject");
adminCommands.add("viewApplicant");
adminCommands.add("createReport");
adminCommands.add("deleteSubject");
adminCommands.add("confirmGrades");
}
@Override
public void init(FilterConfig fConfig) {
LOG.debug("Initializing filter: {}", AuthFilter.class.getSimpleName());
}
@Override
public void destroy() {
LOG.debug("Destroying filter: {}", AuthFilter.class.getSimpleName());
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String command = req.getParameter("command");
// Illegal command
if (!CommandManager.getAllCommands().containsKey(command)) {
LOG.debug("Invalid command: {}", command);
setErrorMessage(req, ERROR_GENERAL_ERROR);
res.sendRedirect(Path.WELCOME_PAGE);
return;
}
// commands available for all
if (accessibleCommands.contains(command)) {
LOG.debug("This command can be accessed by all users: {}", command);
chain.doFilter(req, res);
return;
}
// commands for authorised users
LOG.debug("This command can be accessed only by logged in users: {}", command);
HttpSession session = req.getSession(false);
if (session == null || session.getAttribute("user") == null) {
LOG.debug("Unauthorized access to resource. User is not logged-in.");
res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
}
// command for authorised users and user is logged in
LOG.debug("User is logged-in. Check common commands to logged in users.");
if (commonCommands.contains(command)) {
chain.doFilter(req, res);
return;
}
// command specific to user role
LOG.debug("Command is specific to user. Check user role.");
String role = session.getAttribute("userRole").toString();
// user role allows this command
if (userCommandByUser(role, command) || adminCommandByAdmin(role, command)) {
LOG.debug("Command can be executed by this user: {}", command);
chain.doFilter(req, res);
return;
}
// user role doesn't allow this command
res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
private boolean userCommandByUser(String role, String command) {
return "user".equals(role) && userCommands.contains(command);
}
private boolean adminCommandByAdmin(String role, String command) {
return "admin".equals(role) && adminCommands.contains(command);
}
protected void setErrorMessage(HttpServletRequest request, String messageKey) {
setMessage(request, "errorMessage", messageKey);
}
protected void setOkMessage(HttpServletRequest request, String messageKey) {
setMessage(request, "successfulMessage", messageKey);
}
protected void setMessage(HttpServletRequest request, String attribute, String messageKey) {
HttpSession session = request.getSession();
session.setAttribute(attribute, messageKey);
}
}
|
package com.jun.ex2.repository;
import com.jun.ex2.entity.Memo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.annotation.Commit;
import javax.transaction.Transactional;
import java.lang.reflect.Member;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;
@SpringBootTest
public class MemoRepositoryTests {
@Autowired
MemoRepository memoRepository;
@Test
public void testClass(){
System.out.println(memoRepository.getClass().getName());
}
@Test
public void testInsertDummies(){
IntStream.rangeClosed(1,100).forEach(i -> {
Memo memo = Memo.builder().memoText("Sample...." + i).build();
memoRepository.save(memo);
});
}
@Test
public void testSelect(){
//findById 사용 - findById 사용 순간에 SQL 처리완료
//데이터베이스에 존재하는 mno
Long mno = 100L;
Optional<Memo> result = memoRepository.findById(mno);
System.out.println("================================");
if(result.isPresent()){
Memo memo = result.get();
System.out.println(memo);
}
}
@Transactional
@Test
public void testSelect2(){
//getOne 사용 - 실제 객체를 사용하는 순간에 SQL 동작
//데이터베이스에 존재하는 mno
Long mno = 100L;
//@Deprecated 되었음
Memo memo = memoRepository.getOne(mno);
System.out.println("================================");
System.out.println(memo);
}
@Test
public void testUpdate(){
//save 사용 - Entity 객체 존재 확인(SELECT) 후 해당 @Id를 가진 Entity 객체가 있다면 update, 없다면 insert
Memo memo = Memo.builder().mno(100L).memoText("Update Text").build();
System.out.println(memoRepository.save(memo));
}
@Test
public void testDelete(){
//deleteById 사용 - select 이후 delete
//해당 데이터 존재하지 않으면 org.spring.framework.dao.EmptyDataAccessException 발생
Long mno = 100L;
memoRepository.deleteById(mno);
}
//페이징 처리
//1. Oracle : 인 라인 뷰(inline view)
//2. MySQL : limit
//3. JPA : Dialect - JPA는 findAll() 메서드로 페이징 처리와 정렬을 합니다.
//Spring Data JPA를 이용할 때 페이지 처리는 반드시 '0'부터 시작한다는 점
@Test
public void testPageDefault(){
//1페이지 10개
Pageable pageable = PageRequest.of(0,10 );
Page<Memo> result = memoRepository.findAll(pageable);
System.out.println(result);
System.out.println("================================");
System.out.println("Total Pages : " + result.getTotalPages()); //총 몇 페이지
System.out.println("Total Count : " + result.getTotalElements()); //전체 갯수
System.out.println("Page Number : " + result.getNumber()); //현재 페이지 번호
System.out.println("Page Size : " + result.getSize()); //페이지당 데이터 갯수
System.out.println("has next page? : " + result.hasNext()); //다음 페이지
System.out.println("first page? : " + result.isFirst()); //시작 페이지(0) 여부
System.out.println("================================");
for(Memo memo : result.getContent()){
System.out.println(memo);
}
System.out.println("================================");
}
@Test
public void testSort(){
Sort sort1 = Sort.by("mno").descending();
Sort sort2 = Sort.by("memoText").ascending();
Sort sortAll = sort1.and(sort2); //and를 이용한 연결
Pageable pageable = PageRequest.of(0, 10, sortAll);
Page<Memo> result = memoRepository.findAll(pageable);
result.get().forEach(memo -> {
System.out.println(memo);
});
}
//쿼리 메서드
@Test
public void testQueryMethods(){
List<Memo> list = memoRepository.findByMnoBetweenOrderByMnoDesc(70L, 80L);
for (Memo memo : list){
System.out.println(memo);
}
}
//쿼리 메서드 + Pageable 결합
@Test
public void testQueryMethodWithPageable(){
Pageable pageable = PageRequest.of(0, 10, Sort.by("mno").descending());
Page<Memo> result = memoRepository.findByMnoBetween(10L, 50L, pageable);
result.get().forEach(memo -> System.out.println(memo));
}
//쿼리 메서드 - 삭제처리 : 하나씩 삭제해서 비효율적이다. -> deleteBy를 이용하는 방식보다는 @Query를 이용해서 개선
@Commit
@Transactional
@Test
public void testDeleteQueryMethods(){
memoRepository.deleteMemoByMnoLessThan(10L);
}
}
|
package uk.ac.ed.inf.aqmaps.visualisation;
/**
* Attribute maps divide their domain into attribute buckets and allow for quick retrieval of the necessary attributes
*/
public interface AttributeMap<T,C> {
/**
* Retrieve attribute for the given input
* @param o input
* @return
*/
public C getFor(T o);
}
|
package com.gcit.training.client;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
boolean cont = true;
while(cont){ //loop back to main menu
System.out.println("Welcome to the GCIT Library Management System. "
+ "Which category of user are you?\n1)Librarian \n2)Administrator \n3)Borrower");
int ch = input.nextInt(); //user's choice
boolean cont2 = true;
switch (ch) {
case 1:
//Librarian
while(cont2){
LibrarianClient lib = new LibrarianClient();
System.out.println("LIBRARIAN\n1) Enter branch you manage \n2) Quit to previous");
int x = input.nextInt();
if(x == 1){
try {
lib.begin(input);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
cont2 = false;
}
break;
case 2:
AdministratorClient admin = new AdministratorClient();
try {
admin.begin(input);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case 3:
//borrower
BorrowerClient borr = new BorrowerClient();
try {
borr.begin(input);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
default:
break;
}
}//loop back to main menu
}
}
|
/*
* Copyright 2018 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.pets;
import io.micronaut.context.annotation.ConfigurationProperties;
/**
* @author graemerocher
* @since 1.0
*/
@ConfigurationProperties("pets")
public class PetsConfiguration {
private String databaseName = "petstore";
private String collectionName = "pets";
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
public String getCollectionName() {
return collectionName;
}
public void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
}
|
/**
* Copyright © 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved.
*/
package com.beiyelin.account.service;
import com.beiyelin.account.bean.AccountQuery;
import com.beiyelin.account.entity.Account;
import com.beiyelin.account.entity.AccountOauth;
import com.beiyelin.common.reqbody.PageReq;
import com.beiyelin.common.resbody.PageResp;
import com.beiyelin.commonsql.jpa.BaseDomainCRUDService;
import com.beiyelin.commonsql.jpa.MasterDataCRUDService;
import java.util.List;
/**
* 部门管理
* @author Newmann
* @version 2017-03-18
*/
public interface AccountOauthService extends BaseDomainCRUDService<AccountOauth> {
AccountOauth findFirstByProviderIdAndProviderUserId(String providerId, String providerUserId);
}
|
package pers.pbyang.dao;
import java.util.List;
import pers.pbyang.entity.Member;
public interface MemberDao {
public boolean delete(int id) throws Exception ;
public boolean insert(Member memid) throws Exception ;
public boolean update(Member mem,int id) throws Exception ;
public boolean update1(Member mem,int id) throws Exception ;
public boolean update2(Member mem,int id) throws Exception ;
public List<Member> finAll() throws Exception;
public Member findByNumid(String username) throws Exception;
public Member findByNumid1(String username,String password) throws Exception;
public Member findByNumid2(int memid) throws Exception;
}
|
package com.wyg.eurekaclient.service.hystrix;
import com.wyg.eurekaclient.service.AdminService;
import org.springframework.stereotype.Component;
@Component
public class AdminServiceHystrix implements AdminService{
@Override
public String sayHello(String message) {
return String.format("Hi your message is :%s but request bad",message);
}
}
|
package it.polimi.se2019.controller.weapons.alternative_effects;
import it.polimi.se2019.rmi.UserTimeoutException;
import it.polimi.se2019.controller.GameBoardController;
import it.polimi.se2019.model.player.Player;
import it.polimi.se2019.view.player.PlayerViewOnServer;
import java.util.ArrayList;
import java.util.List;
/**
* @author Eugenio OStrovan
* @author Fabio Mauri
*/
public class ZX2Controller extends AlternativeEffectWeaponController {
public ZX2Controller(GameBoardController g) {
super(g);
name = "ZX2";
}
PlayerViewOnServer client;
@Override
public List<Player> findTargets(Player shooter) throws UserTimeoutException {
client = identifyClient(shooter);
List<Player> targets = new ArrayList<>();
//firingMode = selectFiringMode(client);
if(firingMode.get(0)){
List<String> names = new ArrayList<>();
names = GameBoardController.getPlayerNames
(map.getPlayersOnSquares(
map.getVisibleSquares(
shooter.getPosition()
)
));
names.remove(shooter.getName());
if(!names.isEmpty()){
targets.add
(gameBoardController.identifyPlayer
(client.chooseTargets
(names)));
}
}
else{
List<Player> possibleTargets = map.getPlayersOnSquares(
map.getVisibleSquares(
shooter.getPosition()
)
);
for(int i = 0; i<2; i++){
if(!possibleTargets.isEmpty()){
targets.add
(i, gameBoardController.identifyPlayer
(client.chooseTargets
(GameBoardController.getPlayerNames
(possibleTargets))));
possibleTargets.remove(targets.get(i));
}
}
}
return targets;
}
@Override
public void shootTargets(Player shooter, List<Player> targets) throws UserTimeoutException {
if(firingMode.get(0)){
targets.get(0).takeDamage(shooter, 1);
//add one more point of damage if the player chooses to use a targeting scope
if(useTargetingScope(shooter)){
targets.get(0).takeDamage(shooter, 1);
}
//if the damaged target has a tagback gredade, he/she can use it now
useTagbackGrenade(targets.get(0));
targets.get(0).takeMarks(shooter, 2);
}
else{
for(Player p : targets){
p.takeMarks(shooter, 1);
}
}
}
}
|
package ec.com.yacare.y4all.activities.dispositivo;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import ec.com.yacare.y4all.activities.R;
import ec.com.yacare.y4all.lib.util.AudioQueu;
public class BuscarTelefonoActivity extends Activity {
private Button btnCerrar;
private static MediaPlayer mp1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isScreenLarge()) {
AudioQueu.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
AudioQueu.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.activity_buscar_telefono);
btnCerrar = (Button) findViewById(R.id.btnCerrar);
btnCerrar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
mp1.stop();
AudioQueu.buscarCelular = false;
BuscarTelefonoActivity.this.finish();
}
});
if(getIntent().getExtras() != null && getIntent().getExtras().get("buscar") != null) {
PowerManager pm;
WakeLock wl;
KeyguardManager km;
// KeyguardLock kl;
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
// kl = km.newKeyguardLock("INFO");
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "INFO");
wl.acquire(); //wake up the screen
//// kl.disableKeyguard();// dismiss the keyguard
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
if(!AudioQueu.buscarCelular) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mp1 = MediaPlayer.create(getApplicationContext(), notification);
mp1.start();
AudioQueu.buscarCelular = true;
}
}
}
public boolean isScreenLarge() {
final int screenSize = getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK;
return screenSize == Configuration.SCREENLAYOUT_SIZE_LARGE
|| screenSize == Configuration.SCREENLAYOUT_SIZE_XLARGE;
}
}
|
/**
*
*/
package edu.buffalo.cse.irf14.document;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author nikhillo
* Class that parses a given file into a Document
*/
public class Parser {
/**
* Static method to parse the given file into the Document object
* @param filename : The fully qualified filename to be parsed
* @return The parsed and fully loaded Document object
* @throws ParserException In case any error occurs during parsing
*/
private static final Pattern authorLinePattern = Pattern.compile("<AUTHOR>(.*)</AUTHOR>");
private static final String remove_AUTHOR_Tag_Pattern = "\\s*</*AUTHOR>\\s*";
private static final String remove_By_From_Author_Pattern = "\\S*[by|BY|By|bY]\\s+";
private static final Pattern titlePattern = Pattern.compile("\\s*[a-zA-Z0-9]*;+\\s*");
private static final Pattern datePattern = Pattern.compile("\\d*\\s*(?:[Jj]an(?:uary)?|[Ff]eb(?:ruary)?|[mM][aA][rR](?:[Cc][Hh])?|[aA]pr(?:il)?|[mM]ay?|[jJ]un(?:e)?|[jJ]ul(?:y)?|[aA]ug(?:ust)?|[sS]ep(?:tember)?|[Oo]ct(?:ober)?|([Nn]ov|[Dd]ec)(?:ember))+\\s*\\d+\\s*");
public static Document parse(String filename) throws ParserException {
BufferedReader reader = null;
try {
if (filename == null || filename.isEmpty()){
throw new ParserException("File name cannot be null or empty.");
}
File inputFile = new File(filename);
if (!inputFile.isFile()){
throw new ParserException("File name cannot contain special characters.");
}
reader = new BufferedReader(new FileReader(filename));
Document doc = new Document();
if(reader != null) {
String line = null;
String place = "";
String content = "";
String publishedDate = "";
boolean isTitleLine = true, isSecondLine = true, isPlaceDateLine = true;
String[] placeDateString = null;
doc.setField(FieldNames.FILEID, inputFile.getName());
doc.setField(FieldNames.CATEGORY, inputFile.getParentFile().getName());
while((line = reader.readLine()) != null) {
if(!line.trim().isEmpty()) {
if(isTitleLine) {
if (!(titlePattern.matcher(line).matches())){
doc.setField(FieldNames.TITLE, line.trim());
isTitleLine = false;
}
} else if(isSecondLine && authorLinePattern.matcher(line).matches()) {
line = line.replaceAll(remove_AUTHOR_Tag_Pattern, "").replaceFirst(remove_By_From_Author_Pattern, "");
String authorParams[] = line.split(",");
if(authorParams.length > 1) {
doc.setField(FieldNames.AUTHORORG, authorParams[1].trim());
}
doc.setField(FieldNames.AUTHOR, authorParams[0]);
isSecondLine = false;
} else if (isPlaceDateLine){
//TODO Parse and get place and date.
if (line.contains(" - ")) {
String[] contentFirstLine = line.split("-", 2);
content += contentFirstLine[contentFirstLine.length - 1].trim();
placeDateString = contentFirstLine[0].split(",");
int length = placeDateString.length;
if (datePattern.matcher(placeDateString[placeDateString.length - 1]).matches()){
length = placeDateString.length - 1;
publishedDate = placeDateString[placeDateString.length - 1];
}
if (length >= 1){
place = placeDateString[0];
}
for (int i = 1; i < length; i++){
place = place + ", " + placeDateString[i].trim();
}
doc.setField(FieldNames.NEWSDATE, publishedDate.trim());
} else {
Matcher dateMatch = datePattern.matcher(line);
if (dateMatch.find()){
doc.setField(FieldNames.NEWSDATE, dateMatch.group().trim());
String[] textArray = line.split(dateMatch.group());
content += textArray[textArray.length - 1].trim();
}
else {
content += line.trim();
}
}
doc.setField(FieldNames.PLACE, place.trim());
isPlaceDateLine = false;
} else {
content = content + " " + line.trim();
}
}
}
doc.setField(FieldNames.CONTENT, content);
return doc;
}
}
catch(IOException ex) {
System.err.println(ex);
}
finally {
try {
if(reader != null) reader.close();
} catch (IOException e) {
System.err.println(e);
}
}
return null;
}
}
|
package com.tt.miniapp.manager.basebundle.handler;
import com.tt.miniapp.event.BaseBundleEventHelper;
import com.tt.miniapphost.util.TimeMeter;
import java.io.File;
public class BundleHandlerParam {
public BaseBundleEventHelper.BaseBundleEvent baseBundleEvent;
public long bundleVersion;
public boolean isIgnoreTask;
public boolean isLastTaskSuccess;
public File targetZipFile;
public TimeMeter timeMeter;
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\manager\basebundle\handler\BundleHandlerParam.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package advisor.View;
import advisor.Config;
import advisor.Model.SpotifyData;
import java.util.List;
import java.util.Scanner;
public class PrintData {
static int elem;
static int page;
static List<SpotifyData> data;
static int pagesCount;
public static void print(List<SpotifyData> data) {
elem = -5;
page = 0;
PrintData.data = data;
pagesCount = data.size() / Config.RESULTS_PER_PAGE;
pagesCount += data.size() % Config.RESULTS_PER_PAGE != 0 ? 1 : 0;
printNextPage();
}
public static void printNextPage() {
if (page > pagesCount) {
System.out.println("No more pages.");
} else {
elem += Config.RESULTS_PER_PAGE;
page++;
print();
}
}
public static void printPrevPage() {
if (page == 1) {
System.out.println("No more pages.");
} else {
elem -= Config.RESULTS_PER_PAGE;
page--;
print();
}
}
public static void print() {
data.stream()
.skip(elem)
.limit(Config.RESULTS_PER_PAGE)
.forEach(System.out::println);
System.out.printf("---PAGE %d OF %d---\n", page, pagesCount);
}
}
|
package BlackJack;
import BlackJack.controller.*;
public class Program
{
public static void main(String[] a_args)
{
PlayGame ctrl = new PlayGame();
while (ctrl.Play());
}
}
|
package server;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//From Week 9 Assignment Q/A
public class LoginRequest extends Request {
private String userName;
private String password;
public LoginRequest(String userName, String password){
this.userName = userName;
this.password = password;
/*
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
String input = "password";
byte [] hashedPassword = messageDigest.digest(input.getBytes());
setPassword(bytesToString(hashedPassword));
System.out.print(String.format("Password: %s Hashed Password:%s",input,bytesToString(hashedPassword)));
*/
}
public static String bytesToString(byte[] hash){
StringBuffer stringBuffer = new StringBuffer();
for (byte b : hash){
stringBuffer.append((String.format("%02x", b & 0xFF)));
}
return stringBuffer.toString();
}
public String getUserName(){
return userName;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
}
|
package com.nju.edu.cn.controller;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.nju.edu.cn.model.APIContext;
import com.nju.edu.cn.util.GetAccounts;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
//@Controller
public class SampleController {
// @Override
// protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// return application.sources(SampleController.class);
// }
APIContext context = new APIContext();
// @RequestMapping("/")
// public String index(Model model,HttpServletRequest request) throws IOException {
// GetAccounts accs = new GetAccounts();
// accs.getBizToken(request.getServletContext());
// String modulus = (String) map.get("modulus");
// String exponent = (String) map.get("exponent");
// String eventId = (String) map.get("eventId");
// model.addAttribute("modulus", modulus);
// model.addAttribute("exponent", exponent);
// model.addAttribute("eventId", eventId);
// if(modulus == null || exponent == null || eventId == null) {
// return "errorPage";
// }else {
// return "index";
// }
// }
// @RequestMapping("/login")
// public String login(HttpServletRequest request, Model model) throws IOException{
// String username = request.getParameter("username");
// String password = request.getParameter("password");
// GetAccounts accs = new GetAccounts();
// String accounts = accs.getAccounts(username, password,context);
// if(accounts != null){
// model.addAttribute("accounts", accounts);
// return "accountSummary";
// }else{
// return "errorPage";
// }
// }
//
//
// @RequestMapping("/account")
// public String account(HttpServletRequest request, Model model) throws IOException{
// String accountId = request.getParameter("accountId");
// GetAccounts accs = new GetAccounts();
// String accountDetails = accs.getAccountDetail(accountId, context);
// String transactionDetails = accs.getTransactions(accountId, context);
// if(accountDetails != null) {
// model.addAttribute("accountDetails", accountDetails);
// }
// if(transactionDetails != null){
// model.addAttribute("transactionDetails", transactionDetails);
// }
// return "account";
// }
//
// @RequestMapping("/backtoAccountSummary")
// public String backtoAccountSummary(HttpServletRequest request, Model model) throws IOException{
// String username = context.getUsername();
// String password = context.getPassword();
// GetAccounts accs = new GetAccounts();
// String accounts = accs.getAccounts(username, password,context);
// if(accounts != null){
// model.addAttribute("accounts", accounts);
// return "accountSummary";
// }else{
// return "errorPage";
// }
// }
}
|
package day18_ReadingUserInput;
import java.util.Scanner;
public class Task73 {
public static void main(String[] args) {
int userInput=0;
int secretNumber=8;
Scanner sc= new Scanner(System.in);
System.out.print("Enter a number: ");
do {
userInput=sc.nextInt();
if(userInput<secretNumber) {
System.out.print("Enter a larger number: ");
}else if(userInput>secretNumber) {
System.out.print("Enter a smaller number:");
}else {
System.out.print("Congrat, You got the number! ");
}
}while(userInput!=secretNumber);
}
}
|
package com.tt.miniapp.shortcut.dialog;
public class SingleSpanView {
private int align = 17;
private TextSpan span;
private boolean visibility = true;
public SingleSpanView() {}
public SingleSpanView(TextSpan paramTextSpan) {
this.span = paramTextSpan;
}
public SingleSpanView(TextSpan paramTextSpan, boolean paramBoolean, int paramInt) {
this.span = paramTextSpan;
this.visibility = paramBoolean;
this.align = paramInt;
}
public int getAlign() {
return this.align;
}
public TextSpan getSpan() {
return this.span;
}
public boolean isVisibility() {
return this.visibility;
}
public void setAlign(int paramInt) {
this.align = paramInt;
}
public void setSpan(TextSpan paramTextSpan) {
this.span = paramTextSpan;
}
public void setVisibility(boolean paramBoolean) {
this.visibility = paramBoolean;
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\shortcut\dialog\SingleSpanView.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package mensaje;
import java.util.ArrayList;
import game.Jugador;
public class MsjPartidaObjetoUsado extends Mensaje {
private static final long serialVersionUID = 1L;
private String objeto;
private String jugadorAct;
private ArrayList<Jugador> jugadores;
public MsjPartidaObjetoUsado(String jugadorAct, String objetoUtilizado, ArrayList<Jugador> jugadores) {
clase = getClass().getSimpleName();
this.jugadorAct = jugadorAct;
this.objeto = objetoUtilizado;
this.jugadores = jugadores;
}
@Override
public void ejecutar() {
}
public String getObjeto() {
return objeto;
}
public String getJugadorAct() {
return jugadorAct;
}
public ArrayList<Jugador> getJugadores() {
return jugadores;
}
public void setObjeto(String objeto) {
this.objeto = objeto;
}
public void setJugadorAct(String jugadorAct) {
this.jugadorAct = jugadorAct;
}
public void setJugadores(ArrayList<Jugador> jugadores) {
this.jugadores = jugadores;
}
}
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.client.eclipse.ui.egit.importwizard;
import java.io.File;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IScopeContext;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.microsoft.tfs.client.eclipse.ui.egit.Messages;
import com.microsoft.tfs.client.common.ui.controls.generic.BaseControl;
import com.microsoft.tfs.client.common.ui.framework.helper.SWTUtil;
import com.microsoft.tfs.client.common.ui.framework.helper.UIHelpers;
import com.microsoft.tfs.client.common.ui.framework.layout.GridDataBuilder;
import com.microsoft.tfs.client.eclipse.ui.egit.importwizard.CrossCollectionRepositoryTable.CrossCollectionRepositoryInfo;
import com.microsoft.tfs.core.clients.versioncontrol.SourceControlCapabilityFlags;
import com.microsoft.tfs.core.config.EnvironmentVariables;
import com.microsoft.tfs.jni.PlatformMiscUtils;
import com.microsoft.tfs.util.Check;
import com.microsoft.tfs.util.StringHelpers;
import com.microsoft.tfs.util.listeners.SingleListenerFacade;
public class CrossCollectionRepositorySelectControl extends BaseControl {
private static final Log log = LogFactory.getLog(CrossCollectionRepositorySelectControl.class);
public static final String REPO_TABLE_ID = "CrossCollectionRepositorySelectControl.repoTable"; //$NON-NLS-1$
private static final String EGIT_PREF_STORE_ID = "org.eclipse.egit.ui"; //$NON-NLS-1$
private static final String DEFAULT_REPOSITORY_DIR_KEY = "default_repository_dir"; //$NON-NLS-1$
private final Text filterBox;
private final Timer filterTimer;
private FilterTask filterTask;
private final CrossCollectionRepositoryTable table;
private final Text parentDirectoryBox;
private final Button browseButton;
private final Text folderNameBox;
private boolean ignoreChanges = false;
private final SingleListenerFacade listeners = new SingleListenerFacade(RepositorySelectionChangedListener.class);
public CrossCollectionRepositorySelectControl(
final Composite parent,
final int style,
final SourceControlCapabilityFlags sourceControlCapabilityFlags) {
super(parent, style);
final GridLayout layout = new GridLayout();
layout.marginWidth = 0;
layout.marginHeight = 0;
layout.horizontalSpacing = getHorizontalSpacing();
layout.verticalSpacing = 0;
setLayout(layout);
// Create timer for filtering the list
filterTimer = new Timer(false);
// Create the filter text box
filterBox = new Text(this, SWT.BORDER);
filterBox.setMessage(Messages.getString("CrossCollectionRepositorySelectControl.FilterHintText")); //$NON-NLS-1$
filterBox.addModifyListener(new ModifyListener() {
@Override
public void modifyText(final ModifyEvent e) {
startTimer();
}
});
GridDataBuilder.newInstance().hGrab().hFill().applyTo(filterBox);
table = new CrossCollectionRepositoryTable(this, SWT.NONE);
table.addSelectionChangedListener(new ISelectionChangedListener() {
@Override
public void selectionChanged(final SelectionChangedEvent event) {
onSelectionChanged(true);
}
});
GridDataBuilder.newInstance().grab().hHint(getVerticalSpacing() * 30).vIndent(
getVerticalSpacing()).fill().applyTo(table);
Label parentDirectoryLabel = SWTUtil.createLabel(
this,
Messages.getString("CrossCollectionRepositorySelectControl.ParentDirectoryLabelText")); //$NON-NLS-1$
GridDataBuilder.newInstance().hGrab().vIndent(getVerticalSpacing()).hFill().applyTo(parentDirectoryLabel);
final Composite container = new Composite(this, SWT.NONE);
final GridLayout layout2 = SWTUtil.gridLayout(container, 2, false, 0, 0);
layout2.marginWidth = 0;
layout2.marginHeight = 0;
layout2.horizontalSpacing = getHorizontalSpacing();
layout2.verticalSpacing = getVerticalSpacing();
container.setLayout(layout2);
parentDirectoryBox = new Text(container, SWT.BORDER);
parentDirectoryBox.setText(getDefaultGitRootFolder());
GridDataBuilder.newInstance().hGrab().hFill().applyTo(parentDirectoryBox);
parentDirectoryBox.addModifyListener(new ModifyListener() {
@Override
public void modifyText(final ModifyEvent e) {
onSelectionChanged(false);
}
});
browseButton = SWTUtil.createButton(
container,
Messages.getString("CrossCollectionRepositorySelectControl.BrowseButtonText")); //$NON-NLS-1$
browseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(final SelectionEvent e) {
parentDirectoryBox.setText(browse(parentDirectoryBox.getText()));
}
});
GridDataBuilder.newInstance().hGrab().hFill().applyTo(container);
Label folderNameLabel = SWTUtil.createLabel(
this,
Messages.getString("CrossCollectionRepositorySelectControl.RepositoryFolderLabelText")); //$NON-NLS-1$
GridDataBuilder.newInstance().hGrab().vIndent(getVerticalSpacing()).hFill().applyTo(folderNameLabel);
folderNameBox = new Text(this, SWT.BORDER);
GridDataBuilder.newInstance().hGrab().hFill().applyTo(folderNameBox);
folderNameBox.addModifyListener(new ModifyListener() {
@Override
public void modifyText(final ModifyEvent e) {
onSelectionChanged(false);
}
});
}
private void onSelectionChanged(boolean updateFolderName) {
if (ignoreChanges) {
return;
}
ignoreChanges = true;
try {
final CrossCollectionRepositoryInfo repo = table.getSelectedRepository();
if (updateFolderName) {
String newFolderName = ""; //$NON-NLS-1$
if (repo != null) {
newFolderName = repo.getRepositoryName();
}
folderNameBox.setText(newFolderName);
}
// Fire event to let listeners know that something changed
((RepositorySelectionChangedListener) listeners.getListener()).onRepositorySelectionChanged(
new RepositorySelectionChangedEvent(repo));
} finally {
ignoreChanges = false;
}
}
private void startTimer() {
// Cancel any existing task
if (filterTask != null) {
filterTask.cancel();
}
// Create a new task
filterTask = new FilterTask();
// Schedule the task
filterTimer.schedule(filterTask, 400);
}
// Call this when the owning control is going away
public void stopTimer() {
// Cancel any existing task
if (filterTask != null) {
filterTask.cancel();
}
}
private class FilterTask extends TimerTask {
@Override
public void run() {
UIHelpers.runOnUIThread(true, new Runnable() {
@Override
public void run() {
table.applyFilter(filterBox.getText());
}
});
}
}
private String getDefaultGitRootFolder() {
final IScopeContext scope = new InstanceScope();
final IEclipsePreferences prefs = scope.getNode(EGIT_PREF_STORE_ID);
Check.notNull(prefs, "Egit preferences store"); //$NON-NLS-1$
String workingDirectory = prefs.get(DEFAULT_REPOSITORY_DIR_KEY, null);
// If the preference is not set then use the home environment variable
if (StringHelpers.isNullOrEmpty(workingDirectory)) {
workingDirectory = PlatformMiscUtils.getInstance().getEnvironmentVariable(EnvironmentVariables.HOME);
// If the home environment variable is not set then use the user
// profile (the same logic as eGit)
if (StringHelpers.isNullOrEmpty(workingDirectory)) {
workingDirectory =
PlatformMiscUtils.getInstance().getEnvironmentVariable(EnvironmentVariables.USER_PROFILE);
}
}
return workingDirectory;
}
private String browse(final String currentDirectory) {
final DirectoryDialog dlg = new DirectoryDialog(this.getShell());
dlg.setFilterPath(currentDirectory);
dlg.setText(Messages.getString("CrossCollectionRepositorySelectControl.BrowseDialogTitle")); //$NON-NLS-1$
dlg.setMessage(Messages.getString("CrossCollectionRepositorySelectControl.BrowseDialogMessage")); //$NON-NLS-1$
final String newDirectory = dlg.open();
return newDirectory != null ? newDirectory : currentDirectory;
}
public CrossCollectionRepositoryInfo getSelectedRepository() {
return table.getSelectedRepository();
}
public void setSelectedRepository(CrossCollectionRepositoryInfo repository) {
table.setSelectedElement(repository);
}
public String getWorkingDirectory() {
final String parentDirectory = parentDirectoryBox.getText();
final String folderName = folderNameBox.getText();
if (!StringHelpers.isNullOrEmpty(parentDirectory) && !StringHelpers.isNullOrEmpty(folderName)) {
final File parent = new File(parentDirectory.trim());
final File workingDirectory = new File(parent, folderName.trim());
return workingDirectory.getPath();
}
return null;
}
public void addListener(final RepositorySelectionChangedListener listener) {
listeners.addListener(listener);
}
public void removeListener(final RepositorySelectionChangedListener listener) {
listeners.removeListener(listener);
}
public void refresh(final List<CrossCollectionRepositoryInfo> repos) {
if (repos == null) {
table.setRepositories(null);
return;
}
table.setRepositories(repos.toArray(new CrossCollectionRepositoryInfo[repos.size()]));
}
public interface RepositorySelectionChangedListener {
public void onRepositorySelectionChanged(RepositorySelectionChangedEvent event);
}
public final class RepositorySelectionChangedEvent {
private final CrossCollectionRepositoryInfo selectedRepository;
private RepositorySelectionChangedEvent(final CrossCollectionRepositoryInfo selectedRepository) {
this.selectedRepository = selectedRepository;
}
public CrossCollectionRepositoryInfo getSelectedRepository() {
return selectedRepository;
}
}
}
|
package com.kunsoftware.util;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.kunsoftware.entity.SysUser;
@SuppressWarnings({"rawtypes"})
public class LoginAnnotationInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
String uri = request.getRequestURI();
String paramStr = getParamStr(request);
SysUser userEntity = (SysUser)session.getAttribute(WebUtil.User_Info);
if(isNotRole(request)) {
return true;
}
if(isLogin(request)) {
if (null != userEntity) {
response.sendRedirect(request.getContextPath() + "/manager/productresource/list");
//request.getRequestDispatcher("/manager/productresource/list").forward(request, response);
return false;
}
return true;
}
if(uri.indexOf("manager") != -1) {
String referer = uri + paramStr;
request.setAttribute("referer", referer);
if (null == userEntity) {
request.getRequestDispatcher("/manager/login?loginMsg=请登录后再操作!").forward(request, response);
return false;
}
}
return true;
}
public String getParamStr(HttpServletRequest request) {
String paramStr = "";
Enumeration enumeration = request.getParameterNames();
String paramName = "";
String paramValue = "";
while(enumeration.hasMoreElements()) {
paramName = (String)enumeration.nextElement();;
paramValue = request.getParameter(paramName);
if(StringUtils.isEmpty(paramStr)) {
paramStr += "?";
} else {
paramStr += "&";
}
paramStr += paramName + "=" + paramValue;
}
return paramStr;
}
public boolean isLogin(HttpServletRequest request) {
String uri = request.getRequestURI();
if(uri.indexOf("manager/login") != -1) {
return true;
}
return false;
}
public boolean isNotRole(HttpServletRequest request) {
String uri = request.getRequestURI();
if(uri.indexOf("manager/cascade") != -1) {
return true;
}
return false;
}
}
|
package com.mindviewinc.chapter18.exercise;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* Open a text file so that you can read the file one line at a time. Read each
* line as a String and place that String object into a LinkedList. Print all of
* the lines in the LinkedList in reverse order.
*
* @author BobbyTang
*
*/
public class Ex07 {
public static void main(String[] args) {
BufferedReader reader = null;
LinkedList<String> list = new LinkedList<>();
try {
reader = new BufferedReader(
new FileReader(
"/Users/BobbyTang/Projects/thinkinginjava/src/main/java/com/mindviewinc/chapter18/exercise/Ex7.java"));
String line = null;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
ListIterator<String> iter = list.listIterator(list.size());
while (iter.hasPrevious()) {
System.out.println(iter.previous());
}
}
}
|
package com.icleveret.recipes.service.impl;
import com.icleveret.recipes.component.SessionHolder;
import com.icleveret.recipes.dao.RoleDao;
import com.icleveret.recipes.model.Role;
import com.icleveret.recipes.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("roleService")
public class RoleServiceImpl implements RoleService {
private RoleDao roleDao;
public RoleDao getRoleDao() {
return roleDao;
}
@Autowired
public void setRoleDao(RoleDao roleDao) {
this.roleDao = roleDao;
}
@Override
public Role add(Role role, SessionHolder.SessionContainer sessionContainer) {
return roleDao.add(role, sessionContainer);
}
@Override
public Role updateName(String name, Integer roleId, SessionHolder.SessionContainer sessionContainer) {
return roleDao.updateName(name, roleId, sessionContainer);
}
@Override
public Role findOne(Integer roleId, SessionHolder.SessionContainer sessionContainer) {
return roleDao.findOne(roleId, sessionContainer);
}
@Override
public Role findByName(String name, SessionHolder.SessionContainer sessionContainer) {
return roleDao.findByName(name, sessionContainer);
}
@Override
public List<Role> findAll(SessionHolder.SessionContainer sessionContainer) {
return roleDao.findAll(sessionContainer);
}
@Override
public void delete(Role role, SessionHolder.SessionContainer sessionContainer) {
roleDao.delete(role, sessionContainer);
}
}
|
/**
*
*/
package alg.code123;
/**
* <a href="http://www.code123.cc/757.html">题目:实现一个算法来删除单链表中间的一个结点,只给出指向那个结点的指针。</a>
* 连头结点指针也不给!!
* @title RemoveItem
*/
public class RemoveItem {
}
|
package com.tencent.mm.plugin.backup.b;
import android.database.Cursor;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.s;
import com.tencent.mm.plugin.backup.a.g;
import com.tencent.mm.plugin.backup.e.h;
import com.tencent.mm.plugin.backup.g.d;
import com.tencent.mm.pointers.PLong;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.storage.ai;
import com.tencent.mm.storage.bd;
import java.util.LinkedList;
public final class b {
public boolean gRY = false;
public interface a {
void y(LinkedList<com.tencent.mm.plugin.backup.a.f.b> linkedList);
}
public final void cancel() {
x.i("MicroMsg.BackupCalculator", "cancel. stack:%s", new Object[]{bi.cjd()});
this.gRY = true;
}
public final void a(a aVar) {
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation start");
long VF = bi.VF();
LinkedList linkedList = new LinkedList();
Cursor b = d.asG().asH().FW().b(s.dAN, g.arb(), "*");
if (b.getCount() == 0) {
if (aVar != null) {
ah.A(new 1(this, aVar, linkedList));
}
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation empty conversation!");
b.close();
return;
}
b.moveToFirst();
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation count[%d]", new Object[]{Integer.valueOf(b.getCount())});
while (!this.gRY) {
ai aiVar = new ai();
aiVar.d(b);
if (!bi.oW(aiVar.field_username)) {
if (d.asG().asH().FT().GT(aiVar.field_username) <= 0) {
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation empty conversation:%s", new Object[]{aiVar.field_username});
} else {
au.HU();
if (ab.Dk(c.FR().Yg(aiVar.field_username).field_verifyFlag)) {
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation Biz conv:%s, msgCount[%d]", new Object[]{aiVar.field_username, Integer.valueOf(r5)});
} else {
com.tencent.mm.plugin.backup.a.f.b bVar = new com.tencent.mm.plugin.backup.a.f.b();
bVar.gRI = aiVar.field_username;
bVar.gRJ = d.asG().asH().FT().GY(aiVar.field_username);
bVar.gRK = d.asG().asH().FT().GZ(aiVar.field_username);
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation add conv:%s, msgCount[%d], firstMsgTime[%d], lastMsgTime[%d]", new Object[]{bVar.gRI, Integer.valueOf(r5), Long.valueOf(bVar.gRJ), Long.valueOf(bVar.gRK)});
linkedList.add(bVar);
}
}
}
if (!b.moveToNext()) {
b.close();
if (!(this.gRY || aVar == null)) {
ah.A(new 2(this, aVar, linkedList));
}
x.i("MicroMsg.BackupCalculator", "calculateChooseConversation finish, use time[%d]", new Object[]{Long.valueOf(bi.bH(VF))});
return;
}
}
x.e("MicroMsg.BackupCalculator", "calculateChooseConversation cancel.");
b.close();
}
public final boolean a(com.tencent.mm.plugin.backup.a.f.b bVar, String str, long j) {
if (bVar == null) {
return false;
}
Cursor GN = d.asG().asH().FT().GN(bVar.gRI);
x.i("MicroMsg.BackupCalculator", "calConversation start convName:%s msgCnt:%d[cu.getCount]", new Object[]{bVar.gRI, Integer.valueOf(GN.getCount())});
if (GN.moveToFirst()) {
PLong pLong = new PLong();
PLong pLong2 = new PLong();
while (!GN.isAfterLast()) {
if (this.gRY) {
x.i("MicroMsg.BackupCalculator", "calConversation cancel, return");
GN.close();
return true;
}
bd bdVar = new bd();
bdVar.d(GN);
try {
h.a(bdVar, true, str, pLong, null, null, false, false, j);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupCalculator", e, "packedMsg", new Object[0]);
}
pLong2.value++;
GN.moveToNext();
}
bVar.gRL = pLong.value;
bVar.gRM = pLong2.value;
x.i("MicroMsg.BackupCalculator", "calConversation convName:%s, convDataSize:%d, convMsgCount:%d", new Object[]{bVar.gRI, Long.valueOf(bVar.gRL), Long.valueOf(bVar.gRM)});
}
GN.close();
return false;
}
}
|
package com.pointburst.jsmusic.model;
import java.io.Serializable;
/**
* Created by FARHAN on 12/27/2014.
*/
public class Media implements Serializable {
private String showHideControlSection;
private String lyrics;
private String title;
private String textColor;
private String duration;
private String mirrorImageOriginalAssetId;
private String mirrorImageEncodeProfileId;
private String artImageUrl;
private String mediaKey;
private String streamUrl ;
public String getStreamUrl() {
//if(StringUtils.isNullOrEmpty(streamUrl))
//streamUrl = "https://pub2-o.secure.miisolutions.net/mi/pointburst/Stoopid Rich Produced by Tone Jonez_audio_128K.mp3";
return streamUrl;
}
public void setStreamUrl(String streamUrl) {
this.streamUrl = streamUrl;
}
public String getShowHideControlSection() {
return showHideControlSection;
}
public void setShowHideControlSection(String showHideControlSection) {
this.showHideControlSection = showHideControlSection;
}
public String getLyrics() {
return lyrics;
}
public void setLyrics(String lyrics) {
this.lyrics = lyrics;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTextColor() {
return textColor;
}
public void setTextColor(String textColor) {
this.textColor = textColor;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getMirrorImageOriginalAssetId() {
return mirrorImageOriginalAssetId;
}
public void setMirrorImageOriginalAssetId(String mirrorImageOriginalAssetId) {
this.mirrorImageOriginalAssetId = mirrorImageOriginalAssetId;
}
public String getMirrorImageEncodeProfileId() {
return mirrorImageEncodeProfileId;
}
public void setMirrorImageEncodeProfileId(String mirrorImageEncodeProfileId) {
this.mirrorImageEncodeProfileId = mirrorImageEncodeProfileId;
}
public String getArtImageUrl() {
return artImageUrl;
}
public void setArtImageUrl(String artImageUrl) {
this.artImageUrl = artImageUrl;
}
public String getMediaKey() {
return mediaKey;
}
public void setMediaKey(String mediaKey) {
this.mediaKey = mediaKey;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Media)) return false;
Media media = (Media) o;
if (mediaKey != null ? !mediaKey.equals(media.mediaKey) : media.mediaKey != null) return false;
return true;
}
}
|
package semana1.curso3.coursera.fragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import semana1.curso3.coursera.R;
import semana1.curso3.coursera.adapter.PetProfileAdapter;
import semana1.curso3.coursera.pojo.Pet;
/**
* A simple {@link Fragment} subclass.
*/
public class PetProfileFragment extends Fragment {
private RecyclerView rv_pet_profile;
private ArrayList<Pet> pets;
private PetProfileAdapter petProfileAdapter;
public PetProfileFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_pet_profile, container, false);
rv_pet_profile = (RecyclerView) view.findViewById(R.id.rv_pet_profile);
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
rv_pet_profile.setLayoutManager(gridLayoutManager);
pets = new ArrayList<Pet>();
pets.add(new Pet(R.drawable.pet_four, 4));
pets.add(new Pet(R.drawable.pet_four, 0));
pets.add(new Pet(R.drawable.pet_four, 2));
pets.add(new Pet(R.drawable.pet_four, 3));
pets.add(new Pet(R.drawable.pet_four, 2));
pets.add(new Pet(R.drawable.pet_four, 6));
pets.add(new Pet(R.drawable.pet_four, 4));
pets.add(new Pet(R.drawable.pet_four, 5));
pets.add(new Pet(R.drawable.pet_four, 3));
pets.add(new Pet(R.drawable.pet_four, 0));
pets.add(new Pet(R.drawable.pet_four, 2));
pets.add(new Pet(R.drawable.pet_four, 3));
pets.add(new Pet(R.drawable.pet_four, 2));
pets.add(new Pet(R.drawable.pet_four, 6));
petProfileAdapter = new PetProfileAdapter(getActivity(), pets);
rv_pet_profile.setAdapter(petProfileAdapter);
return view;
}
}
|
package report;
import base.TestBase;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import java.io.File;
import java.io.IOException;
/**
* Created by Ksenia on 11.12.2016.
*/
public class MyReporter {
private static String result = "";
public static String createScreenshot(String screenshotName) {
TakesScreenshot takesScreenshot = (TakesScreenshot) TestBase.getDriver();
File source = takesScreenshot.getScreenshotAs(OutputType.FILE);
String pathName = System.getProperty("user.dir") + "/ReportResult/" + screenshotName + ".png";
File destination = new File(pathName);
try {
FileUtils.copyFile(source, destination);
} catch (IOException e) {
e.printStackTrace();
}
return pathName;
}
public static String testResult(Boolean bool) {
if (bool == true) {
result = "Test passed";
} else {
result = "Test failed";
}
return result;
}
}
|
class FriendsPairing{
private static int numberOfPairs(int n, int[] dp){
if(dp[n]!=0){
return dp[n];
}
else if(n<=2){
return n;
}
else{
return dp[n] = numberOfPairs(n-1,dp) + (n-1)*numberOfPairs(n-2,dp);
}
}
public static void main(String args[]){
int n = 5;
int[] dp = new int[n+1];
System.out.println(numberOfPairs(n,dp));
}
}
|
package finalProject;
public class Switch extends AbstractActor{
public Switch() {
super();
initialize(2, 2);
}
@Override
public void run() {
assert isComplete();
while(!Simulation.end) {
try {
if(aInputChannels[0].peek()==null ||aInputChannels[1].peek()==null) {
if(!Simulation.end) {
Simulation.pool.getQueue().add(this);
break;
}else {break;}
}
int bool = aInputChannels[0].take();
// this bool has to be either 0 or 1
assert bool == 0 || bool == 1 ;
int data = aInputChannels[1].take();
Fire(bool,data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void Fire(int... is) throws InterruptedException {
int bool = is[0];
int data = is[1];
aOutputChannels[bool].put(data);
}
}
|
package com.zjc.netty.inandoutbound;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* @author : zoujc
* @date : 2021/7/11
* @description :
*/
public class MyByteToLongDecoder extends ByteToMessageDecoder {
/**
*
* @param ctx 上下文
* @param in 入站的ByteBuf
* @param out list集合, 将解码后的数据传给下一个handler处理
* @throws Exception
*/
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
System.out.println("MyByteToLongDecoder 被调用");
//Long 8个字节, 需要判断有8个字节才能读取一个long
if (in.readableBytes() >=8 ) {
out.add(in.readLong());
}
}
}
|
package basic;
public class Exercise20 {
public boolean checkHappyNum(int num) {
int sum = 0;
do {
int mod = num % 10;
sum += mod * mod;
num /= 10;
if (num == 0) {
if (sum / 10 == 0) break;
num = sum;
sum = 0;
}
} while (num != 0);
return sum == 1 ? true : false;
}
}
|
package com.storytime.client.changevieweventhandlers;
import com.google.gwt.event.shared.EventHandler;
public interface LoginExistingUserLocalEventHandler extends EventHandler {
public void onLoginExistingUser();
}
|
package Interfacesgui;
import Controller.CategorieDaoImpl;
import Controller.ClientDaoImpl;
import Controller.ProduitDaoImplL;
import dao.ClientDAO;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import model.Categorie;
import model.Client;
import model.Produit;
import java.util.List;
public class FormClient {
private BorderPane root=new BorderPane();
TableView<Client> tableclient=new TableView<>();
ObservableList<Client> observableTable= FXCollections.observableArrayList();
GridPane pane = new GridPane();
ClientDAO pdao=new ClientDaoImpl();
List<Client> clients=pdao.findAll();
Button addbtn=new Button();
Button editbtn=new Button();
Button deletebtn=new Button();
Button clear=new Button();
Label nomlabel = new Label("nom");
TextField nominput = new TextField();
Label prenomlabel = new Label("prenom");
TextField prenominput = new TextField();
Label telephonelabel = new Label("telephone");
TextField telephoneinput = new TextField();
Label citylabel = new Label("ville");
TextField cityinput = new TextField();
private void initelements(){
Label title=new Label("GESTION DE CLIENT");
title.setStyle(" -fx-padding:7px;");
title.setStyle("-fx-font-size:25px;");
title.setTextFill(Color.WHITE);
HBox titletop=new HBox();
titletop.setAlignment(Pos.CENTER);
titletop.getChildren().add(title);
titletop.setPadding(new Insets(20));
titletop.setStyle("-fx-background-color: black;");
addbtn.setStyle("-fx-background-color: #69779b;-fx-min-width: 100;-fx-min-height: 50;");
addbtn.setGraphic(new Label("AJOUTER"));
addbtn.getGraphic().setStyle("-fx-text-fill: #f0ece2;");
deletebtn.setStyle("-fx-background-color: #69779b;-fx-min-width: 100;-fx-min-height: 50;");
deletebtn.setGraphic(new Label("SUPPRIMER"));
deletebtn.getGraphic().setStyle("-fx-text-fill: #f0ece2;");
editbtn.setStyle("-fx-background-color: #69779b;-fx-min-width: 100;-fx-min-height: 50;");
editbtn.setGraphic(new Label("MODIFIER"));
editbtn.getGraphic().setStyle("-fx-text-fill: #f0ece2;");
clear.setStyle("-fx-background-color: #69779b;-fx-min-width: 100;-fx-min-height: 50;");
clear.setGraphic(new Label("INIT"));
clear.getGraphic().setStyle("-fx-text-fill: #f0ece2;");
pane.setPadding(new Insets(0,20,20,20));
pane.setHgap(15);
pane.setVgap(15);
pane.add(nomlabel, 0, 1);
pane.add(prenomlabel, 0, 2);
pane.add(telephonelabel, 0, 3);
pane.add(citylabel, 0, 4);
pane.add(nominput, 1, 1);
pane.add(prenominput, 1, 2);
pane.add(telephoneinput, 1, 3);
pane.add(cityinput, 1, 4);
pane.add(addbtn,0,5);
pane.add(editbtn,1,5);
pane.add(deletebtn,0,6);
pane.add(clear,1,6);
initTableProduct();
VBox view=new VBox();
TextField search= new TextField();
search.setStyle("-fx-border-color: #69779b");
VBox.setMargin(view,new Insets(60,0,0,0));
VBox.setMargin(search,new Insets(10,0,5,0));
view.getChildren().add(search);
view.getChildren().add(tableclient);
HBox footer=new HBox();
Label footertext=new Label("Created By YOUSSEF AMZIL");
footertext.setStyle(" -fx-padding:3px;");
footertext.setStyle("-fx-font-size:12px;");
footertext.setTextFill(Color.WHITE);
footer.setAlignment(Pos.CENTER);
footer.getChildren().add(footertext);
footer.setPadding(new Insets(15));
footer.setStyle("-fx-background-color: black;");
root.setTop(titletop);
root.setCenter(view);
root.setRight(pane);
root.setBottom(footer);
//on add button
addbtn.setOnAction(event -> {
Client c=new Client(pdao.getLastId(),nominput.getText(),prenominput.getText(),telephoneinput.getText(),cityinput.getText());
pdao.create(c);
this.observableTable.add(c);
});
deletebtn.setOnAction(event -> {
Client t=tableclient.getSelectionModel().getSelectedItem();
try {
pdao.delete(t);
this.observableTable.remove(t);
}catch (Exception e) {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setContentText(e.getMessage());
alert.setTitle("impossible !!!");
alert.show();
}
});
editbtn.setOnAction(event -> {
Client t=tableclient.getSelectionModel().getSelectedItem();
t.setNom(nominput.getText());
t.setPrenom(prenominput.getText());
t.setTelephone(telephoneinput.getText());
t.setCity(cityinput.getText());
pdao.update(t);
this.observableTable.set(this.observableTable.indexOf(t),t);
});
//tableView selection
tableclient.setOnMouseClicked(event -> {
try{
Client t=tableclient.getSelectionModel().getSelectedItem();
this.nominput.setText(t.getNom());
this.prenominput.setText(t.getPrenom());
this.telephoneinput.setText(t.getTelephone());
this.cityinput.setText(t.getCity());
}catch(Exception e){
e.getMessage();
}
});
search.setOnKeyPressed(event -> {
if (!search.getText().isEmpty()) {
ObservableList<Client> searchlist = FXCollections.observableArrayList();
for (Client pr : clients) {
if (pr.getPrenom().contains(search.getText()) || pr.getNom().contains(search.getText()) || pr.getTelephone().contains(search.getText()))
searchlist.add(pr);
}
this.observableTable.setAll(searchlist);
}
});
clear.setOnMouseClicked(events->{
this.nominput.setText("");
this.prenominput.setText("");
this.telephoneinput.setText("");
this.cityinput.setText("");
});
}
private void initTableProduct(){
tableclient.setStyle("-fx-border-color: #69779b");
TableColumn<Client, Integer> clientIdColon=new TableColumn<>("Id");
clientIdColon.setCellValueFactory(new PropertyValueFactory<>("id"));
clientIdColon.setPrefWidth(50);
TableColumn<Client, String> nomColon=new TableColumn<>("nom");
nomColon.setCellValueFactory(new PropertyValueFactory<>("nom"));
nomColon.setPrefWidth(100);
TableColumn<Client, String> prenomColon=new TableColumn<>("Prenom");
prenomColon.setCellValueFactory(new PropertyValueFactory<>("prenom"));
prenomColon.setPrefWidth(80);
TableColumn<Client, String> telephoneColon=new TableColumn<>("Telephone");
telephoneColon.setCellValueFactory(new PropertyValueFactory<>("telephone"));
telephoneColon.setPrefWidth(80);
TableColumn<Client, String> cityColon=new TableColumn<>("City");
cityColon.setCellValueFactory(new PropertyValueFactory<>("city"));
cityColon.setPrefWidth(80);
tableclient.getColumns().addAll(clientIdColon,nomColon,prenomColon,telephoneColon,cityColon);
observableTable.setAll(clients);
tableclient.setItems(observableTable);
}
public BorderPane getAll(){
initelements();
return this.root;
}
}
|
package com.example.demo.entities;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
public class Publication implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String type;
private String titre;
private String lien;
@Temporal(TemporalType.DATE)
private Date date;
private String source;
public Publication() {
super();
}
public Publication(String type, String titre, String lien, Date date, String source) {
super();
this.type = type;
this.titre = titre;
this.lien = lien;
this.date = date;
this.source = source;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getLien() {
return lien;
}
public void setLien(String lien) {
this.lien = lien;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}
|
package com.tencent.mm.protocal.c;
import f.a.a.b;
import f.a.a.c.a;
import java.util.LinkedList;
public final class adh extends bhp {
public int rHB;
public LinkedList<ts> rHC = new LinkedList();
public th rHD;
public int rHE;
public LinkedList<th> rHF = new LinkedList();
public int rHG;
public LinkedList<tl> rHH = new LinkedList();
public int rHI;
public LinkedList<tj> rHJ = new LinkedList();
public int rHK;
public int rHL;
public int rHM;
public LinkedList<tj> rHN = new LinkedList();
public bhy rcT;
protected final int a(int i, Object... objArr) {
int fS;
byte[] bArr;
if (i == 0) {
a aVar = (a) objArr[0];
if (this.six == null) {
throw new b("Not all required fields were included: BaseResponse");
} else if (this.rcT == null) {
throw new b("Not all required fields were included: ReqBuf");
} else {
if (this.six != null) {
aVar.fV(1, this.six.boi());
this.six.a(aVar);
}
if (this.rcT != null) {
aVar.fV(2, this.rcT.boi());
this.rcT.a(aVar);
}
aVar.fT(3, this.rHB);
aVar.d(4, 8, this.rHC);
if (this.rHD != null) {
aVar.fV(5, this.rHD.boi());
this.rHD.a(aVar);
}
aVar.fT(6, this.rHE);
aVar.d(7, 8, this.rHF);
aVar.fT(8, this.rHG);
aVar.d(9, 8, this.rHH);
aVar.fT(10, this.rHI);
aVar.d(11, 8, this.rHJ);
aVar.fT(12, this.rHK);
aVar.fT(13, this.rHL);
aVar.fT(14, this.rHM);
aVar.d(15, 8, this.rHN);
return 0;
}
} else if (i == 1) {
if (this.six != null) {
fS = f.a.a.a.fS(1, this.six.boi()) + 0;
} else {
fS = 0;
}
if (this.rcT != null) {
fS += f.a.a.a.fS(2, this.rcT.boi());
}
fS = (fS + f.a.a.a.fQ(3, this.rHB)) + f.a.a.a.c(4, 8, this.rHC);
if (this.rHD != null) {
fS += f.a.a.a.fS(5, this.rHD.boi());
}
return (((((((((fS + f.a.a.a.fQ(6, this.rHE)) + f.a.a.a.c(7, 8, this.rHF)) + f.a.a.a.fQ(8, this.rHG)) + f.a.a.a.c(9, 8, this.rHH)) + f.a.a.a.fQ(10, this.rHI)) + f.a.a.a.c(11, 8, this.rHJ)) + f.a.a.a.fQ(12, this.rHK)) + f.a.a.a.fQ(13, this.rHL)) + f.a.a.a.fQ(14, this.rHM)) + f.a.a.a.c(15, 8, this.rHN);
} else if (i == 2) {
bArr = (byte[]) objArr[0];
this.rHC.clear();
this.rHF.clear();
this.rHH.clear();
this.rHJ.clear();
this.rHN.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (fS = bhp.a(aVar2); fS > 0; fS = bhp.a(aVar2)) {
if (!super.a(aVar2, this, fS)) {
aVar2.cJS();
}
}
if (this.six == null) {
throw new b("Not all required fields were included: BaseResponse");
} else if (this.rcT != null) {
return 0;
} else {
throw new b("Not all required fields were included: ReqBuf");
}
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
adh adh = (adh) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
f.a.a.a.a aVar4;
boolean z;
th thVar;
tj tjVar;
switch (intValue) {
case 1:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
fl flVar = new fl();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = flVar.a(aVar4, flVar, bhp.a(aVar4))) {
}
adh.six = flVar;
}
return 0;
case 2:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, bhp.a(aVar4))) {
}
adh.rcT = bhy;
}
return 0;
case 3:
adh.rHB = aVar3.vHC.rY();
return 0;
case 4:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
ts tsVar = new ts();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = tsVar.a(aVar4, tsVar, bhp.a(aVar4))) {
}
adh.rHC.add(tsVar);
}
return 0;
case 5:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
thVar = new th();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = thVar.a(aVar4, thVar, bhp.a(aVar4))) {
}
adh.rHD = thVar;
}
return 0;
case 6:
adh.rHE = aVar3.vHC.rY();
return 0;
case 7:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
thVar = new th();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = thVar.a(aVar4, thVar, bhp.a(aVar4))) {
}
adh.rHF.add(thVar);
}
return 0;
case 8:
adh.rHG = aVar3.vHC.rY();
return 0;
case 9:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
tl tlVar = new tl();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = tlVar.a(aVar4, tlVar, bhp.a(aVar4))) {
}
adh.rHH.add(tlVar);
}
return 0;
case 10:
adh.rHI = aVar3.vHC.rY();
return 0;
case 11:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
tjVar = new tj();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = tjVar.a(aVar4, tjVar, bhp.a(aVar4))) {
}
adh.rHJ.add(tjVar);
}
return 0;
case 12:
adh.rHK = aVar3.vHC.rY();
return 0;
case 13:
adh.rHL = aVar3.vHC.rY();
return 0;
case 14:
adh.rHM = aVar3.vHC.rY();
return 0;
case 15:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
tjVar = new tj();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = tjVar.a(aVar4, tjVar, bhp.a(aVar4))) {
}
adh.rHN.add(tjVar);
}
return 0;
default:
return -1;
}
}
}
}
|
package org.zerock.service;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Service;
import org.zerock.domain.MerchanVO;
import org.zerock.mapper.MerchanMapper;
import java.util.List;
@Service
@Log4j
@AllArgsConstructor
public class MerchanServiceImpl implements MerchanService{
MerchanMapper mapper;
@Override
public void register(MerchanVO vo) {
log.info("registering Merchan...");
mapper.insert(vo);
}
@Override
public MerchanVO get(int merchanOid) {
log.info("getting Merchan...");
return mapper.read(merchanOid);
}
@Override
public boolean remove(int merchanOid) {
log.info("deleting Merchan...");
if(mapper.delete(merchanOid) == 1){
return true;
}else{
return false;
}
}
@Override
public boolean modify(MerchanVO vo) {
log.info("modifying Merchan...");
if(mapper.update(vo) == 1){
return true;
}else{
return false;
}
}
@Override
public boolean modifyUser(int merchanOid, String userId) {
if(mapper.updateUser(merchanOid,userId) == 1){
return true;
}else{
return false;
}
}
@Override
public boolean modifyBrand(int merchanOid, int brandOid) {
if(mapper.updateBrand(merchanOid,brandOid) == 1){
return true;
}else{
return false;
}
}
@Override
public List<MerchanVO> getList() {
log.info("listing Merchan...");
return mapper.getList();
}
@Override
public List<MerchanVO> getNewList() {
log.info("listing Newest Merchan...");
return mapper.getNewList();
}
@Override
public List<MerchanVO> getLogoList() {
log.info("listing Logo Merchan...");
return mapper.getLogoList();
}
@Override
public List<MerchanVO> getNotLogoList() {
log.info("listing NotLogo Merchan...");
return mapper.getNotLogoList();
}
@Override
public List<MerchanVO> getListAccordingToBrandOid(int brandOid) {
return mapper.getListAccordingToBrandOid(brandOid);
}
}
|
package com.mochasoft.fk.configuration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mochasoft.fk.configuration.entity.Configuration;
import com.mochasoft.fk.configuration.service.IConfigurationService;
public class ConfigurationInfo {
private static final Logger log = LoggerFactory.getLogger(ConfigurationInfo.class);
private static ConfigurationInfo info = null;
private IConfigurationService service;
private Map<String, Object> config = new HashMap<String, Object>();
private ConfigurationInfo(){
}
public void setService(IConfigurationService service) {
this.service = service;
}
/**
* 单例获取ConfigurationInfo对象
*
* @return
*/
public static ConfigurationInfo getInstance(){
if(info == null){
info = new ConfigurationInfo();
}
return info;
}
/**
* 根据key获取value值
*
* @param key
* @return
*/
public String getValue(String key){
Configuration configuration = null;
@SuppressWarnings("unchecked")
List<Configuration> list = (List<Configuration>)config.get("dbconfig");
if(list != null && list.size() != 0){
Iterator<Configuration> iterator = list.iterator();
while(iterator.hasNext()){
configuration = iterator.next();
if(key.equals(configuration.getKey())){
return configuration.getValue();
}
}
}
return "";
}
/**
* 全部重新获取
*/
public void reloadAll(){
config.clear();
//getAllConfigInfo();
}
/**
* 获取键值对放入map中
* 之所以用map,是考虑有可能从properties文件中读入键值对时,可复用此方法
*/
private void getAllConfigInfo(){
service.flushCacheAll();
List<Configuration> list = service.selectAll();
config.put("dbconfig", list);
log.info(list.size()+"");
}
}
|
package com.example.nannybot;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.provider.Settings;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
public class StreamVideo extends AppCompatActivity {
WebView webStream;
//
private TextView textViewStatus;
private EditText editTextGainFactor;
private Button btnStartSendVoice,btnStopSendVoice;
private boolean isActiveThread = false;
ThreadAudio tAudio;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_video);
//code connection bluetooth
//
//BluetoothConnect.connect("16:07:54:CC:81:3A");
//
//code video streaming
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Supraveghere");
btnStartSendVoice = findViewById(R.id.start);
btnStopSendVoice = findViewById(R.id.stop);
webStream = (WebView) findViewById(R.id.webStream);
webStream.loadUrl("http://192.168.43.6/cam.mjpeg");
//code send vocal message
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PackageManager.PERMISSION_GRANTED);
textViewStatus = findViewById(R.id.textViewStatus);
btnStartSendVoice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { buttonStart();}
});
btnStopSendVoice.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { buttonStop();}
});
//-------------------------------------------------------
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home){
onBackPressed();
webStream.destroy();
//BluetoothConnect.disconnect();
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK))
{
//onBackPressed();
webStream.destroy();
//BluetoothConnect.disconnect();
}
return super.onKeyDown(keyCode, event);
}
public void buttonStart(){
tAudio = new ThreadAudio();
textViewStatus.setText("Activ");
//System.out.println(Thread.currentThread());
}
public void buttonStop(){
tAudio.stop();
textViewStatus.setText("Inactiv");
}
}
|
package ua.kiev.doctorvera;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import android.content.Context;
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.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
/*
* <p>Adapter for ListView with checkbox on items</p>
* <p>It also handles click on item and checking checkbox</p>
* @author Volodymyr Bodnar
* @version %I%, %G%
* @since 1.0
*/
public class CheckboxListAdapter extends ArrayAdapter<Map<String, Object>> implements View.OnClickListener, AdapterView.OnItemClickListener {
private List<Map<String, Object>> data;
//private final String LOG_TAG = "myLogs CheckboxListAdapter";
private Context context;
private final String LOG_TAG = "myLogs CheckboxListAdapter";
private int resourceItem;
//Data for creating ListView Adapter
// Names of Map keys
private final String SMS_TEXT = "text";
private final String SMS_DATE = "date";
private final String SMS_ID = "id";
private final String SMS_PHONE = "phone";
private final String SMS_STATE = "state";
public CheckboxListAdapter(Context context, List<Map<String, Object>> data, int resource) {
super(context, resource, data);
this.context = context;
this.resourceItem = resource;
getData();
Log.d(LOG_TAG, "Adapter Created for " + context.getResources().getResourceEntryName(resource));
}
@Override
public int getCount() {
return data.size();
}
@Override
public Map<String, Object> getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
/*
* (non-Javadoc)
* @see android.widget.SimpleAdapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
// We only create the view if its needed
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(resourceItem, viewGroup, false);
}
//Depending on which fragment is calling this
if (resourceItem == R.layout.archive_item){
//Searching for elements
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);
ImageView iv = (ImageView) view.findViewById(R.id.status_icon);
TextView phoneNumber = (TextView) view.findViewById(R.id.phone_number);
TextView dateCreated = (TextView) view.findViewById(R.id.date_created);
TextView text = (TextView) view.findViewById(R.id.text);
//Setting data to elements
phoneNumber.setText((String)data.get(position).get(SMS_PHONE));
dateCreated.setText((String)data.get(position).get(SMS_DATE));
text.setText((String)data.get(position).get(SMS_TEXT));
// Setting icon depending on the SMS state
if (iv != null)
switch ((Byte) data.get(position).get("state")) {
case 3:
iv.setImageResource(R.drawable.status_icon_sent);
break;
case 4:
iv.setImageResource(R.drawable.status_icon_delivered);
break;
case 5:
iv.setImageResource(R.drawable.status_icon_derror);
break;
case 6:
iv.setImageResource(R.drawable.status_icon_error);
break;
}
// Set the click listener for the checkbox
checkBox.setChecked(false);
checkBox.setOnClickListener(this);
}else{
//Searching for elements
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkBox);
TextView dateCreated = (TextView) view.findViewById(R.id.date_created);
TextView text = (TextView) view.findViewById(R.id.text);
//Setting data to elements
dateCreated.setText((String)data.get(position).get(SMS_DATE));
text.setText((String)data.get(position).get(SMS_TEXT));
// Set the click listener for the checkbox
// Set the click listener for the checkbox
checkBox.setChecked(false);
checkBox.setOnClickListener(this);
}
return view;
}
/*
* Fires when Item is clicked. Method fills phone field and text field of the NewSMSTab with data from the clicked SMS
* (non-Javadoc)
* @see android.widget.AdapterView.OnItemClickListener#onItemClick(android.widget.AdapterView, android.view.View, int, long)
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SMS_DAO smsDao = new SMS_DAO(context);
int smsId = (Integer) data.get(position).get("id");
//Retrieving NewSMSTab & its fields
Fragment newSMSTab = ((MainActivity) context).getSupportFragmentManager().getFragments().get(0);
AutoCompleteTextView phone = (AutoCompleteTextView) newSMSTab.getView().findViewById(R.id.phoneNumberField);
EditText text = (EditText) newSMSTab.getView().findViewById(R.id.smsTextField);
//Filling fields
text.setText(smsDao.getSMS(smsId).getText());
if (((MainActivity) context).getActionBar().getSelectedTab().getPosition() == 0)
phone.setText(smsDao.getSMS(smsId).getPhoneNumber());
((MainActivity) context).getSupportActionBar().setSelectedNavigationItem(1);
}
@Override
/** Will be called when a checkbox has been clicked. */
public void onClick(View view) {
//We are looking for position of the clicked checkbox
CheckBox cb = (CheckBox) view;
ListView lvMain = (ListView) cb.getParent().getParent();
int position = lvMain.getPositionForView(cb);
//Marking List item as checked or not
if (cb.isChecked()) data.get(position).put("checked", true);
else data.get(position).put("checked", false);
}
/*
* This method updates the state of sent SMS, retrieves SMS data & pack it to the structure for adapter(ArrayList<Map<String, Object>>)
* @return ArrayList<Map<String, Object>> SMS data for this tab
*/
public void getData() {
final ArrayList<Map<String, String>> contactData = Utils.getContactData((MainActivity)context); //Get device contacts
//Updating SMS state
Log.d(LOG_TAG,"Update SMS state");
try {
new SMSGatewayConnect(context).execute("updateSMSState").get();
} catch (InterruptedException e) {
Log.e(LOG_TAG, e.getMessage());
} catch (ExecutionException e) {
Log.e(LOG_TAG, e.getMessage());
}
// Initializing DB Object
SMS_DAO smsDao = new SMS_DAO(context);
// Find all SMS needed for this tab
List<SMS> smsList = new ArrayList<SMS>() ;
if (resourceItem == R.layout.archive_item){
smsList.addAll(smsDao.getAllSMS((byte) 3));
smsList.addAll(smsDao.getAllSMS((byte) 4));
smsList.addAll(smsDao.getAllSMS((byte) 5));
smsList.addAll(smsDao.getAllSMS((byte) 6));
}else{
smsList.addAll(smsDao.getAllSMS((byte) 2));
}
// I want SMS to be sorted by date they were sent
Collections.sort(smsList, new Comparator<SMS>(){
@Override
public int compare(SMS o1, SMS o2) {
return (o1.getDateSent().getTime()>o2.getDateSent().getTime() ? -1 : (o1.getDateSent().getTime()==o2.getDateSent().getTime() ? 0 : 1));
}
});
// Packing data for adapter
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(smsList.size());
Map<String, Object> m;
for (int i = 0; i < smsList.size(); i++) {
m = new HashMap<String, Object>();
m.put(SMS_ID, smsList.get(i).getId());
m.put(SMS_TEXT, smsList.get(i).getText());
m.put(SMS_STATE, smsList.get(i).getState());
//I want SMS_PHONE to be formatted like in phonebook in the case that it is already in contacts
for (Map<String, String> contact : contactData) {
contact.put("Phone", Utils.formatPhoneNumber(contact.get("Phone")));//just formatting phone, so it could be compared
if (contact.containsValue(smsList.get(i).getPhoneNumber()))
m.put(SMS_PHONE, contact.get("Name")); //in the case phone is already in contacts retrieving the Name of the person
else
m.put(SMS_PHONE, smsList.get(i).getPhoneNumber()); //else put as is
}
//Different Date formatting depending on the Tab
if (resourceItem == R.layout.archive_item)
m.put(SMS_DATE, Utils.formatDateTwoLines(smsList.get(i).getDateSent(),context.getResources().getConfiguration().locale));
else
m.put(SMS_DATE, Utils.formatDateOneLine(smsList.get(i).getDateSent(),context.getResources().getConfiguration().locale));
data.add(m);
}
this.data=data;
Log.d(LOG_TAG, "Data changed!");
}
}
|
package com.tencent.tencentmap.mapsdk.a;
import java.util.HashMap;
import java.util.Map;
public final class cm extends cx implements Cloneable {
private static Map<Integer, byte[]> b;
public Map<Integer, byte[]> a = null;
public final void a(cw cwVar) {
cwVar.a(this.a, 0);
}
public final void a(cv cvVar) {
if (b == null) {
b = new HashMap();
Integer valueOf = Integer.valueOf(0);
byte[] bArr = new byte[1];
bArr[0] = (byte) 0;
b.put(valueOf, bArr);
}
this.a = (Map) cvVar.a(b, 0, true);
}
}
|
package chap06.sec13.exam02_constructor_access_package2;
import chap06.sec13.exam02_constructor_access_package1.A;
public class C {
//필드
A a1 = new A(true);
// A a2 = new A(1); // x, default는 다른 패키지에서 접근할 수 없다.
// A a3 = new A("a");
}
|
package org.tinyspring.beans.factory.config;
/**
* @author tangyingqi
* @date 2018/7/28
*/
public interface BeanPostProcessor {
Object beforeInitialization(Object bean,String beanName);
Object afterInitialization(Object bean,String beanName);
}
|
/*
* 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 calculadorarmi;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import Calculadora.*;
import java.rmi.AlreadyBoundException;
/**
*
* @author Alexis
*/
public class Servidor implements Calculadora{
public Servidor() {}
public int suma(int x, int y) {
System.out.println("Corriendo en el servidor");
return x+y;
}
public int resta(int x, int y){
System.out.println("Corriendo en el servidor");
return x-y;
}
public int mult(int x, int y){
System.out.println("Corriendo en el servidor");
return x*y;
}
public double division(double a, double b){
System.out.println("Corriendo en el servidor");
return a/b;
}
public static void main(String args[]) {
try {
//puerto default del rmiregistry
java.rmi.registry.LocateRegistry.createRegistry(1099);
System.out.println("RMI registro listo.");
} catch (RemoteException e) {
System.out.println("Excepcion RMI del registry:");
}//catch
try {
System.setProperty("java.rmi.server.codebase", "file:/c:/Temp/Calculadora/");
Servidor obj = new Servidor();
Calculadora stub = (Calculadora) UnicastRemoteObject.exportObject(obj, 0);
// Ligamos el objeto remoto en el registro
Registry registry = LocateRegistry.getRegistry();
registry.bind("Calculadora", stub);
System.err.println("Servidor listo...");
} catch (AlreadyBoundException | RemoteException e) {
System.err.println("Excepción del servidor: " + e.toString());
}
}
}
|
package pages;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "BOOKS") //BOOKS is name of table
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id //primary key
private int id;
private String name;
private String author;
private String subject;
private double price;
public Book() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", author=" + author + ", subject=" + subject + ", price=" + price
+ "]";
}
}
|
package com.shopify.order.popup;
import java.util.Date;
import lombok.Data;
@Data
public class LocalDeliveryData {
private int idx;
private String id;
private String code;
private String zone;
private int weight;
private int price;
private String startDate;
private String endDate;
private String useYn;
private String codeKname;
private String codeEname;
private String codeName;
private String regDate;
private String locale;
private String courierName;
private String courierId;
private String nowDate;
}
|
package com.tencent.mm.api;
import com.tencent.mm.pluginsdk.ui.chat.f;
public class n implements f {
public a bxe;
}
|
package no.uib.info331.util;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.support.design.widget.BaseTransientBottomBar;
import android.support.v4.content.ContextCompat;
import android.view.View;
import no.uib.info331.R;
/**
* Created by moled on 03.10.2017.
*/
public class Animations {
/**
* Gets the system-defined animation times. Recommended to use, as these are adjusted accordingly
* if systemwide animations are changed. I.e. in developer options.
*
*/
public int getShortAnimTime(Context context) {
return context.getResources().getInteger(android.R.integer.config_shortAnimTime);
}
public int getMediumAnimTime(Context context) {
return context.getResources().getInteger(android.R.integer.config_mediumAnimTime);
}
public int getLongAnimTime(Context context) {
return context.getResources().getInteger(android.R.integer.config_longAnimTime);
}
/**********************************************************************************************/
/**
* Fades in a view. Sets the view to 0 alpha ad fades gradually in. Remember to set the alpha
* to 0 in XML, or else the view will "blink" before fading
* @param view view to fade
* @param startDelay how long it should take from init the method to teh animation to begin
* @param duration the duration of the anim
*/
public void fadeInView(View view, int startDelay, int duration) {
view.setAlpha(0);
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(view, "alpha", 0, 1f);
fadeIn.setStartDelay(startDelay);
fadeIn.setDuration(duration);
fadeIn.start();
}
/**
* Fades out a view. Starts from 1 alpha and gradually fades down to 0 alpha. Remember to set
* view's alpha to zero after fade, or else it will pop back up again, as this is opnly the animation
* and doesnt set the alpha afterwards.
* @param view view to fade
* @param startDelay how long it should take from init the method to teh animation to begin
* @param duration the duration of the anim
*/
public void fadeOutView(View view, int startDelay, int duration) {
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(view, "alpha", 1f, 0);
fadeIn.setStartDelay(startDelay);
fadeIn.setDuration(duration);
fadeIn.start();
}
/**
* Moves a view along the Y axis (vertically). Moves relative to the view's position, meaning that 0 is the view's start position.
*
* @param VIEW the view to move
* @param startDelay how long it should take from init the method to teh animation to begin
* @param duration the duration of the anim
* @param offset Relative pixel (not dpi) distance to where ti should move. Positive numbers is downwards, negative is upwards.
* @param goneOnAnimEnd whether the view's visibility shold be set to gone or not. TRUE = gone, False = still exists
* Note: Visibility = GONE affects the View's space around it, meaning that setting it to gone, it won't take up space anymore.
* It's also still instantiated, meaning that you can set the property to "VISIBLIE" and it'll pop up back again.
*/
public void moveViewToTranslationY(final View VIEW, int startDelay, int duration, int offset, final boolean goneOnAnimEnd) {
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(VIEW, "TranslationY", offset);
fadeIn.setStartDelay(startDelay);
fadeIn.setDuration(duration);
fadeIn.start();
fadeIn.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
if(!goneOnAnimEnd){
VIEW.setVisibility(View.VISIBLE);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if(goneOnAnimEnd){
VIEW.setVisibility(View.GONE);
}
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
}
/**
* Fades a view's background color from one specified color to another specified color
* @param view the voew to change its color
* @param duration duration of the fading
* @param fromColor the start color, usually this would be the current color of the view.
* I.e. if the view's bg color is white, the color here should be white.
* @param toColor the color the view should change in to.
*/
public void fadeBackgroundFromColorToColor(View view, int duration, int fromColor, int toColor){
ColorDrawable[] color2 = {new ColorDrawable(fromColor), new ColorDrawable(toColor)};
TransitionDrawable trans = new TransitionDrawable(color2);
//This will work also on old devices. The latest API says you have to use setBackground instead.
view.setBackground(trans);
trans.startTransition(duration);
}
}
|
package handlers;
import model.Key;
public interface DoorChain
{
void setNextDoor(DoorChain nextDoor);
void tryDoor(Key key);
}
|
package lexer;
public class Num extends Token{
public final int value;
public Num(int v){super(Tag.NUM);value=v;}
public String toString(){return ""+value;}
}
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a;
int b = 0;
for (int i = 1; i <= 5; i++){
a = scan.nextInt();
if (a % 2 == 0){
b += 1;
}
} System.out.println(b + " valores pares");
}
}
|
package jp.satoshun.chreco.tests;
import android.app.Activity;
import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
import android.test.AndroidTestCase;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.synd.SyndEntry;
import java.util.List;
import jp.satoshun.chreco.MainActivity;
import jp.satoshun.chreco.libs.User;
public class FeedListAdapterTest extends ActivityInstrumentationTestCase2<MainActivity> {
private Activity context;
public FeedListAdapterTest(Class<MainActivity> activityClass) {
super(activityClass);
}
public void setUp() {
context = getActivity();
}
public void testUserId() throws Exception {
}
private List<SyndEntry> getEntryList() {
return null;
}
}
|
/*Copyright [2018] [Jurgen Emanuels]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.*/
package za.co.samtakie.samtakieradio.utilities;
import android.net.Uri;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;
import javax.net.ssl.HttpsURLConnection;
/**
* Created by Jurgen Emanuels on 2017/04/2018
* This class has the functionality to download the Json data from the web.
*/
public class NetworkUtils {
private NetworkUtils(){}
// Set the url for downloading the data and assign it to constant DYNAMIC_RADIO_URL
private static final String DYNAMIC_RADIO_URL = "https://www.samtakie.co.za/samtakie_json.php";
/**
* Build the url string and return the full parsed url string
* @return The URL to query the samtakie online radio server
*/
public static URL buildUrl(){
Uri builtUri;
builtUri = Uri.parse(DYNAMIC_RADIO_URL).buildUpon().build();
URL url = null;
try{
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return url;
}
public static String getResponseFromHttpUrl(URL url) throws IOException{
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
try{
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if(hasInput){
return scanner.next();
} else {
return null;
}
} finally {
urlConnection.disconnect();
}
}
}
|
package net.crunchdroid.dao;
import net.crunchdroid.model.ProduitFacture;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProduitFactureDao extends JpaRepository<ProduitFacture, Long> {
}
|
package com.eres.waiter.waiter.fragment.viewpager_fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.eres.waiter.waiter.R;
import com.eres.waiter.waiter.adapters.AdapterITable;
import com.eres.waiter.waiter.app.App;
import com.eres.waiter.waiter.model.IAmTables;
import com.eres.waiter.waiter.model.events.EventIAmTableChange;
import com.eres.waiter.waiter.model.singelton.DataSingelton;
import com.eres.waiter.waiter.model.test.NotificationEventAlarm;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
public class FragmentITable extends Fragment {
private RecyclerView recyclerView;
private ArrayList<IAmTables> iAmTabless;
private String TAG = "MY_LOG";
private AdapterITable adapterITable;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.i_table_layout, container, false);
iAmTabless = DataSingelton.getiAmTables();
recyclerView = view.findViewById(R.id.rec_layout_itable);
loadData();
return view;
}
public void loadRecycler() {
adapterITable = new AdapterITable(iAmTabless);
recyclerView.setAdapter(adapterITable);
recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 4));
}
@Override
public void onDestroyView() {
super.onDestroyView();
EventBus.getDefault().unregister(this);
}
private void loadData() {
Log.d(TAG, "notifyData: size " + DataSingelton.eventNotifAlarm.size());
Log.d(TAG, "MY TABLE size : " + iAmTabless.size());
loadRecycler();
notifyData();
}
public void loadNotifyTable() {
for (IAmTables table : DataSingelton.getiAmTables()) {
table.setType(-1);
Integer a = DataSingelton.eventNotifAlarm.get("" + table.getId());
if (a != null) {
Log.d("TEST_EVENT1", "table Id: " + table.getId() + " type ==" + a);
table.setType(a);
}
}
adapterITable.loadNewData(DataSingelton.getiAmTables());
}
public void notifyData() {
loadNotifyTable();
adapterITable.notifyDataSetChanged();
Log.d(TAG, "MY TABLE size : " + iAmTabless.size());
}
@Override
public void onResume() {
super.onResume();
if (adapterITable != null)
notifyData();
}
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void EventITable(EventIAmTableChange eventIAmTableChange) {
notifyData();
Log.d(TAG, "notiife size on resume : " + DataSingelton.eventNotifAlarm.size() + " === data size ==== " + DataSingelton.iAmTables.size());
}
}
|
package com.ringcentral;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.ResponseBody;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
import com.ringcentral.definitions.MakeRingOutCallerInfoRequestFrom;
import com.ringcentral.definitions.MakeRingOutCallerInfoRequestTo;
import com.ringcentral.definitions.MakeRingOutRequest;
public class RingOutTest extends BaseTest {
@Test
public void testRingOutAndCallLog() throws IOException, RestException {
MakeRingOutRequest callRequestBody = new MakeRingOutRequest()
.from(new MakeRingOutCallerInfoRequestFrom().phoneNumber(config.get("username")))
.to(new MakeRingOutCallerInfoRequestTo().phoneNumber(config.get("receiver")));
ResponseBody callReqAck = restClient.post("/restapi/v1.0/account/~/extension/~/ring-out", callRequestBody);
JsonElement jsonCallReqAck = new JsonParser().parse(callReqAck.string());
JsonObject jObjCallReqAck = jsonCallReqAck.getAsJsonObject();
String callId = jObjCallReqAck.get("id").getAsString();
Assert.assertTrue("CallID is not retreived, call may not be successful", !callId.equals(""));
//get call log information
HttpClient.QueryParameter params = new HttpClient.QueryParameter("content-type", "application/json");
String endpoint = "/restapi/v1.0/account/~/extension/~/call-log";
ResponseBody callsLog = restClient.get(endpoint, params);
JsonElement callsLogJson = new JsonParser().parse(callsLog.string());
JsonObject callLogsJObj = callsLogJson.getAsJsonObject();
JsonArray callRecords = callLogsJObj.getAsJsonArray("records");
JsonObject recentCallRecord = callRecords.get(0).getAsJsonObject();
String latestCallLogUrl = recentCallRecord.get("uri").getAsString();
ResponseBody callLog = restClient.get(latestCallLogUrl, params);
System.out.println(callLog.string());
}
}
|
package ga.islandcrawl.map;
import java.util.ArrayList;
import java.util.Random;
import ga.islandcrawl.draw.Rectangle;
import ga.islandcrawl.object.*;
import ga.islandcrawl.object.Object;
/**
* Created by Ga on 12/27/2015.
*/
public class TileMarker { //Only marks for 1 draw
private static final float rectSize = 1f/Dimension.registerPrecision;
private static ArrayList<Object> tiles = new ArrayList<>();
public static void addTile(I p){
addTile(p, new float[]{1,1,0,1});
}
public static void addTile(I p, float[] color){
Object t = new Object("0",new Rectangle(1 / Dimension.registerPrecision, 1 / Dimension.registerPrecision, color));
t.place(p);
tiles.add(t);
}
public static Object addPermanantTile(I p){
Object t = new Object("0",new Rectangle(1 / Dimension.registerPrecision, 1 / Dimension.registerPrecision, new float[]{1,0,1,1}));
t.place(p);
return t;
}
public static void wipe(){
for (int i=0;i<tiles.size();i++) {
tiles.get(i).die();
}
tiles = new ArrayList<>();
}
public static void draw(float[] matrix){
for (int i=0;i<tiles.size();i++) {
tiles.get(i).draw(matrix);
}
}
}
|
/*
We have jobs: difficulty[i] is the difficulty of the ith job, and profit[i] is the profit of the ith job.
Now we have some workers. worker[i] is the ability of the ith worker, which means that this worker can only complete a job with difficulty at most worker[i].
Every worker can be assigned at most one job, but one job can be completed multiple times.
For example, if 3 people attempt the same job that pays $1, then the total profit will be $3. If a worker cannot complete any job, his profit is $0.
What is the most profit we can make?
Example 1:
Input: difficulty = [2,4,6,8,10], profit = [10,20,30,40,50], worker = [4,5,6,7]
Output: 100
Explanation: Workers are assigned jobs of difficulty [4,4,6,6] and they get profit of [20,20,30,30] seperately.
Notes:
1 <= difficulty.length = profit.length <= 10000
1 <= worker.length <= 10000
difficulty[i], profit[i], worker[i] are in range [1, 10^5]
*/
//The key to this problem is to sort the input? How to sort?
//After sorting, keep track of the max value you can make.
class Solution {
public int maxProfitAssignment(int[] difficulty, int[] profit, int[] worker) {
Arrays.sort(worker);
PriorityQueue<int[]> pq = new PriorityQueue<> ((a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
for (int i = 0; i < profit.length; i++) {
pq.offer(new int[]{difficulty[i], profit[i]});
}
int res = 0;
int max = 0;
for (int w : worker) {
while (pq.size() > 0 && w >= pq.peek()[0]) {
max = Math.max(max, pq.poll()[1]);
}
res += max;
}
return res;
}
}
|
package ru.usu.cs.fun.lang.types;
public class FunString extends Value<String> {
public FunString(String value) {
super(value);
}
}
|
package pattern.factory;
public class LDPepperPizza extends Pizza {
@Override
public void prepare() {
System.out.println("伦敦胡椒pizza");
}
}
|
package com.koreait.model;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.koreait.dao.MemberDao;
import com.koreait.dto.ItemDto;
public class GoBuyPage implements Action {
@Override
public String command(HttpServletRequest request, HttpServletResponse response) {
MemberDao dao = MemberDao.getInstance();
List<ItemDto> list = dao.getItemList();
request.setAttribute("list", list);
return "buy/buyPage.jsp";
}
}
|
package myproject.game.dao;
import myproject.game.models.entities.Question;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface QuestionRepository extends JpaRepository<Question, Long> {
}
|
package ro.redeul.google.go.lang.psi.impl.toplevel;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.ResolveState;
import com.intellij.psi.scope.PsiScopeProcessor;
import org.jetbrains.annotations.NotNull;
import ro.redeul.google.go.lang.psi.impl.GoPsiElementBase;
import ro.redeul.google.go.lang.psi.toplevel.GoTypeDeclaration;
import ro.redeul.google.go.lang.psi.toplevel.GoTypeSpec;
import ro.redeul.google.go.lang.psi.visitors.GoElementVisitor;
/**
* Author: Toader Mihai Claudiu <mtoader@gmail.com>
* <p/>
* Date: Aug 30, 2010
* Time: 8:59:20 PM
*/
public class GoTypeDeclarationImpl extends GoPsiElementBase implements GoTypeDeclaration {
public GoTypeDeclarationImpl(@NotNull ASTNode node) {
super(node);
}
public GoTypeSpec[] getTypeSpecs() {
return findChildrenByClass(GoTypeSpec.class);
}
@Override
public void accept(GoElementVisitor visitor) {
visitor.visitTypeDeclaration(this);
}
@Override
public boolean processDeclarations(@NotNull PsiScopeProcessor processor, @NotNull ResolveState state, PsiElement lastParent, @NotNull PsiElement place) {
GoTypeSpec typeSpecs[] = getTypeSpecs();
for (GoTypeSpec typeSpec : typeSpecs) {
if ( typeSpec != lastParent ) {
if ( ! typeSpec.processDeclarations(processor, state, null, place) ) {
return false;
}
}
}
return true;
}
}
|
package com.simbircite.homesecretary.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.Months;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import com.simbircite.demo.util.DateUtil;
@Entity
@Table(name = "PERIODIC_TRANSACTIONS")
public class PeriodicTransaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
int id;
@Column(name = "ACCRUAL")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(iso = ISO.DATE)
DateTime accrual; //время когда начислять
@Column(name = "DEADLINE")
@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(iso = ISO.DATE)
DateTime deadline; //конец выплат
@Column(name = "SUMM", nullable = false)
double summ;
@Column(name = "PERIOD")
int period; //частота начисления
@Column(name = "PERCENTAGE")
double percentage; //сколько процентов от суммы начисляется
public int getId() {
return id;
}
public void setId(int value) {
id = value;
}
public double getSumm() {
return summ;
}
public void setSumm(double value) {
summ = value;
}
public DateTime getAccrual() {
return accrual;
}
public void setAccrual(DateTime value) {
accrual = value;
}
public String getAccrualString() {
return DateUtil.format(accrual);
}
public DateTime getDeadline() {
return deadline;
}
public void setDeadline(DateTime value) {
deadline = value;
}
public String getDeadlineString() {
return DateUtil.format(deadline);
}
public int getPeriod() {
return period;
}
public void setPeriod(int value) {
period = value;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double value) {
percentage = value;
}
// Единичный платеж
public double getPay() {
return summ * percentage / 100;
}
// Количество необходимых платежей
public int getInterval() {
return Months.monthsIn(new Interval(accrual, deadline)).getMonths();
}
public int getPayCount() {
return getInterval() / period;
}
public double getTotal() {
return getPay() * getPayCount();
}
// Количество совершенных платежей
public int getCurrentInterval() {
return Months.monthsIn(new Interval(accrual, new DateTime())).getMonths();
}
public int getCurrentPayCount() {
return getCurrentInterval() / period;
}
public double getComplete() {
return getPay() * getCurrentPayCount();
}
// Осталось оплатить
public double getBalance() {
return getTotal() - getComplete();
}
}
|
package net.minecraft.block;
import net.minecraft.block.material.MapColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.IBlockAccess;
public class BlockPrismarine extends Block {
public static final PropertyEnum<EnumType> VARIANT = PropertyEnum.create("variant", EnumType.class);
public static final int ROUGH_META = EnumType.ROUGH.getMetadata();
public static final int BRICKS_META = EnumType.BRICKS.getMetadata();
public static final int DARK_META = EnumType.DARK.getMetadata();
public BlockPrismarine() {
super(Material.ROCK);
setDefaultState(this.blockState.getBaseState().withProperty((IProperty)VARIANT, EnumType.ROUGH));
setCreativeTab(CreativeTabs.BUILDING_BLOCKS);
}
public String getLocalizedName() {
return I18n.translateToLocal(String.valueOf(getUnlocalizedName()) + "." + EnumType.ROUGH.getUnlocalizedName() + ".name");
}
public MapColor getMapColor(IBlockState state, IBlockAccess p_180659_2_, BlockPos p_180659_3_) {
return (state.getValue((IProperty)VARIANT) == EnumType.ROUGH) ? MapColor.CYAN : MapColor.DIAMOND;
}
public int damageDropped(IBlockState state) {
return ((EnumType)state.getValue((IProperty)VARIANT)).getMetadata();
}
public int getMetaFromState(IBlockState state) {
return ((EnumType)state.getValue((IProperty)VARIANT)).getMetadata();
}
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, new IProperty[] { (IProperty)VARIANT });
}
public IBlockState getStateFromMeta(int meta) {
return getDefaultState().withProperty((IProperty)VARIANT, EnumType.byMetadata(meta));
}
public void getSubBlocks(CreativeTabs itemIn, NonNullList<ItemStack> tab) {
tab.add(new ItemStack(this, 1, ROUGH_META));
tab.add(new ItemStack(this, 1, BRICKS_META));
tab.add(new ItemStack(this, 1, DARK_META));
}
public enum EnumType implements IStringSerializable {
ROUGH(0, "prismarine", "rough"),
BRICKS(1, "prismarine_bricks", "bricks"),
DARK(2, "dark_prismarine", "dark");
private static final EnumType[] META_LOOKUP = new EnumType[(values()).length];
private final int meta;
private final String name;
private final String unlocalizedName;
static {
byte b;
int i;
EnumType[] arrayOfEnumType;
for (i = (arrayOfEnumType = values()).length, b = 0; b < i; ) {
EnumType blockprismarine$enumtype = arrayOfEnumType[b];
META_LOOKUP[blockprismarine$enumtype.getMetadata()] = blockprismarine$enumtype;
b++;
}
}
EnumType(int meta, String name, String unlocalizedName) {
this.meta = meta;
this.name = name;
this.unlocalizedName = unlocalizedName;
}
public int getMetadata() {
return this.meta;
}
public String toString() {
return this.name;
}
public static EnumType byMetadata(int meta) {
if (meta < 0 || meta >= META_LOOKUP.length)
meta = 0;
return META_LOOKUP[meta];
}
public String getName() {
return this.name;
}
public String getUnlocalizedName() {
return this.unlocalizedName;
}
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\block\BlockPrismarine.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com;
import com.view.LoginView;
public class WarehouseManagement {
public static void main(String[] args) {
new LoginView();
}
}
|
package com.gregfmartin.smsdemo;
import android.app.Application;
import android.content.res.Configuration;
import android.provider.Telephony;
import android.util.Log;
import com.gregfmartin.smsdemo.entities.ConversationListing;
/**
* Application-level class for maintaining state and members that need to be known to the entirety of the program.
*
* @author gregfmartin
*/
public class ApplicationCore extends Application {
static final private String TAG = ApplicationCore.class.getSimpleName();
static final private boolean DEBUG = true;
static private ConversationListing mConversationListing;
@Override public void onCreate() {
super.onCreate();
if(DEBUG) { Log.i(TAG, "onCreate Started"); }
mConversationListing = new ConversationListing(this);
if(DEBUG) { Log.i(TAG, "onCreate Ending"); }
}
@Override public void onTerminate() {
super.onTerminate();
if(DEBUG) { Log.i(TAG, "onTerminate Started"); }
if(DEBUG) { Log.i(TAG, "onTerminate Ending"); }
}
@Override public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(DEBUG) { Log.i(TAG, "onConfigurationChanged Started"); }
if(DEBUG) { Log.i(TAG, "onConfigurationChanged Ending"); }
}
static final public boolean getDebug() { return DEBUG; }
static final public ConversationListing getConversationListing() { return mConversationListing; }
}
|
package HuaWei;
import java.util.Scanner;
public class 杨辉三角变形偶数位子 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int line = in.nextInt();
if (line<=2) {
System.out.println(-1);
}else if (line%2==1) {
System.out.println(2);
}else if (line%4==0) {
System.out.println(3);
}else {
System.out.println(4);
}
}
}
}
|
package org.basic.dao.adapter;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.ORecordLazyList;
import com.orientechnologies.orient.core.db.record.ORecordLazySet;
import com.orientechnologies.orient.core.record.impl.ODocument;
import java.util.HashSet;
import java.util.List;
public class DaoAdapter implements DaoInterface {
@Override
public ODocument save(ODatabaseDocumentTx db, ODocument model) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAll(ODatabaseDocumentTx db) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAll(ODatabaseDocumentTx db, long start, long end) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumn(ODatabaseDocumentTx db, String kolom,
Object value) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumn(ODatabaseDocumentTx db, String kolom,
String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumn(ODatabaseDocumentTx db, String kolom,
Object value, long start, long end) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumn(ODatabaseDocumentTx db, String kolom,
String value, long start, long end) {
// TODO Auto-generated method stub
return null;
}
@Override
public ODocument getOne(ODatabaseDocumentTx db, String kolom, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public ODocument getOne(ODatabaseDocumentTx db, String kolom, Object value,
String kolom2, Object value2, String operator) {
// TODO Auto-generated method stub
return null;
}
@Override
public ODocument getOne(ODatabaseDocumentTx db, String kolom, Object value,
String kolom2, Object vallue2) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getCount(ODatabaseDocumentTx db) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getCount(ODatabaseDocumentTx db, String sql, String as) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getCountByColumn(ODatabaseDocumentTx db, String colom,
String value) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getCountByColumn(ODatabaseDocumentTx db, String colom,
Object value) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long getCountByColumn(ODatabaseDocumentTx db, String colom,
String value, String colom2, String value2, String operator) {
// TODO Auto-generated method stub
return 0;
}
@Override
public void printAll(ODatabaseDocumentTx db) {
// TODO Auto-generated method stub
}
@Override
public long delByColoumn(ODatabaseDocumentTx db, String colom, String value) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long truncetClass(ODatabaseDocumentTx db) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long truncetRecord(ODatabaseDocumentTx db, String rid) {
// TODO Auto-generated method stub
return 0;
}
@Override
public long deleteAll(ODatabaseDocumentTx db) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getClassName() {
// TODO Auto-generated method stub
return null;
}
@Override
public ODocument delete(ODatabaseDocumentTx db, ODocument o) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getNameFielsToString() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllSearch(ODatabaseDocumentTx db, ODocument o) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getCountSearch(ODatabaseDocumentTx db, ODocument o) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<ODocument> getCountAllSearch(ODatabaseDocumentTx db, ODocument o) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllSearch(ODatabaseDocumentTx db, ODocument o,
long tmp, long jumlahPerHalaman) {
// TODO Auto-generated method stub
return null;
}
@Override
public ODocument update(ODatabaseDocumentTx db, ODocument model) {
// TODO Auto-generated method stub
model.save();
return model;
}
@Override
public ODocument update(ODatabaseDocumentTx db, ODocument model,
String jsonOld) {
model.save();
return model;
}
@Override
public List<ODocument> getLinkList(ODatabaseDocumentTx db, String linklist) {
// TODO Auto-generated method stub
return null;
}
@Override
public HashSet<ODocument> getLinkSet(ODatabaseDocumentTx db, ORecordLazyList linkset) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumnLike(ODatabaseDocumentTx db,
String col, String value, long tmp, long jumlahPerHalaman) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumnLike(ODatabaseDocumentTx db,
String col, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getCountByColumnLike(ODatabaseDocumentTx db, String col,
String value) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getFormatCode() {
return "00000";
}
@Override
public boolean isUseFormatCode() {
return true;
}
@Override
public boolean isTrueChildThis(ODocument o) {
// TODO Auto-generated method stub
return false;
}
@Override
public List<ODocument> getAllByColumnLikeCollection(ODatabaseDocumentTx db,
String col, String kolomAnak, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getAllByColumnLikeCollection(ODatabaseDocumentTx db,
String kolom, String kolomAnak, String value, long start, long end) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getCountByColumnLikeCollection(ODatabaseDocumentTx db,
String col, String col2, String string) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<ODocument> getLinkList(ODatabaseDocumentTx db,
ORecordLazyList linklist) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<ODocument> getLinkList(ODatabaseDocumentTx db,
ORecordLazySet linklist) {
// TODO Auto-generated method stub
return null;
}
}
|
package com.tencent.mm.plugin.voip.ui;
class e$9 implements Runnable {
final /* synthetic */ e oSe;
e$9(e eVar) {
this.oSe = eVar;
}
public final void run() {
if (this.oSe.getActivity() != null && !this.oSe.getActivity().isFinishing()) {
e.g(this.oSe).setVisibility(8);
}
}
}
|
package com.hcr.service.impl;
import com.hcr.model.User;
import com.hcr.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public User getUser(Integer id) {
return new User(1,"hcr");
}
@Override
public User add(User user) throws Exception {
if("".equals(user.getName())){
throw new Exception("名字为空!");
}
System.out.println("新增用户");
return user;
}
@Override
public void update(User user) {
System.out.println("修改用户");
}
@Override
public void delete(Integer id) {
}
}
|
package cs414.a1.gazawayj;
import static org.junit.Assert.*;
import java.util.HashSet;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
public class ProjectTest {
@Test
public void testProj() {
//setup enviro
setupTestEnviroment();
//test missingQualifications
Project proj = testMiss();
//test isHelpful
testHelp(proj);
testEquals(proj);
}
//Tests overridden equals method
public void testEquals(Project proj) {
assertFalse(proj.equals(proj3));
proj3 = proj;
assertTrue(proj.equals(proj3));
Project proj9 = testMiss();
assertTrue(proj.equals(proj9));
}
//Tests project is helpful
public void testHelp(Project proj) {
//Assert that Worker temp2 is useful for proj1
assertTrue(proj1.isHelpful(temp2));
assertFalse(proj1.isHelpful(temp1));
}
//Tests missing qualifications
public Project testMiss(){
miss.add(qual2);
miss.add(qual3);
miss.add(qual4);
//both sets are subsets of eachother, meaning that they contain the same elements
assertTrue(miss.containsAll(proj1.missingQualifications()));
assertTrue(proj1.missingQualifications().containsAll(miss));
//This calls the next test!!
return proj1;
}
//Simply sets up the test enviroment
public void setupTestEnviroment() {
miss = new HashSet<Qualification>();
qual1 = new Qualification("Heroe");
qual2 = new Qualification("Noble");
qual3 = new Qualification("Valiant");
qual4 = new Qualification("asdt");
set1 = new HashSet<Qualification>();
set2 = new HashSet<Qualification>();
set3 = new HashSet<Qualification>();
set4 = new HashSet<Qualification>();
set1.add(qual1);
set2.add(qual1);
set2.add(qual2);
set3.add(qual1);
set3.add(qual2);
set3.add(qual3);
set3.add(qual4);
set4.add(qual3);
set4.add(qual4);
temp1 = new Worker("One", set1);
temp2 = new Worker("Two", set4);
//Have to make Worker sets
ws1 = new HashSet<Worker>();
ws1.add(temp1);
//Have to make some projects to test overloaded String n, Set<Worker> ws, Set<Qualification> qs, ProjectSize s
proj1 = new Project("Project1", ws1, set3, ProjectSize.large, null);
proj2 = new Project("Project2", ws1, set3, ProjectSize.medium, null);
proj3 = new Project("Project3", ws1, set2, ProjectSize.large, null);
//Proj4 has need quals: noble, valiant. Gets: noble
proj4 = new Project("Project4", ws1, set2, ProjectSize.large, null);
proj1.setStatus(ProjectStatus.active);
proj2.setStatus(ProjectStatus.active);
proj3.setStatus(ProjectStatus.active);
proj4.setStatus(ProjectStatus.active);
}
//Needed variables
Set<Worker> ws1;
Qualification qual1;
Qualification qual2;
Qualification qual3;
Qualification qual4;
Qualification quals;
Set<Qualification> set1;
Set<Qualification> set2;
Set<Qualification> set3;
Set<Qualification> set4;
Worker temp1;
Worker temp2;
Project proj1;
Project proj2;
Project proj3;
Project proj4;
Set<Qualification> miss;
}
|
package fr.lteconsulting.training.moviedb;
import fr.lteconsulting.training.moviedb.ejb.GestionCategories;
import fr.lteconsulting.training.moviedb.ejb.GestionProduits;
import fr.lteconsulting.training.moviedb.model.Categorie;
import fr.lteconsulting.training.moviedb.model.Produit;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.ejb.EJB;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(Arquillian.class)
public class GestionCategoriesTest {
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class, "test.war")
.addPackage(Categorie.class.getPackage())
.addPackage(GestionCategories.class.getPackage())
.addAsResource("test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
}
@EJB
private GestionCategories gestionCategories;
@EJB
private GestionProduits gestionProduits;
@Test
public void testAjoutCategorie() {
Categorie categorie = new Categorie();
categorie.setNom("test");
gestionCategories.add(categorie);
assertNotNull("l'ID ne devrait pas être null", categorie.getId());
assertEquals("le nom devrait être 'test'", "test", categorie.getNom());
}
@Test
public void testGetNbProduitParCategorieId() {
Categorie categorie = new Categorie();
gestionCategories.add(categorie);
int nb = 10;
for (int i = 0; i < nb; i++) {
Produit produit = new Produit();
produit.setCategorie(categorie);
gestionProduits.add(produit);
}
assertNotNull("l'ID ne devrait pas être null", categorie.getId());
assertEquals("il devrait y avoir " + nb + " produits pour cette catégorie", nb, gestionCategories.getNbProduitParCategorieId(categorie.getId()));
}
}
|
package pl.training.shop.category.model;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class CategoriesService {
@NonNull
private CategoriesRepository categoriesRepository;
public List<Category> getAllCategories() {
return categoriesRepository.findAll();
}
public void addCategory(Category category) {
categoriesRepository.save(category);
}
}
|
package com.example.expense;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
public static final String ID="_id";
public static final String FULLNAME="name";
public static final String PASSWORD="password";
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+"LOGIN"+
"( " +"ID"+" integer primary key autoincrement,"+ " FULLNAME text,PASSWORD text); ";
// Variable to hold the database instance
public static SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private Mysignupdatabasehelper dbHelper;
public LoginDataBaseAdapter(Context _context)
{
context = _context;
dbHelper = new Mysignupdatabasehelper(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException
{
db = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
db.close();
}
public SQLiteDatabase getDatabaseInstance()
{
return db;
}
public void delete(Context context)
{
context.deleteDatabase(DATABASE_NAME);
}
public void insertEntry(String Name,String password)
{
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put("FULLNAME",Name);
newValues.put("PASSWORD",password);
// Insert the row into your table
db.insert("LOGIN", null, newValues);
Toast.makeText(context, "GOOD TO GO !", Toast.LENGTH_LONG).show();
}
public int deleteEntry(String UserName)
{
//String id=String.valueOf(ID);
String where="USERNAME=?";
int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
// Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
return numberOFEntriesDeleted;
}
public String getSinlgeEntry(String password)
{
Cursor cursor=db.query("LOGIN", null, " PASSWORD=?", new String[]{password}, null, null, null);
String passwordorg;
if(cursor.getCount()<1)
{
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
passwordorg= cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return passwordorg;
}
public String getname(String password)
{
String[] columns = new String[]{"ID","FULLNAME","PASSWORD"};
Cursor cursor=db.query("LOGIN",columns, " PASSWORD=?", new String[]{password}, null, null, null);
String name = "";
int iName = cursor.getColumnIndex("FULLNAME");
if(cursor.getCount()<1)
{
cursor.close();
return "NOT EXIST";
}
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
name=cursor.getString(iName);
}
return name;
}
public boolean checkForTables(){
boolean hasTables = false;
Cursor cursor = db.rawQuery("SELECT * FROM " + "LOGIN", null);
if(cursor.getCount() == 0){
hasTables=false;
}
if(cursor.getCount() > 0){
hasTables=true;
}
cursor.close();
return hasTables;
}
public void updateEntry(String Name,String old,String password)
{
String[] columns = new String[]{"ID","FULLNAME","PASSWORD"};
Cursor cursor=db.query("LOGIN",columns, " PASSWORD=?", new String[]{old}, null, null, null);
String passwordold = "";
int iPassword = cursor.getColumnIndex("PASSWORD");
if(cursor.getCount()<1)
{
cursor.close();
}
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
{
passwordold=cursor.getString(iPassword);
}
if(old.equals(passwordold))
{
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put("FULLNAME", Name);
updatedValues.put("PASSWORD", password);
db.update("LOGIN",updatedValues,"PASSWORD" ,null);
}
else
Toast.makeText(context,"Password Incorrect ", Toast.LENGTH_SHORT).show();
}
}
|
package common;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.awt.image.WritableRaster;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Blob;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import view.MainWindow;
public class Check {
public static void main(String[] args) throws IOException {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
System.out.println(dateFormat.format(date));
}
}
|
package com.swrdfish.unshop.admin;
import com.google.common.base.CaseFormat;
import com.google.common.base.Strings;
import spark.Route;
import java.util.Map;
import java.util.Set;
class RouteGenerator {
public static void generate(Set<AdminResource> resources, Map<String, Route> routes) {
for(AdminResource resource: resources) {
String modelName = resource.getModelClass().getSimpleName();
//skip anonymous model classes
if(Strings.isNullOrEmpty(modelName)) continue;
String pathName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, modelName);
routes.put("/" + pathName, (req, res) -> modelName);
}
}
}
|
package Analysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
import org.apache.commons.math3.stat.regression.SimpleRegression;
public class Test {
private static double[][] x = new double[540][];
private static double[] y = new double[540];
public static void main(String[] args){
/*
double[] y = new double[]{11.0, 12.0, 13.0, 14.0, 15.0, 16.0};
double[][] x = new double[6][];
x[0] = new double[]{0, 0, 0, 0};
x[1] = new double[]{2.0, 0, 0, 0};
x[2] = new double[]{0, 3.0, 0, 0};
x[3] = new double[]{0, 0, 4.0, 0};
x[4] = new double[]{0, 0, 0, 5.0};
x[5] = new double[]{0, 0, 0, 6.0}; */
double[][] pre = new double[][]{
{1,1,1,1,2,1,1,1,8},
{1,1,1,3,2,1,1,1,1},
{5,10,10,5,4,5,4,4,1},
{3,1,1,1,2,1,1,1,1},
{3,1,1,1,2,1,2,1,2},
{3,1,1,1,3,2,1,1,1},
{2,1,1,1,2,1,1,1,1},
{5,10,10,3,7,3,8,10,2},
{4,8,6,4,3,4,10,6,1},
{4,8,8,5,4,5,10,4,1}
};
try {
readFile("breast-cancer.txt");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for( int i = 0; i < 10; i ++){
OLSmultiple(x,y,pre[i]);
}
}
public static void readFile(String fileName) throws IOException {
File data = new File(fileName);
BufferedReader input = null;
//
BufferedReader inputLabel = null;
try{
input = new BufferedReader(new FileReader(data));
//
inputLabel = new BufferedReader(new FileReader(new File("breast-cancerlabel.txt")));
}catch(FileNotFoundException e){
e.printStackTrace();
System.out.println("Can't read file " + fileName);
}
for( int i = 0; i < 540; i ++){
String line = input.readLine();
Scanner in = new Scanner(line);
//
in.nextInt();
int num1 = in.nextInt();
int num2 = in.nextInt();
int num3 = in.nextInt();
int num4 = in.nextInt();
int num5 = in.nextInt();
int num6 = in.nextInt();
int num7 = in.nextInt();
int num8 = in.nextInt();
int num9 = in.nextInt();
/*
int timePoint = in.nextInt();
double comment = in.nextDouble();
double score = in.nextDouble(); */
//
String labelLine = inputLabel.readLine();
Scanner label = new Scanner(labelLine);
x[i] = new double[]{num1,num2,num3,num4,num5,num6,num7,num8,num9};
y[i] = label.nextDouble();
}
}
public static void simple(){
SimpleRegression simple = new SimpleRegression(true);
double[][] set = new double[][]{
{1,3},
{2,5},
{3,6},
{4,2},
{5,5},
{6,9},
};
double pre = 7;
simple.addData(set);
System.out.println("Simple slope = "+ simple.getSlope());
System.out.println("Simple intercept = "+ simple.getIntercept());
System.out.println("Simple prediction for "+ pre + " = " + simple.predict(pre));
}
public static void OLSmultiple(double[][] x, double[] y, double[] pre){//ordinary least square
OLSMultipleLinearRegression multiple = new OLSMultipleLinearRegression();
multiple.newSampleData(y, x);
double[] beta = multiple.estimateRegressionParameters();
double[] residuals = multiple.estimateResiduals();
double error = multiple.estimateRegressionStandardError();
System.out.println("OLS beta :");
for( int i = 0 ; i < beta.length; i ++)
System.out.println(beta[i]);
/*
System.out.println("OLS residuals :" );
for( int i = 0; i < residuals.length; i ++)
System.out.println(residuals[i]); */
System.out.println("Error Rate:" + error);
double result = beta[0];
for( int i =0 ; i < pre.length; i ++){
result += beta[i+1] * pre[i];
}
System.out.println("OLS prediction for " + result);
}
}
|
package kimmyeonghoe.cloth.dao.logo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import kimmyeonghoe.cloth.dao.map.logo.LogoMap;
@Repository
public class LogoDaoImpl implements LogoDao {
@Autowired private LogoMap logoMap;
@Override
public int insertImage(String fileName, String storedName, int fileSize) {
return logoMap.insertImage(fileName, storedName, fileSize);
}
@Override
public int insertLogo(String logoName, String storedName) {
return logoMap.insertLogo(logoName, storedName);
}
@Override
public String selectLogoName() {
return logoMap.selectLogoName();
}
@Override
public String selectStoredName(int logoNum) {
return logoMap.selectStoredName(logoNum);
}
@Override
public int selectlogoNum() {
return logoMap.selectlogoNum();
}
@Override
public int deleteImage(int imageNum) {
return logoMap.deleteImage(imageNum);
}
@Override
public int deleteLogo(int logoNum) {
return logoMap.deleteLogo(logoNum);
}
}
|
// This file is a part of Humanoid project.
// Copyright (C) 2020 Aleksander Gajewski <adiog@mindblow.io>.
package io.mindblow.humanoid.canvas.core;
import io.mindblow.humanoid.context.MasterContext;
public class CanvasController extends Thread {
private MasterContext masterContext;
public CanvasController(MasterContext masterContext) {
this.masterContext = masterContext;
}
public void run() {
while (isAlive()) {
try {
Thread.sleep(masterContext.config.canvasIntervalMillis);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
masterContext.canvas.tick();
}
}
}
|
package com.wifiesta.restaurant.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.wifiesta.restaurant.model.Menu;
@Service
public class MenuRepository {
@Value(value = "${data.menu.sourcePath}")
private String filePath;
private Object fileLock = new Object(); // Lock to ensure that we access the file only once at a time
private ObjectMapper objectMapper;
public MenuRepository() {
this.objectMapper = new ObjectMapper();
this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
this.objectMapper.registerModule(new JavaTimeModule());
}
public List<Menu> getAll() {
synchronized (this.fileLock) {
return this.readAllFromFile();
}
}
public void deleteAll() {
synchronized (this.fileLock) {
this.saveToFile(new ArrayList<>());
}
}
public void saveMenu(Menu menu) {
synchronized (this.fileLock) {
List<Menu> menus = this.readAllFromFile();
menus.add(menu);
this.saveToFile(menus);
}
}
// Not syncronized, callers should do that.
private List<Menu> readAllFromFile() {
try {
File file = new File(this.filePath);
if (file.createNewFile()) {
return new ArrayList<>();
}
InputStream stream = new FileInputStream(file);
return this.objectMapper.readValue(stream, new TypeReference<List<Menu>>() {
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// Not syncronized, callers should do that.
private void saveToFile(List<Menu> menus) {
try {
File file = new File(this.filePath);
file.createNewFile();
OutputStream stream = new FileOutputStream(file);
this.objectMapper.writeValue(stream, menus);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
import java.util.Scanner;
public class EmployeeDemo {
//data members
int empid;
String name;
float slary;
Scanner sc=new Scanner(System.in);
public void EnterDetails() {
System.out.println("enter empid");
empid=sc.nextInt();
System.out.println("name");
name=sc.next();
System.out.println("slary");
slary=sc.nextFloat();
}
public void display() {
System.out.println("empid is:" +empid);
System.out.println("name is:" +name);
System.out.println("slary is:" +slary);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
EmployeeDemo obj= new EmployeeDemo();
obj.EnterDetails();
obj.display();
}
}
|
package unalcol.math.metric;
/**
* <p>Title: QuasiMetric</p>
* <p>Description: Represents a quasimetric. A quasimetric satisfies the following conditions:</p>
* <p>d(x,y) >= 0</p>
* <p>d(x,x) = 0</p>
* <p>d(x,y)=0 -> x = y</p>
* <p>d(x,z) <= d(x,y) + d(y,z)</p>
* <p>if it satisfies d(x,y) = d(y,x) then it is called metric</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: Universidad Nacional de Colombia</p>
*
* @author Jonatan Gomez Reviewed by (Aurelio Benitez, Giovanni Cantor, Nestor Bohorquez)
* @version 1.0
*/
public interface QuasiMetric<T> {
/**
* Calculates the distance from one object to other. Remember in quasimetrics
* the property d(x,y) == d(y,x) is not always true.
*
* @param x The first object
* @param y The second object
* @return Distance from object x to object y
*/
public double apply(T x, T y);
}
|
import java.util.*;
/**
* 236. Lowest Common Ancestor of a Binary Tree
* Medium
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
Deque<TreeNode> stack = new LinkedList<>();
TreeNode visited = null;
stack.push(root);
TreeNode t = root;
List<TreeNode> ancestors = null;
while (!stack.isEmpty()) {
while (t.left != null) {
t = t.left;
stack.push(t);
}
TreeNode x = stack.peek(); // check current node's right
if (x.right != null && x.right != visited) {
t = x.right;
stack.push(t);
} else {
visited = stack.pop();
if (visited.val == p.val || visited.val == q.val) {
if (ancestors == null) { // save first node's ancestors
ancestors = new ArrayList<>(stack);
} else { // got second node's ancestors
stack.push(visited);
break;
}
}
}
}
TreeNode anc = root;
int i = ancestors.size();
Iterator<TreeNode> j = stack.descendingIterator();
while (i-- > 0 && j.hasNext()) {
if (ancestors.get(i) == j.next()) {
anc = ancestors.get(i);
} else {
break;
}
}
return anc;
}
}
// Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
|
public class DisplayOverloading{
public void display(String c){
System.out.println("One parameter : " + c);
}
public void display(String c, int num){
System.out.println("Two paraameters Method : " + c + "," + num);
}
public void display(int c){
System.out.println("One parameter : " + c);
}
}
|
package Puzzles.GlobalLogic.PrettyPrinter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* Created by skyll on 06.10.2017.
*/
public class Runner {
public static void main(String[] args) throws IOException {
System.out.print("Input path: ");
String path = new BufferedReader(new InputStreamReader(System.in)).readLine();
AccouningData data = new AccouningData("src\\Puzzles\\GlobalLogic\\PrettyPrinter\\accounting_data.csv");
AccouningData data1 = new AccouningData("src\\Puzzles\\GlobalLogic\\PrettyPrinter\\excel.csv");
AccouningData accouningData = new AccouningData(path);
PrettyPrinter.print(accouningData);
System.out.println();
PrettyPrinter.print(data);
System.out.println();
PrettyPrinter.print(data1);
}
}
|
package com.ganesh.gsmarena.crawler;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.ganesh.gsmarena.model.GSMArenaCurrentStatus;
import com.ganesh.gsmarena.util.GSMArenaParseUtility;
/**
* @author shriganesh
*
*/
public class GSMArenaCrawler {
public static void main(String[] args) {
String website = "http://www.gsmarena.com/";
Document fullPage = null;
try {
fullPage = Jsoup.connect(website).data("query", "Java").userAgent("Mozilla").cookie("auth", "token")
.timeout(3000).post();
GSMArenaCurrentStatus currentStatus = new GSMArenaCurrentStatus();
// parsing path from div id body--> div "sidebar col left" --> div
// "brandmenu-v2 light l-box clearfix" --> 2nd element which is list
Elements initial = fullPage.select("div#body");
Elements brandList = initial.first().children().get(1).children().first().child(1).children();
for (Element el : brandList) {
String bPage = el.children().first().absUrl("href");
// Extracting brand
String brand = el.children().first().text();
// Visit each individual webpage of brand for all models.
Document brandPage = Jsoup.connect(bPage).data("query", "Java").userAgent("Mozilla")
.cookie("auth", "token").timeout(3000).post();
// For each individual model page, visit details page.
Elements phoneModelsList = brandPage.select("div.makers").first().children().first().children();
// Getting all the pagination links. Check if page links exist
// for more pages.
Elements tempList = brandPage.select("div.nav-pages");
if (null != tempList) {
Elements pagesList = tempList.first().getElementsByAttribute("href");
// For all links.. get models.
for (Element element : pagesList) {
currentStatus = GSMArenaParseUtility.getInstance().iterateOverModelsList(brand, phoneModelsList,
currentStatus);
// Sleeping for 30 seconds after one list page of a
// brand
// TODO Configure how much sleep is needed.
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
brandPage = Jsoup.connect(element.attr("href")).data("query", "Java").userAgent("Mozilla")
.cookie("auth", "token").timeout(3000).post();
phoneModelsList = brandPage.select("div.makers").first().children().first().children();
}
} else {
currentStatus = GSMArenaParseUtility.getInstance().iterateOverModelsList(brand, phoneModelsList,
currentStatus);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.jack.rookietest.excel;
import com.alibaba.excel.EasyExcel;
import java.io.File;
/**
* @author jack
* @Classname ReadExcelTest1
* Create by jack 2020/1/5
* @date: 2020/1/5 11:25
* @Description:
* 读取EXCEL测试1
* 参考资料:
* https://github.com/alibaba/easyexcel/blob/master/src/test/java/com/alibaba/easyexcel/test/demo/read/ReadTest.java
*/
public class ReadExcelTest1 {
public static void main(String[] args) {
// 写法1:
String fileUrl1 = "F:\\20191226-YUBINMST7_mon1.xlsx";
File file = new File(fileUrl1);
//写法1:
// 这里 需要指定读用哪个class去读,然后读取第二个sheet 文件流会自动关闭
//EasyExcel.read(file, DemoData.class, new DemoDataListener()).sheet(1).doRead();
// 这里 需要指定读用哪个class去读,然后读取第一个sheet 文件流会自动关闭, headRowNumber这里可以设置1,因为头就是一行。如果多行头,可以设置其他值。不传入也可以,因为默认会根据DemoData 来解析,他没有指定头,也就是默认1行
EasyExcel.read(file, DemoData.class, new DemoDataListener()).sheet().headRowNumber(0).doRead();
// 写法2:
//ExcelReader excelReader = EasyExcel.read(file, DemoData.class, new DemoDataListener()).build();
//读取excel的第一个sheet
//ReadSheet readSheet = EasyExcel.readSheet(0).build();
//excelReader.read(readSheet);
// 这里千万别忘记关闭,读的时候会创建临时文件,到时磁盘会崩的
//excelReader.finish();
}
}
|
package com.tencent.mm.plugin.chatroom.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import com.tencent.mm.model.au;
import com.tencent.mm.plugin.chatroom.d.k;
import com.tencent.mm.plugin.chatroom.ui.ChatroomInfoUI.21;
class ChatroomInfoUI$21$1 implements OnCancelListener {
final /* synthetic */ k hMh;
final /* synthetic */ 21 hMi;
ChatroomInfoUI$21$1(21 21, k kVar) {
this.hMi = 21;
this.hMh = kVar;
}
public final void onCancel(DialogInterface dialogInterface) {
au.DF().c(this.hMh);
}
}
|
package com.tencent.mm.g.a;
public final class iy$b {
public String bPu;
public String bSE;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.