text stringlengths 10 2.72M |
|---|
package com.cg.test.service.city;
import com.cg.test.model.City;
import com.cg.test.service.IGeneralService;
public interface ICityService extends IGeneralService<City> {
}
|
/*
* Copyright 2016 TeddySoft Technology. All rights reserved.
*
*/
package tw.teddysoft.gof.TemplateMethod;
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class ConfigParserTest {
private ByteArrayOutputStream stream = null;
private PrintStream printStream = null;
@Before
public void setUp() {
stream = new ByteArrayOutputStream();
printStream = new PrintStream(stream);
System.setOut(printStream);
}
@After
public void tearDown() throws IOException {
if (null != printStream)
printStream.close();
if (null != stream)
stream.close();
}
@Test
public void testFileConfigParser(){
ConfigParser fileParser = new
FileConfigParser("C:\\config.ini");
PersonData fpd = fileParser.doParse();
assertEquals("Teddy", fpd.getName());
assertEquals(100, fpd.getHP());
String expected = "Read config data from file: "
+ "C:\\config.ini\n"
+ "parseToken...\n"
+ "validate config data built from file...\n";
assertEquals(expected, stream.toString());
}
@Test
public void testDBConfigParser(){
ConfigParser dbParser = new
DbConfigParser("http://127.0.0.1/hsql/mydb");
PersonData dbpd = dbParser.doParse();
assertEquals("Kay", dbpd.getName());
assertEquals(100, dbpd.getHP());
String expected = "Read config data from database: "
+ "http://127.0.0.1/hsql/mydb\n"
+ "parseToken...\n"
+ "validate config data built from database...\n";
assertEquals(expected, stream.toString());
}
}
|
package lab_1_revision;
import java.util.Arrays;
/**
* @author Dmitrijs Lobanovskis
* @since 22/09/2016.
*/
public class SimpleArray {
public int[] clear(int[] array){
return new int[]{};
}
public static void printElements(int[] array){
Arrays.stream(array)
.forEach(System.out::println);
}
public int maxElement(int[] array){
int max = Integer.MIN_VALUE;
for (int i = 0; i < array.length; i++) {
if (array[i] > max){
max = array[i];
}
}
return max;
}
public int maxPosition(int[] array){
int max = Integer.MIN_VALUE;
int pos = -1;
for (int i = 0; i < array.length; i++) {
if (array[i] > max){
max = array[i];
pos = i;
}
}
return pos;
}
public int[] reverse(int[] array){
int[] newArray = new int[array.length];
for (int i = array.length - 1; i <= 0; i--) {
newArray[i] = array[i];
}
return newArray;
}
public int[] inPlaceReverse(int[] array){
int low = 0;
int hight = array.length - 1;
int mid = (low + hight) / 2;
while (low < mid){
int tmp = array[low];
array[low] = array[hight];
array[hight] = tmp;
low++;
hight--;
}
return array;
}
}
|
package iteration02.fr.agh.services;
import iteration02.fr.agh.domain.Grid;
/**
* @author elm
*
*/
public interface PrintService {
public void print(int stepNumber,Grid grid);
}
|
package GCC;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
public class Storage
{
public static List<Player> players = new ArrayList<>();
public static Queue<Player> playersQueue = new PriorityQueue<>();
public static boolean usernameExists(String user)
{
for (Player p : players)
if (p.getUsername().equals(user))
return true;
return false;
}
public static void initMatchmaking(Player player)
{
if (playersQueue.size() == 0)
{
playersQueue.add(player);
player.getWriter().println(player.gcp.messageComposer(GCP.Codes.matchmaker_queue, "null"));
}
else
{
Match m = new Match(player, playersQueue.poll());
Main.appendDebugText("New match created, "+m.player1.getUsername()+" vs "+m.player2.getUsername());
}
}
}
|
package com.example.awesoman.owo2_comic.storage;
import android.os.Environment;
import android.provider.BaseColumns;
import java.io.File;
/**
* Created by Awesome on 2016/11/7.
*/
public class ComicEntry implements BaseColumns {
public static final String PROJECT_PATH ="Owo2_Comic";
public static final String DATABASE_PATH = PROJECT_PATH+ File.separator+"databases";
public static final String DATABASE_NAME = "owe2comic.db";
// public static final String COMIC_PATH = PROJECT_PATH+File.separator+"files"+File.separator +"ComicAll";
// public static final String MUSIC_PATH = PROJECT_PATH+File.separator+"files"+File.separator +"MusicAll";
public static final String COMIC_PATH = "ComicRes";
public static final String MUSIC_PATH = "MusicRes";
/**
* 获取根目录
*/
public static String getProjectPath(){
return Environment.getExternalStorageDirectory()+File.separator+PROJECT_PATH;
}
/**
* 获取漫画资源文件夹路径
* @return
*/
public static String getComicPath(){
return Environment.getExternalStorageDirectory()+File.separator+PROJECT_PATH+File.separator+COMIC_PATH;
}
/**
* 获取音乐资源文件夹路径
*/
public static String getMusicPath(){
return Environment.getExternalStorageDirectory()+File.separator+PROJECT_PATH+File.separator+MUSIC_PATH;
}
//ComicAll表名
public static final String COMIC_ALL_TABLE_NAME = "ComicInMain";
//ComicAll列名
public static final String COMIC_ALL_COLUMNS_NAME_COMIC_TYPE = "ComicType";
public static final String COMIC_ALL_COLUMNS_NAME_COMIC_NAME = "ComicName";
public static final String COMIC_ALL_COLUMNS_NAME_COMIC_PATH ="ComicPath";
//ComicAll创建表格的SQL语句
public static final String SQL_CREATE_TABLE_COMIC_IN_MAIN =
"create table " + COMIC_ALL_TABLE_NAME + " (" +
_ID + " integer primary key," +
COMIC_ALL_COLUMNS_NAME_COMIC_TYPE + " text," +
COMIC_ALL_COLUMNS_NAME_COMIC_NAME + " text, " +
COMIC_ALL_COLUMNS_NAME_COMIC_PATH +" text"+")";
//ComicAll删除表格的SQL语句
public static final String COMIC_ALL_SQL_DELETE_TABLE =
"drop table if exists " + COMIC_ALL_TABLE_NAME;
//ComicType表名
public static final String COMIC_TYPE_TABLE_NAME = "ComicType";
//ComicType列名
public static final String TYPE_COLUMNS_NAME_COMIC_NAME = "TypeName";
public static final String TYPE_COLUMNS_NAME_COMIC_No = "TypeNo";
//ComicType创建表格的SQL语句
public static final String SQL_CREATE_TABLE_COMIC_TYPE =
"create table " + COMIC_TYPE_TABLE_NAME + " (" +
_ID + " integer primary key," +
TYPE_COLUMNS_NAME_COMIC_NAME + " text," +
TYPE_COLUMNS_NAME_COMIC_No + " text" +")";
//ComicType删除表格的SQL语句
public static final String TYPE_SQL_DELETE_TABLE =
"drop table if exists " + COMIC_TYPE_TABLE_NAME;
//ComicHistory表名
public static final String COMIC_HISTORY_TABLE_NAME = "ComicHistory";
//ComicHistory列名
public static final String HISTORY_COLUMNS_NAME_COMIC_NAME = "ComicName";
public static final String HISTORY_COLUMNS_NAME_COMIC_CHAPTER = "ComicChapter";
public static final String HISTORY_COLUMNS_NAME_COMIC_PAGE = "ComicPage";
//ComicHistory创建表格的SQL语句
public static final String SQL_CREATE_TABLE_COMIC_HISTORY =
"create table " + COMIC_HISTORY_TABLE_NAME + " (" +
_ID + " integer primary key," +
HISTORY_COLUMNS_NAME_COMIC_NAME + " text," +
HISTORY_COLUMNS_NAME_COMIC_CHAPTER + " text" +
HISTORY_COLUMNS_NAME_COMIC_PAGE+"text" +")";
//ComicHistory删除表格的SQL语句
public static final String COMIC_HISTORY_SQL_DELETE_TABLE =
"drop table if exists " + COMIC_HISTORY_TABLE_NAME;
//MusicTrigger表名
public static final String MUSIC_TRIGGER_TABLE_NAME = "MusicTrigger";
//MusicTrigger列名
public static final String TRIGGER_COLUMNS_NAME_MUSIC_PATH = "MusicPath";
public static final String TRIGGER_COLUMNS_NAME_COMIC_NAME = "ComicName";
public static final String TRIGGER_COLUMNS_NAME_COMIC_CHAPTER = "ComicChapter";
public static final String TRIGGER_COLUMNS_NAME_COMIC_PAGE = "ComicPage";
//MusicTrigger创建表格的SQL语句
public static final String SQL_CREATE_TABLE_MUSIC_TRIGGER =
"create table " + MUSIC_TRIGGER_TABLE_NAME + " (" +
_ID + " integer primary key," +
TRIGGER_COLUMNS_NAME_MUSIC_PATH + " text," +
TRIGGER_COLUMNS_NAME_COMIC_NAME + " text" +
TRIGGER_COLUMNS_NAME_COMIC_CHAPTER+"text" +
TRIGGER_COLUMNS_NAME_COMIC_PAGE +"text" +")";
//MusicTrigger删除表格的SQL语句
public static final String MUSIC_TRIGGER_SQL_DELETE_TABLE =
"drop table if exists " + MUSIC_TRIGGER_TABLE_NAME;
}
|
/*
* Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main.java.fr.ericlab.sondy.algo.eventdetection;
import main.java.fr.ericlab.sondy.algo.Parameter;
/**
*
* @author Adrien GUILLE, ERIC Lab, University of Lyon 2
* @email adrien.guille@univ-lyon2.fr
*/
public class OnlineLDA extends EventDetectionMethod {
public OnlineLDA(){
super();
}
@Override
public String getName() {
return "On-line LDA";
}
@Override
public String getCitation() {
return "<li><b>On-line LDA:</b> J H Lau, N Collier, T Baldwin (2012) On-line Trend Analysis with Topic Models: #twitter Trends Detection Topic Model Online, In Proceedings of the 2012 International Conference on Computational Linguistics, pp. 1519-1534.</li>";
}
@Override
public String getDescription() {
return "A topic modeling-based methodology to track emerging events in microblogs";
}
@Override
public void apply() {
}
}
|
package com.git.cloud.resmgt.network.model.po;
import java.util.Date;
import com.git.cloud.common.model.base.BaseBO;
/**
* @Title RmNwResPoolPo.java
* @Package com.git.cloud.resmgt.network.model.po
* @author syp
* @date 2014-9-15下午4:32:26
* @version 1.0.0
* @Description
*
*/
public class RmNwResPoolPo extends BaseBO {
private static final long serialVersionUID = 1L;
private String resPoolId;// 资源池ID
private String nwResPoolTypeCode;// 网络资源池类型
private String cclassId;
private int ipStart;
private int ipEnd;
private int ipTotalCnt;
private int ipAvailCnt;
private String convergeId;
private String subnetMask;
private String gateway;
private String vlanId;
private String secureAreaId;
private String secureTierId;
private String platformId;
private String virtualTypeId;
private String hostTypeId;
private String useId;
private String datacenterId;
private String isActive;
private String isEnable;
private String updateUser;
private Date updateTime;
private String projectId;
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
/**
* <p>Title:</p>
* <p>Description:</p>
*/
public RmNwResPoolPo() {
super();
}
/**
* <p>Title:</p>
* <p>Description:</p>
* @param resPoolId
* @param nwResPoolTypeCode
* @param cclassId
* @param ipStart
* @param ipEnd
* @param ipTotalCnt
* @param ipAvailCnt
* @param convergeId
* @param subnetMask
* @param gateway
* @param vlanId
* @param secureAreaId
* @param secureTierId
* @param platformId
* @param virtualTypeId
* @param hostTypeId
* @param useId
* @param isActive
* @param isEnable
*/
public RmNwResPoolPo(String resPoolId, String nwResPoolTypeCode, String cclassId, int ipStart, int ipEnd, int ipTotalCnt, int ipAvailCnt, String convergeId, String subnetMask, String gateway,
String vlanId, String secureAreaId, String secureTierId, String platformId, String virtualTypeId, String hostTypeId, String useId, String isActive, String isEnable) {
super();
this.resPoolId = resPoolId;
this.nwResPoolTypeCode = nwResPoolTypeCode;
this.cclassId = cclassId;
this.ipStart = ipStart;
this.ipEnd = ipEnd;
this.ipTotalCnt = ipTotalCnt;
this.ipAvailCnt = ipAvailCnt;
this.convergeId = convergeId;
this.subnetMask = subnetMask;
this.gateway = gateway;
this.vlanId = vlanId;
this.secureAreaId = secureAreaId;
this.secureTierId = secureTierId;
this.platformId = platformId;
this.virtualTypeId = virtualTypeId;
this.hostTypeId = hostTypeId;
this.useId = useId;
this.isActive = isActive;
this.isEnable = isEnable;
}
public String getResPoolId() {
return resPoolId;
}
public void setResPoolId(String resPoolId) {
this.resPoolId = resPoolId;
}
public String getNwResPoolTypeCode() {
return nwResPoolTypeCode;
}
public void setNwResPoolTypeCode(String nwResPoolTypeCode) {
this.nwResPoolTypeCode = nwResPoolTypeCode;
}
public String getCclassId() {
return cclassId;
}
public void setCclassId(String cclassId) {
this.cclassId = cclassId;
}
public int getIpStart() {
return ipStart;
}
public void setIpStart(int ipStart) {
this.ipStart = ipStart;
}
public int getIpEnd() {
return ipEnd;
}
public void setIpEnd(int ipEnd) {
this.ipEnd = ipEnd;
}
public int getIpTotalCnt() {
return ipTotalCnt;
}
public void setIpTotalCnt(int ipTotalCnt) {
this.ipTotalCnt = ipTotalCnt;
}
public int getIpAvailCnt() {
return ipAvailCnt;
}
public void setIpAvailCnt(int ipAvailCnt) {
this.ipAvailCnt = ipAvailCnt;
}
public String getConvergeId() {
return convergeId;
}
public void setConvergeId(String convergeId) {
this.convergeId = convergeId;
}
public String getSubnetMask() {
return subnetMask;
}
public void setSubnetMask(String subnetMask) {
this.subnetMask = subnetMask;
}
public String getGateway() {
return gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getVlanId() {
return vlanId;
}
public void setVlanId(String vlanId) {
this.vlanId = vlanId;
}
public String getSecureAreaId() {
return secureAreaId;
}
public void setSecureAreaId(String secureAreaId) {
this.secureAreaId = secureAreaId;
}
public String getSecureTierId() {
return secureTierId;
}
public void setSecureTierId(String secureTierId) {
this.secureTierId = secureTierId;
}
public String getPlatformId() {
return platformId;
}
public void setPlatformId(String platformId) {
this.platformId = platformId;
}
public String getVirtualTypeId() {
return virtualTypeId;
}
public void setVirtualTypeId(String virtualTypeId) {
this.virtualTypeId = virtualTypeId;
}
public String getHostTypeId() {
return hostTypeId;
}
public void setHostTypeId(String hostTypeId) {
this.hostTypeId = hostTypeId;
}
public String getUseId() {
return useId;
}
public void setUseId(String useId) {
this.useId = useId;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public String getIsEnable() {
return isEnable;
}
public void setIsEnable(String isEnable) {
this.isEnable = isEnable;
}
public String getDatacenterId() {
return datacenterId;
}
public void setDatacenterId(String datacenterId) {
this.datacenterId = datacenterId;
}
public String getUpdateUser() {
return updateUser;
}
public void setUpdateUser(String updateUser) {
this.updateUser = updateUser;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
/* (non-Javadoc)
* <p>Title:getBizId</p>
* <p>Description:</p>
* @return
* @see com.git.cloud.common.model.base.BaseBO#getBizId()
*/
@Override
public String getBizId() {
return resPoolId;
}
}
|
package dao;
import configs.DB;
import entity.Author;
import entity.Book;
import utils.Books;
import java.sql.Connection;
import java.util.List;
import java.util.Set;
public interface BookDAO {
Connection connect(DB db);
Connection getConnection();
boolean save(Object object);
List<Book> searchBookByAuthor(String name, String surname);
boolean deleteAuthorWithHisBooksById(Long authorId);
boolean updateBookNameByBookId(String newName, Long bookId);
boolean addAuthorWithAllHisBooks(Set<Book> books);
Set<Author> findAllAuthors();
List<Book> findAllBooks();
int getTransactionType();
void setTransactionType(int transactionType);
Set<Book> checkBooks(Books books);
boolean writeXmlFile(String xml);
boolean closeConnection();
String moneyCourse(String path);
}
|
package com.example.loopertest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText mNumberEditText;
TextView mResultTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNumberEditText = findViewById(R.id.number_editText);
mResultTextView = findViewById(R.id.result_textView);
}
public void onButtonClick(View view) {
}
} |
package com.example.spring05.service.member;
import javax.servlet.http.HttpSession;
import com.example.spring05.model.member.dto.MemberDTO;
public interface MemberService {
public boolean loginCheck(
MemberDTO dto, HttpSession session);
public void logout(HttpSession session);
public MemberDTO viewMember(String userid);
}
|
package com.my.testio.controller;
import com.my.testio.domain.User;
import com.my.testio.service.IUserService;
import com.my.testio.service.SmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Author: xiaoni
* @Date: 2021/3/21 18:04
*/
@RestController
public class UserController {
@Autowired
private IUserService userService;
@Autowired
private SmsClient smsClient;
@PostMapping("/user")
public String addUser(User user) {
long start = System.currentTimeMillis();
userService.insert(user);
long end = System.currentTimeMillis();
return "SUCCESS:" + (end - start);
}
ExecutorService executorService = Executors.newFixedThreadPool(10);
@PostMapping("/sms/user")
public String register(User user) {
long start = System.currentTimeMillis();
userService.insert(user);
//同步发送短信,比较费时间
// smsClient.sendSms("12345678");
//异步化
executorService.submit(() -> {
smsClient.sendSms("12345678");
});
long end = System.currentTimeMillis();
return "SUCCESS:" + (end - start);
}
}
|
package com.metoo.lucene.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.stereotype.Component;
/**
*
* <p>
* Title: LuceneThreadPool.java
* </p>
*
* <p>
* Description:写索引线程池。默认为单线程池。Executors可创建各类线程池 JDK1.5。
* </p>
*
* <p>
* Copyright: Copyright (c) 2015
* </p>
*
* <p>
* Company: 湖南创发科技有限公司 www.koala.com
* </p>
*
* @author jinxinzhe
*
* @date 2014年12月1日
*
* @version koala_b2b2c 2.0
*/
@Component
public class LuceneThreadPool {
ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();//创建单线程池
private static LuceneThreadPool pool = new LuceneThreadPool();//单例
/**
*向线程池中添加一个任务
*@Descript execute() 接收一个Runnable对象的方法
*/
public void addThread(Runnable r){
fixedThreadPool.execute(r);
}
/**
*获取一个单例 饿汉式
*/
public static LuceneThreadPool instance(){
return pool;
}
/**
*获取池对象
*/
public ExecutorService getService(){
return fixedThreadPool;
}
}
|
package entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Adresse implements Serializable {
@Id
private int IdAdresse;
private int numeroRue;
private String Rue;
private String adresseComplementaire;
private String codePostal;
private String ville;
private String pays;
public int getIdAdresse() {
return IdAdresse;
}
public void setIdAdresse(int idAdresse) {
IdAdresse = idAdresse;
}
public int getNumeroRue() {
return numeroRue;
}
public void setNumeroRue(int numeroRue) {
this.numeroRue = numeroRue;
}
public String getRue() {
return Rue;
}
public void setRue(String rue) {
Rue = rue;
}
public String getAdresseComplementaire() {
return adresseComplementaire;
}
public void setAdresseComplementaire(String adresseComplementaire) {
this.adresseComplementaire = adresseComplementaire;
}
public String getCodePostal() {
return codePostal;
}
public void setCodePostal(String codePostal) {
this.codePostal = codePostal;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return pays;
}
public void setPays(String pays) {
this.pays = pays;
}
}
|
package com.buddybank.mdw.dataobject.adapter;
import java.util.ArrayList;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import com.buddybank.mdw.dataobject.domain.Entry;
import com.buddybank.mdw.dataobject.header.Context;
import com.buddybank.mdw.dataobject.header.Header;
import com.buddybank.mdw.dataobject.header.HeaderKeys;
public class ContextAsHeaderAdapter extends XmlAdapter<Header, Context> {
@Override
public Header marshal(Context context) throws Exception {
Header header = new Header();
header.setEntry(new ArrayList<Entry>());
header.getEntry().add(new Entry(HeaderKeys.SECURE_TOKEN.name(), context.getSecureToken()));
header.getEntry().add(new Entry(HeaderKeys.IP.name(), context.getIp().getValue()));
header.getEntry().add(new Entry(HeaderKeys.APP_VERSION.name(), context.getAppVersion()));
header.getEntry().add(new Entry(HeaderKeys.APP_ID.name(), context.getAppId()));
header.getEntry().add(new Entry(HeaderKeys.API_VERSION.name(), context.getApiVersion()));
header.getEntry().add(new Entry(HeaderKeys.REFRESH_CACHE.name(), context.isRefreshCacheData().toString()));
header.getEntry().add(new Entry(HeaderKeys.PUSH_TOKEN.name(), context.getPushToken()));
header.getEntry().add(new Entry(HeaderKeys.APP_LANGUAGE.name(), context.getAppLanguage().name()));
header.getEntry().add(new Entry(HeaderKeys.CHANNEL.name(), context.getChannel()));
header.getEntry().add(new Entry(HeaderKeys.USER_ID.name(), context.getUserID()));
header.getEntry().add(new Entry(HeaderKeys.IMPERSONATOR_ID.name(), context.getImpersonatorID()));
header.getEntry().add(new Entry(HeaderKeys.DEVICE_TYPE.name(), context.getDeviceType()));
return header;
}
@Override
public Context unmarshal(Header header) throws Exception {
return new Context(header);
}
}
|
/*
* Shania Jo RunningRabbit and Amira Ramirez Gonzalez
*/
package tests;
import clueGame.*;
import static org.junit.Assert.*;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Set;
import org.junit.BeforeClass;
import org.junit.Test;
public class GameActionTests {
private static Board board;
@BeforeClass
public static void setUp() {
board = Board.getInstance();
board.setConfigFiles("data/ClueLayout.csv", "data/ClueRooms.txt","data/PlayerLegend.txt", "data/WeaponLegend.txt");
board.initialize();
// Created new test players for testing
ArrayList<Player> newPlayers = new ArrayList<>();
newPlayers.add(new HumanPlayer("Person 1", 3, 19, Color.RED));
newPlayers.add(new ComputerPlayer("Person 2", 10, 1, Color.ORANGE));
newPlayers.add(new ComputerPlayer("Person 3", 20, 1, Color.YELLOW));
newPlayers.add(new ComputerPlayer("Person 4", 3, 3, Color.GREEN));
newPlayers.add(new ComputerPlayer("Person 5", 20, 10, Color.BLUE));
board.setPlayers(newPlayers);
// Created new deck for testing
ArrayList<Card> newDeck = new ArrayList<>();
newDeck.add(new Card("Home Decoration", CardType.ROOM));
newDeck.add(new Card("Room Decoration", CardType.ROOM));
newDeck.add(new Card("Kitchen Decoration", CardType.ROOM));
newDeck.add(new Card("Weapon 1", CardType.WEAPON));
newDeck.add(new Card("Weapon 2", CardType.WEAPON));
newDeck.add(new Card("Weapon 3", CardType.WEAPON));
newDeck.add(new Card("Weapon 4", CardType.WEAPON));
newDeck.add(new Card("Weapon 5", CardType.WEAPON));
newDeck.add(new Card("Person 1", CardType.PERSON));
newDeck.add(new Card("Person 2", CardType.PERSON));
newDeck.add(new Card("Person 3", CardType.PERSON));
newDeck.add(new Card("Person 4", CardType.PERSON));
newDeck.add(new Card("Person 5", CardType.PERSON));
board.setDeck(newDeck);
board.shuffleDeck();
board.dealCards();
}
/*
Target location tests (computer)
*/
@Test
public void computerLocationTest() {
// No room in target list, random selection
ComputerPlayer testPlayer = new ComputerPlayer("Tester", 9, 6, Color.RED);
board.calcTargets(testPlayer.getRow(), testPlayer.getColumn(), 1);
Set<BoardCell> testTargets = board.getTargets();
BoardCell testLocation = testPlayer.pickLocation(board.getTargets());
assertTrue(testTargets.contains(testLocation));
// If room in list that was not just visited, must select it
testPlayer = new ComputerPlayer("Tester", 7, 4, Color.RED);
board.calcTargets(testPlayer.getRow(), testPlayer.getColumn(), 1);
testLocation = testPlayer.pickLocation(board.getTargets());
assertEquals(testLocation, board.getCellAt(6, 4));
// If room just visited is in list, each target (including room) selected randomly (after picking door, leaving)
testPlayer = new ComputerPlayer("Tester", 16, 3, Color.RED);
board.calcTargets(testPlayer.getRow(), testPlayer.getColumn(), 2);
testTargets = board.getTargets();
testLocation = testPlayer.pickLocation(board.getTargets());
assertTrue(testTargets.contains(testLocation));
}
/*
Accusation tests (board)
*/
@Test
public void checkAccusations() {
Solution testSolution = new Solution("Killer","Weapon","Room");
Solution testAccusation = new Solution("Killer","Weapon","Room");
board.setAnswer(testSolution);
// Test solution that is correct
assertTrue(board.checkAccusation(testAccusation));
// Test solution with wrong person
testAccusation = new Solution("Plebian","Weapon","Room");
assertFalse(board.checkAccusation(testAccusation));
// Test solution with wrong weapon
testAccusation = new Solution("Killer","Flower","Room");
assertFalse(board.checkAccusation(testAccusation));
// Test solution with wrong room
testAccusation = new Solution("Killer","Weapon","Outdoors");
assertFalse(board.checkAccusation(testAccusation));
}
/*
Suggestion tests
*/
@Test
public void creatingComputerSuggestion() { // Computer
// Grabbing the 4th player
ComputerPlayer testPlayer = (ComputerPlayer) board.getPlayers().get(3);
testPlayer.possibleCard(new Card("Weapon 1", CardType.WEAPON));
testPlayer.possibleCard(new Card("Person 1", CardType.PERSON));
ArrayList<Card> testSeenCards = board.getDeck();
// Remove cards to make sure that the player sees them as possibilities
testSeenCards.removeIf(card -> card.getCardName().equals("Weapon 1"));
testSeenCards.removeIf(card -> card.getCardName().equals("Person 1"));
testPlayer.setSeenCards(testSeenCards);
testPlayer.createSuggestion();
Solution testSuggestion = testPlayer.getSuggestion();
// Make sure room matches current location
assertEquals("Home Decoration", testSuggestion.getRoom());
// If only one weapon not seen, it's selected
assertEquals("Weapon 1", testSuggestion.getWeapon());
// If only one person not seen, it's selected (can be same test as weapon)
assertEquals("Person 1", testSuggestion.getPerson());
testPlayer = new ComputerPlayer("Player 4", 3, 3, Color.RED);
testPlayer.possibleCard(new Card("Weapon 1", CardType.WEAPON));
testPlayer.possibleCard(new Card("Weapon 2", CardType.WEAPON));
testPlayer.possibleCard(new Card("Weapon 3", CardType.WEAPON));
testPlayer.possibleCard(new Card("Person 1", CardType.PERSON));
testPlayer.possibleCard(new Card("Person 2", CardType.PERSON));
testPlayer.possibleCard(new Card("Person 3", CardType.PERSON));
testPlayer.createSuggestion();
testSuggestion = testPlayer.getSuggestion();
// If multiple weapons not seen, one of them is randomly selected
boolean seenWeapon = false;
for (Card card : testPlayer.getPossibleWeapons()) {
if (card.getCardName().equals(testSuggestion.getWeapon())) {
seenWeapon = true;
break;
}
}
assertTrue(seenWeapon);
// If multiple persons not seen, one of them is randomly selected
boolean seenPerson = false;
for (Card card : testPlayer.getPossiblePeople()) {
if (card.getCardName().equals(testSuggestion.getPerson())) {
seenPerson = true;
break;
}
}
assertTrue(seenPerson);
}
@Test
public void disproveSuggestion() { // Player
Player testPlayer = new Player("Tester", 9, 6, Color.RED);
ArrayList<Card> newHand = new ArrayList<>();
newHand.add(new Card("Killer", CardType.PERSON));
newHand.add(new Card("Weapon", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayer.setHand(newHand);
// If player has only one matching card it should be returned
Card card = testPlayer.disproveSuggestion(new Solution("Killer", "Spoon", "Closet"));
assertEquals("Killer", card.getCardName());
// If players has >1 matching card, returned card should be chosen randomly
card = testPlayer.disproveSuggestion(new Solution("Killer", "Weapon", "Closet"));
assertTrue(card.getCardName().equals("Killer") || card.getCardName().equals("Weapon"));
// If player has no matching cards, null is returned
card = testPlayer.disproveSuggestion(new Solution("Man", "Spoon", "Closet"));
assertNull(card);
}
@Test
public void handlingSuggestion() { // Board
ArrayList<Player> testPlayers = board.getPlayers();
ArrayList<Card> testDeck = board.getDeck();
// Suggestion no one can disprove returns null
Solution testSuggestion = new Solution("","","");
assertNull(board.handleSuggestion(testSuggestion, testPlayers.get(1)));
// Suggestion only accusing player can disprove returns null
ArrayList<Card> oldHand = testPlayers.get(1).getHand();
ArrayList<Card> newHand = new ArrayList<>();
newHand.add(new Card("", CardType.PERSON));
newHand.add(new Card("Weapon", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(1).setHand(newHand);
assertNull(board.handleSuggestion(testSuggestion, testPlayers.get(1)));
testPlayers.get(1).setHand(oldHand);
// Suggestion only human can disprove returns answer (i.e., card that disproves suggestion)
oldHand = testPlayers.get(0).getHand();
newHand = new ArrayList<>();
newHand.add(new Card("", CardType.PERSON));
newHand.add(new Card("Weapon", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(0).setHand(newHand);
Card testCard = board.handleSuggestion(testSuggestion, testPlayers.get(1));
assertTrue(testSuggestion.hasCard(testCard));
testPlayers.get(0).setHand(oldHand);
// Suggestion only human can disprove, but human is accuser, returns null
oldHand = testPlayers.get(0).getHand();
newHand = new ArrayList<>();
newHand.add(new Card("", CardType.PERSON));
newHand.add(new Card("Weapon", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(0).setHand(newHand);
assertNull(board.handleSuggestion(testSuggestion, testPlayers.get(0)));
testPlayers.get(0).setHand(oldHand);
// Suggestion that two players can disprove, correct player (based on starting with next player in list) returns answer
ArrayList<Card> oldHand1 = testPlayers.get(1).getHand();
newHand = new ArrayList<>();
newHand.add(new Card("", CardType.PERSON));
newHand.add(new Card("Weapon", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(1).setHand(newHand);
ArrayList<Card> oldHand2 = testPlayers.get(2).getHand();
newHand = new ArrayList<>();
newHand.add(new Card("Killer", CardType.PERSON));
newHand.add(new Card("", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(2).setHand(newHand);
testCard = board.handleSuggestion(testSuggestion, testPlayers.get(0));
assertTrue(testPlayers.get(1).getHand().contains(testCard));
testPlayers.get(1).setHand(oldHand1);
testPlayers.get(2).setHand(oldHand2);
// Suggestion that human and another player can disprove, other player is next in list, ensure other player returns answer
oldHand1 = testPlayers.get(0).getHand();
newHand = new ArrayList<>();
newHand.add(new Card("", CardType.PERSON));
newHand.add(new Card("Weapon", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(0).setHand(newHand);
oldHand2 = testPlayers.get(1).getHand();
newHand = new ArrayList<>();
newHand.add(new Card("Killer", CardType.PERSON));
newHand.add(new Card("", CardType.WEAPON));
newHand.add(new Card("Room", CardType.ROOM));
testPlayers.get(1).setHand(newHand);
testCard = board.handleSuggestion(testSuggestion, testPlayers.get(2));
assertTrue(testPlayers.get(1).getHand().contains(testCard));
testPlayers.get(0).setHand(oldHand1);
testPlayers.get(1).setHand(oldHand2);
}
}
|
/*Raymond Luu
* TCSS143
* John Mayer
* 10/31/11
*/
import java.io.File;
import java.util.*;
public class TestShapes {
public static void main(String args[]) {
Scanner fileScan = null;//initialize Scanner
//import file
try {
fileScan = new Scanner(new File("Shapes.txt"));
} catch(Exception e) {//catch if file isn't found
System.out.println("File not found");
}
List<Shape> shapeList = new ArrayList<Shape>();//new ArrayList of shapes
//look through file
while(fileScan.hasNextLine()) {
String lineString = fileScan.nextLine();//make each line a string
Scanner lineScan = new Scanner(lineString);//Scanner for each line
List<Double> numList =new ArrayList<Double>();//new temporary ArrayList of numbers
//add # to list
while(lineScan.hasNextDouble()) {
numList.add(lineScan.nextDouble());
}
//create shapes and store into ArrayList
if(numList.size() == 1) {
Circle cir = new Circle(numList.get(0));
shapeList.add(cir);
} else if(numList.size() == 2) {
Rectangle rect = new Rectangle(numList.get(0), numList.get(1));
shapeList.add(rect);
} else if(numList.size() == 3) {
Triangle tri = new Triangle(numList.get(0), numList.get(1), numList.get(2));
shapeList.add(tri);
}
}
System.out.println("Original Shape List -");
displayShapes(shapeList);
List<Shape> copyShapeList = new ArrayList<Shape>();
copyShapeList.addAll(shapeList);
Collections.sort(copyShapeList);
System.out.println("Sorted Shape List -");
displayShapes(copyShapeList);
System.out.println("Original Shape List -");
displayShapes(shapeList);
}
public static void displayShapes (List<Shape> shapeList) {
Iterator<Shape> shapeIter = shapeList.iterator();
//display shapes
while(shapeIter.hasNext()) {
Shape a = shapeIter.next();
System.out.printf("%-50s", a);
System.out.printf("Area: %.2f\n", a.calculateArea());
}
System.out.println();
}
} |
package com.example.demo.company;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* This is a controller on Company with Admin APIs
*/
@RestController
public class CompanyControllerAdmin {
@Autowired
CompanyService companyService;
/**
* Post a Company
*
* @param companyDto the company dto
* @return the company
*/
@PostMapping("/admin/companies")
public Company createCompany(@RequestBody CompanyDto companyDto){
Company company = new Company(companyDto.getName(),companyDto.getLocation());
return companyService.createCompany(company);
}
/**
* PUT an existed company
*
*
* @param companyDto the company dto
* @return the company
*/
@PutMapping("/admin/companies")
public Company updateCompany(@RequestBody CompanyDto companyDto){
Company company = new Company();
company.setId(companyDto.getId());
company.setLocation(companyDto.getLocation());
company.setName(companyDto.getName());
return companyService.updateCompany(company);
}
/**
* Delete company.
*
* @param id the id
*/
@DeleteMapping("/admin/companies/{id}")
public void deleteCompany(@PathVariable int id){
companyService.deleteCompany(id);
}
}
|
package br.com.cubo.sps.main;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import br.com.cubo.sps.process.MatchScorer;
import br.com.cubo.sps.process.PLayFileReader;
import br.com.cubo.sps.vo.Match;
import br.com.cubo.sps.vo.Score;
public class Main {
public static void main(String[] args) {
InputStream fileLog = Main.class.getClassLoader().getResourceAsStream(
"play-log.log");
PLayFileReader pLayFileReader = new PLayFileReader();
List<Match> matchList = pLayFileReader.read(fileLog);
MatchScorer matchScorer = new MatchScorer();
List<Score> createScore = matchScorer.createScore(matchList);
for (Score score : createScore) {
System.out.println(score.getMachId());
Map<String, Integer> killerScore = score.getKillerScore();
Set<Entry<String, Integer>> killerEntrySet = killerScore.entrySet();
for (Entry<String, Integer> entry : killerEntrySet) {
System.out.println("Kills " + entry.getKey() + " - " + entry.getValue());
}
Map<String, Integer> killedScore = score.getKilledScore();
Set<Entry<String, Integer>> killedEntrySet = killedScore.entrySet();
for (Entry<String, Integer> entry : killedEntrySet) {
System.out.println("Deads " + entry.getKey() + " - " + entry.getValue());
}
}
}
}
|
package homework2.loops;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.stream.Stream;
public class Exponent3Test {
@ParameterizedTest(name = "{displayName} получно число {0},возвести в степень {1} -> {2}")
@MethodSource("argumentsSource")
public void getExpTest(double d, int i, double res){
Assertions.assertEquals(res, Exponent3.getExp(d,i));
}
public static Stream<Arguments> argumentsSource(){
return Stream.of(
Arguments.arguments(18.0, 5,1_889_568.0 ),
Arguments.arguments(7.5, 2, 56.25),
Arguments.arguments(33.3, 3, 36926.03699999999)
);
}
}
|
public class NeuralNetwork
{
private String filename;
private int [] inputNeurons;
Learn learn;
Guess guess;
public void setLearn(Learn learn)
{
this.learn = learn;
}
public void learning()
{
learn.learning(filename);
}
public void setGuess(Guess guess)
{
this.guess = guess;
}
public void guessing()
{
guess.guessing(filename, this.inputNeurons);
}
public void setFilename(String filename)
{
this.filename = filename;
}
public void setInputNeurons(int[] inputNeurons)
{
this.inputNeurons = inputNeurons;
}
}
|
package com.socialteinc.socialate;
import android.content.Intent;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.ViewInteraction;
import android.support.test.espresso.action.ViewActions;
import android.support.test.espresso.contrib.RecyclerViewActions;
import android.support.test.filters.LargeTest;
import android.support.test.filters.MediumTest;
import android.support.test.filters.SmallTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerViewAccessibilityDelegate;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.*;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.*;
import static android.support.test.espresso.action.ViewActions.swipeUp;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.*;
import static org.hamcrest.Matchers.allOf;
@RunWith(AndroidJUnit4.class)
public class MainTest1 {
FirebaseAuth mAuth;
DatabaseReference mUsersDatabaseReference;
FirebaseDatabase mFireBaseDatabase;
@Rule
public ActivityTestRule<MainActivity> rule = new ActivityTestRule<>(MainActivity.class);
@Before
public void login(){
FirebaseApp.initializeApp(rule.getActivity());
mAuth = FirebaseAuth.getInstance();
mAuth.signInWithEmailAndPassword("musa@gmail.com", "password")
.addOnCompleteListener(rule.getActivity(), new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
} else {
// If sign in fails, display a message to the user.
Log.w("login activity", "signInWithEmail:failure", task.getException());
}
}
});
}
// @Test
// public void recyclerViewTest() throws InterruptedException{
// login();
// Thread.sleep(4000);
// onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.scrollToPosition(3));
// //onView(withId(R.id.entertainmentSpotRecyclerView)).perform(RecyclerViewActions.scrollToHolder(...));
// }
@Test
@MediumTest
public void signOutTest() throws InterruptedException {
Thread.sleep(6000);
mAuth.signOut();
Thread.sleep(2000);
login();
Thread.sleep(2000);
}
@Test
@LargeTest
public void checkProfileTest() throws InterruptedException{
Thread.sleep(6000);
mFireBaseDatabase = FirebaseDatabase.getInstance();
mUsersDatabaseReference = mFireBaseDatabase.getReference().child("users");
FirebaseApp.initializeApp(rule.getActivity());
mAuth = FirebaseAuth.getInstance();
Looper.prepare();
final MainActivity obj = new MainActivity();
if(mAuth.getCurrentUser() != null){
final String user_id = mAuth.getCurrentUser().getUid();
mUsersDatabaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
obj.startActivity(new Intent(obj.getApplicationContext(), CreateProfileActivity.class));
obj.finish();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Thread.sleep(4000);
}
} |
package com.thomson.dp.principle.zen.dip;
/**
* 司机接口
*
* @author Thomson Tang
*/
public interface IDriver {
void setCar(ICar car);
void drive();
}
|
package Automobili;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import artikli.Kompozicija;
public class ServisneKnjizice {
private Automobil automobil;
private ArrayList<Servis> lista_servisa;
public Automobil() {
this.automobil = new Automobil();
this.podaci_oautu = new ArrayList<Automobil>();
}
public ArrayList<Servis> getLista_servisa() {
return lista_servisa;
}
public void setLista_servisa(ArrayList<Servis> lista_servisa) {
this.lista_servisa = lista_servisa;
}
public ServisneKnjizice(ArrayList lista_servisa,Automobil automobil) {
super();
this.lista_servisa = lista_servisa;
this.automobil = automobil;
}
}
|
package com.dexvis.simple.transform;
import javafx.scene.web.HTMLEditor;
import org.simpleframework.xml.transform.Transform;
public class HTMLEditorTransform implements Transform<HTMLEditor>
{
public HTMLEditor read(String value) throws Exception
{
HTMLEditor editor = new HTMLEditor();
editor.setHtmlText(value);
return editor;
}
@Override
public String write(HTMLEditor value) throws Exception
{
return value.getHtmlText();
}
}
|
package com.skfeng.ndk;
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.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import android.util.Log;
import com.skfeng.gradesign.FileInfo;
import com.skfeng.gradesign.Select_file_set;
public class ExtractSiftFea {
public static String SIFT_FEA_DIR_STRING="/storage/sdcard1/GraDesign/sift";
public static int k=70;//the k of kmeans
public static int lda_k=3;
public static String[] pho_paths=
{"/storage/sdcard1/DCIM/myphoto/e.jpg","/storage/sdcard1/DCIM/myphoto/d.jpg",
"/storage/sdcard1/DCIM/myphoto/f.jpg","/storage/sdcard1/DCIM/myphoto/a.jpg",
"/storage/sdcard1/DCIM/myphoto/b.jpg","/storage/sdcard1/DCIM/myphoto/c.jpg"};
//存放每张图片特征向量文件的文件夹
private static final String TAG="ExtractSiftFea";
public static int[]category = new int[100];//要分类的图片的个数不会超过100的。
public static String res_dir="/storage/sdcard1/GraDesign/res";
public static final void Gen_Sift_fea()
{
int len=Select_file_set.selected_files.size();
FileInfo[] fileInfos=Select_file_set.selected_files.toArray(new FileInfo[len]);
pho_paths=new String[len];
for (int i = 0; i < pho_paths.length; i++) {
pho_paths[i]=fileInfos[i].getFilePath();
}
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
for (int i = 0; i < fileInfos.length; i++) {
final String file_path=pho_paths[i];
fixedThreadPool.execute(new Runnable(){
@Override
public void run() {
System.out.println("Thread begin!");
GeaFeaFile(file_path);
}
});
}
fixedThreadPool.shutdown();
try
{
// awaitTermination返回false即超时会继续循环,返回true即线程池中的线程执行完成主线程跳出循环往下执行,
//每隔10秒循环一次
while (!fixedThreadPool.awaitTermination(10, TimeUnit.SECONDS));
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Log.v(TAG, "调用Gather_result前");
Gather_result(pho_paths, len);
Log.v(TAG, "调用Gather_result后");
}
public static final void cluster_kmeans()
{
int len=pho_paths.length;
Log.v(TAG, "调用cluster_kmeanspp前");
cluster_kmeanspp(pho_paths,k,len);
Log.v(TAG, "调用cluster_kmeanspp后");
}
public static final void freq_count()
{
int len=pho_paths.length;
Log.v(TAG, "调用fre_count前");
fre_count(pho_paths,k,len);
Log.v(TAG, "调用fre_count后");
}
public static final void final_lda()
{
int len=pho_paths.length;
Log.v(TAG, "调用lda_main前");
lda_main(lda_k,len,category);
Log.v(TAG, "调用lda_main后");
}
/**
* 删除一个目录(可以是非空目录)
*
* @param dir
*/
public static boolean delDir(File dir) {
if (dir == null || !dir.exists() || dir.isFile()) {
return false;
}
for (File file : dir.listFiles()) {
if (file.isFile()) {
file.delete();
} else if (file.isDirectory()) {
delDir(file);// 递归
}
}
dir.delete();
return true;
}
public static final void copy(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
public static final void Cre_res()//根据分类结果拷贝相应的图片到此目录
{
File res_file_dir=new File(res_dir);
if(res_file_dir.exists())
delDir(res_file_dir);
res_file_dir.mkdir();
String base_name="class";
for (int i = 0; i < lda_k; i++) {
String class_name=base_name+Integer.toString(i);
File class_name_dir=new File(res_dir+"/"+class_name);
class_name_dir.mkdir();
for(int j=0;j<pho_paths.length;j++)
{
if(category[j]==i)
{
String dst_string=class_name_dir.getAbsolutePath()+
pho_paths[j].substring(pho_paths[j].lastIndexOf("/"));
File src = new File(pho_paths[j]),
dst = new File(dst_string);
try {
copy(src, dst);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static final native void GeaFeaFile(String file_path);
public static final native void Gather_result(String[] files_paths,int len);
public static final native void GeaFeaFiles(String[] files_paths,int len);
public static final native void cluster_kmeanspp(String[] files_paths,int k,int len);
public static final native void fre_count(String[] files_paths,int k,int len);
public static final native void lda_main(int lda_k,int doc_num,int[] category);
public static void test1()
{
Log.v(TAG,"请开始工作吧!");
}
//下面开始载入动态链接库
static{
System.loadLibrary("opencv_java");
System.loadLibrary("nonfree");
System.loadLibrary("Sift");
System.loadLibrary("cluster");
System.loadLibrary("freCount");
System.loadLibrary("ldaApply");
Log.v(TAG,"all library loaded successfully,no UnsatisfiedLinkError throwed!!!");
}
}
|
package com.esum.wp.ims.errorsummary.dao;
import java.util.List;
import com.esum.appframework.dao.IBaseDAO;
import com.esum.appframework.exception.ApplicationException;
public interface IErrorSummaryDAO extends IBaseDAO {
List selectDocumentPageList(Object object) throws ApplicationException;
List selectErrCodeDetailPageList(Object object) throws ApplicationException;
} |
package org.testing.testScript;
public class TC_5 {
// Login - video play - Like - browser close
}
|
package org.point85.domain.proficy;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
/**
* Serialized tag sample data
*
*/
public class TagSample {
@SerializedName(value = "TimeStamp")
private String timeStamp;
@SerializedName(value = "Value")
private String value;
@SerializedName(value = "Quality")
private Integer quality;
/**
* Create a tag sample from a value
*
* @param dataValue Java object data value
*/
public TagSample(Object dataValue) {
timeStamp = Instant.now().truncatedTo(ChronoUnit.MILLIS).toString();
value = dataValue.toString();
quality = TagQuality.Good.getQuality();
}
public String getTimeStamp() {
return timeStamp;
}
public String getValue() {
return value;
}
public Integer getQuality() {
return quality;
}
public boolean isArray() {
return value.contains("[");
}
/**
* Get the Java Instant for the UTC time stamp
*
* @return Instant in time
*/
public Instant getTimeStampInstant() {
return (timeStamp != null) ? Instant.parse(timeStamp) : null;
}
/**
* Get the OffsetDateTime of the tag's time stamp in the local time zone
*
* @return OffsetDateTime time stamp
*/
public OffsetDateTime getTimeStampTime() {
Instant timestamp = getTimeStampInstant();
// UTC time in local zone
return (timestamp != null) ? OffsetDateTime.ofInstant(timestamp, ZoneId.systemDefault()) : null;
}
/**
* Get the Java value for this tag data type
*
* @param type {@link TagDataType}
* @return Java Object
*/
public Object getTypedValue(TagDataType type) {
return !type.isArray() ? TagSample.parseType(getValue(), type) : null;
}
private static Object parseType(String tagValue, TagDataType type) {
Object typedValue = null;
Class<?> clazz = type.getJavaType();
if (clazz != null) {
if (clazz.equals(String.class)) {
typedValue = tagValue;
} else if (clazz.equals(Byte.class)) {
typedValue = Byte.valueOf(tagValue);
} else if (clazz.equals(Short.class)) {
typedValue = Short.valueOf(tagValue);
} else if (clazz.equals(Integer.class)) {
typedValue = Integer.valueOf(tagValue);
} else if (clazz.equals(Long.class)) {
typedValue = Long.valueOf(tagValue);
} else if (clazz.equals(Float.class)) {
typedValue = Float.valueOf(tagValue);
} else if (clazz.equals(Double.class)) {
typedValue = Double.valueOf(tagValue);
} else if (clazz.equals(Boolean.class)) {
typedValue = Boolean.valueOf(tagValue);
} else if (clazz.equals(Instant.class)) {
typedValue = Instant.parse(tagValue);
}
}
return typedValue;
}
/**
* A Java typed list from an array tag
*
* @param type {@link TagDataType}
* @return List of Object
*/
public List<Object> getTypedList(TagDataType type) {
List<Object> values = new ArrayList<>();
StringBuilder sb = new StringBuilder();
sb.append('{').append('"').append("Values").append('"').append(':').append(value).append('}');
String json = sb.toString();
Gson gson = new Gson();
TagStringArray tagStringArray = gson.fromJson(json, TagStringArray.class);
for (String stringValue : tagStringArray.getValues()) {
values.add(TagSample.parseType(stringValue, type));
}
return values;
}
public TagQuality getEnumeratedQuality() {
return TagQuality.fromInt(quality);
}
}
|
package com.dataart.was.entities;
public class Country extends SimpleEntity {
}
|
package ca.polymtl.rubikcube.CubeActivity;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.util.Log;
import ca.polymtl.rubikcube.CubeActivity.CubeSurfaceViewRenderer.AnimationCompleteCallback;
import ca.polymtl.rubikcube.CubeActivity.model.Rubik;
import ca.polymtl.rubikcube.CubeActivity.model.Side;
import ca.polymtl.rubikcube.CubeActivity.model.Rubik.RotationDirection;
import ca.polymtl.rubikcube.util.Rotation;
import ca.polymtl.rubikcube.util.Vect3f;
/**
* This class is responsible for drawing a visual representation of a Rubik cube with OpenGL.
*
* @author markys
*
*/
public class CubeRenderer {
public static final String LOG_TAG = CubeRenderer.class.getSimpleName();
/**
* The rubik cube we are drawing.
*/
Rubik rubik = null;
Rubik rubikPicking;
// The Renderer we will use to render each cubelet.
final CubeletRenderer cubeletRenderer;
/* Offsets of the cubelets position */
final float[] _translates;// =
public CubeRenderer(GL10 gl) {
//this.rubik = rubik;
this.rubikPicking = new Rubik();
cubeletRenderer = new CubeletRenderer(gl);
_translates = new float[3];
_translates[0] = -1 * cubeletRenderer.getDimension();
_translates[1] = 0 * cubeletRenderer.getDimension();
_translates[2] = 1 * cubeletRenderer.getDimension();
}
AnimationCompleteCallback animationCompleteCallback = null;
/**
* Renders a cube using OpenGL.
*
* @param gl
* The OpenGL context.
* @param cube
* The cube to render.
*/
public void render(GL10 gl, boolean picking, boolean pickingSide) {
if (rubik == null) {
return;
}
/*
* Will increment the rotation angle if there is a face rotating.
*/
if (!picking) {
incrementRotateFace();
}
/*
* If one face is in rotation, we draw three layers of 9 cubelets in a sequence perpendicular to that face. In
* other words, if a face is rotating, we will draw all the cubelets of this face at the same time
*/
/*
* If it is Front or Back
*/
if (isInRotation && (sideInRotation == Side.FRONT || sideInRotation == Side.BACK || sideInRotation == Side.MIDDLE_FB)) {
/* Is it front or back */
int rotatingZ = 0;
if (sideInRotation == Side.FRONT) {
rotatingZ = 2;
}
else if (sideInRotation == Side.BACK) {
rotatingZ = 0;
}
else {
rotatingZ = 1;
}
/*
* Draw the three cubelet layers
*/
for (int k = 0; k < Rubik.CUBEDIM; k++) {
/*
* If it is the rotating layer.
*/
if (k == rotatingZ) {
gl.glPushMatrix();
Rotation r = new Rotation(angleInRotation, new Vect3f(0f, 0f, 1f));
gl.glMultMatrixf(r.asFloatBuffer());
}
/* Draw the 9 cubelets of this layer */
for (int j = 0; j < Rubik.CUBEDIM; j++) {
for (int i = 0; i < Rubik.CUBEDIM; i++) {
gl.glPushMatrix();
gl.glTranslatef(_translates[i], _translates[j], _translates[k]);
if (picking) {
cubeletRenderer.render(gl, rubikPicking.cubeletAt(i, j, k), picking, pickingSide);
}
else {
cubeletRenderer.render(gl, rubik.cubeletAt(i, j, k), picking, pickingSide);
}
gl.glPopMatrix();
}
}
if (k == rotatingZ) {
gl.glPopMatrix();
}
}
}
/*
* If it is Top or Bottom
*/
if (isInRotation && (sideInRotation == Side.UP || sideInRotation == Side.DOWN || sideInRotation == Side.MIDDLE_UD)) {
/* Is it top of bottom */
int rotatingY = 0;
if (sideInRotation == Side.UP) {
rotatingY = 2;
}
else if (sideInRotation == Side.DOWN) {
rotatingY = 0;
}
else {
rotatingY = 1;
}
for (int j = 0; j < Rubik.CUBEDIM; j++) {
/*
* If it is the rotating layer.
*/
if (j == rotatingY) {
gl.glPushMatrix();
Rotation r = new Rotation(angleInRotation, new Vect3f(0f, 1f, 0f));
gl.glMultMatrixf(r.asFloatBuffer());
}
for (int k = 0; k < Rubik.CUBEDIM; k++) {
for (int i = 0; i < Rubik.CUBEDIM; i++) {
gl.glPushMatrix();
gl.glTranslatef(_translates[i], _translates[j], _translates[k]);
if (picking) {
cubeletRenderer.render(gl, rubikPicking.cubeletAt(i, j, k), picking, pickingSide);
}
else {
cubeletRenderer.render(gl, rubik.cubeletAt(i, j, k), picking, pickingSide);
}
gl.glPopMatrix();
}
}
if (j == rotatingY) {
gl.glPopMatrix();
}
}
}
/*
* If it is Right or Left
*/
if (isInRotation && (sideInRotation == Side.RIGHT || sideInRotation == Side.LEFT || sideInRotation == Side.MIDDLE_RL)) {
/* Is it right or left */
int rotatingX = 0;
if (sideInRotation == Side.RIGHT) {
rotatingX = 2;
}
else if (sideInRotation == Side.LEFT) {
rotatingX = 0;
}
else {
rotatingX = 1;
}
for (int i = 0; i < Rubik.CUBEDIM; i++) {
/*
* If it is the rotating layer.
*/
if (i == rotatingX) {
gl.glPushMatrix();
Rotation r = new Rotation(angleInRotation, new Vect3f(1f, 0f, 0f));
gl.glMultMatrixf(r.asFloatBuffer());
}
for (int k = 0; k < Rubik.CUBEDIM; k++) {
for (int j = 0; j < Rubik.CUBEDIM; j++) {
gl.glPushMatrix();
gl.glTranslatef(_translates[i], _translates[j], _translates[k]);
if (picking) {
cubeletRenderer.render(gl, rubikPicking.cubeletAt(i, j, k), picking, pickingSide);
}
else {
cubeletRenderer.render(gl, rubik.cubeletAt(i, j, k), picking, pickingSide);
}
gl.glPopMatrix();
}
}
if (i == rotatingX) {
gl.glPopMatrix();
}
}
}
/*
* No rotation, draw everything in any order
*/
if (!isInRotation) {
for (int i = 0; i < Rubik.CUBEDIM; i++) {
for (int j = 0; j < Rubik.CUBEDIM; j++) {
for (int k = 0; k < Rubik.CUBEDIM; k++) {
gl.glPushMatrix();
gl.glTranslatef(_translates[i], _translates[j], _translates[k]);
if (picking) {
cubeletRenderer.render(gl, rubikPicking.cubeletAt(i, j, k), picking, pickingSide);
}
else {
cubeletRenderer.render(gl, rubik.cubeletAt(i, j, k), picking, pickingSide);
}
gl.glPopMatrix();
}
}
}
}
}
/*
* For the animation of the rotation of a face.
*/
boolean isInRotation = false;
float angleInRotation = 0f;
Side sideInRotation = null;
RotationDirection wayInRotation = null;
float rotationInc = 0f;
/**
* Initiate the rotation of a face.
*
* @param side
* Which face to rotate.
* @param way
* Which way.
*/
public void startRotateFace(Side side, RotationDirection way) {
/*
* Something is wrong in there, it turns the face the wrong way ! So, instead of fixing the real problem, hide
* it and go back watching TV.
*/
way = (way == RotationDirection.CW) ? RotationDirection.CCW : RotationDirection.CW;
/* If there is a rotation going on, finish it instantly */
if (isInRotation) {
finishRotateFace();
}
Log.d(LOG_TAG, "Start rotation " + side + " " + way);
isInRotation = true;
angleInRotation = 0f;
sideInRotation = side;
wayInRotation = way;
/* We want the rotation direction to be relative to a view from the exterior of the cube */
if (side.ordinal() <= 2 && way == RotationDirection.CCW || side.ordinal() >= 3 && way == RotationDirection.CW) {
rotationInc = 0.1f / 2;
} else {
rotationInc = -0.1f / 2;
}
}
/**
* Slightly increase the angle of the rotating face to simulate the movement.
*/
public void incrementRotateFace() {
if (!isInRotation) {
return;
}
angleInRotation += rotationInc;
/* Test if the rotation is complete */
if (Math.abs(angleInRotation) >= Math.PI / 2.0) {
finishRotateFace();
}
}
/**
* Complete the rotation of the face.
*/
public void finishRotateFace() {
if (!isInRotation) {
return;
}
Log.d(LOG_TAG, "Stop rotation " + sideInRotation + " " + wayInRotation);
rubik.rotateFace(sideInRotation, wayInRotation);
isInRotation = false;
angleInRotation = 0f;
sideInRotation = null;
wayInRotation = null;
rotationInc = 0f;
if (animationCompleteCallback != null) {
animationCompleteCallback.animationCompleted();
}
}
public void loadGLTexture(GL10 gl, Context context) {
cubeletRenderer.loadGLTexture(gl, context);
}
public void setRubik(Rubik rubik) {
this.rubik = rubik;
}
public void setAnimationCompleteCallback(AnimationCompleteCallback callback) {
this.animationCompleteCallback = callback;
}
}
|
package com.choco.order.controller;
import com.alibaba.dubbo.config.annotation.Reference;
import com.choco.common.entity.Admin;
import com.choco.rpc.service.CartService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* Created by choco on 2021/1/11 17:17
*/
@Controller
@RequestMapping("cart")
public class CartController {
@Reference(interfaceClass = CartService.class)
private CartService cartService;
/**
* 返回购物车数量
* @param model
* @param request
* @return
*/
@ResponseBody
@RequestMapping("cartNum")
public Integer getCartNum(Model model, HttpServletRequest request){
Admin admin = (Admin) request.getSession().getAttribute("user");
return cartService.getCartNums(admin);
}
}
|
package com.example.dmitriy.musicplayer.activities;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.example.dmitriy.musicplayer.R;
import com.example.dmitriy.musicplayer.Utils;
import com.example.dmitriy.musicplayer.services.DownloadMusicService;
import java.io.File;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
|
package com.lovers.java.mapper;
import com.lovers.java.domain.SysUser;
import com.lovers.java.domain.UserMoodRecord;
import com.lovers.java.domain.UserMoodRecordExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface UserMoodRecordMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
long countByExample(UserMoodRecordExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int deleteByExample(UserMoodRecordExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int deleteByPrimaryKey(Integer recordId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int insert(UserMoodRecord record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int insertSelective(UserMoodRecord record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
List<UserMoodRecord> selectByExample(UserMoodRecordExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
UserMoodRecord selectByPrimaryKey(Integer recordId);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByExampleSelective(@Param("record") UserMoodRecord record, @Param("example") UserMoodRecordExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByExample(@Param("record") UserMoodRecord record, @Param("example") UserMoodRecordExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByPrimaryKeySelective(UserMoodRecord record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_mood_record
*
* @mbg.generated Wed Sep 25 10:59:33 CST 2019
*/
int updateByPrimaryKey(UserMoodRecord record);
List<UserMoodRecord> selectByUsers(@Param("sysUsers") List<SysUser> sysUsers);
} |
package BST;
import java.util.*;
public class LevelOrderTraversal {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null)
return null;
List<List<Integer>> outerList = new ArrayList<List<Integer>>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while (!queue.isEmpty()) {
// clear list always
List<Integer> innerList = new ArrayList<Integer>();
int size = queue.size();
// process queue
for (int i = 0; i < size; i++) {
TreeNode curr = queue.poll(); // 3
innerList.add(curr.val); // 3
if (curr.left != null)
queue.add(curr.left);
if (curr.right != null)
queue.add(curr.right);
}
outerList.add(innerList);
}
return outerList;
}
} |
package cn.itcast.core.service;
import cn.itcast.core.pojo.item.Item;
import cn.itcast.core.pojo.seckill.SeckillGoods;
import java.util.List;
public interface ItemService {
public List<Item> findByGoodsId(Long goodsId);
public Item findOne(Long id);
}
|
package ca.usask.cs.srlab.simclipse;
public class SimClipseException extends RuntimeException {
private static final long serialVersionUID = -5363162729846063176L;
public SimClipseException() {
super();
// TODO Auto-generated constructor stub
}
public SimClipseException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
public SimClipseException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public SimClipseException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
}
|
/*
* 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.
*/
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static spark.Spark.*;
public class FriendController {
public FriendController() {
get("/friends", (req, res) -> {
/*Map<String, User> userList = new HashMap<>();
User user001 = new User("Summer Smith", "summer@randm.com", "Summer Sol", "rickandmorty.com");
userList.put(user001.getId(), user001);
Gson gson = new Gson();
return gson.toJson(userList);*/
String id = UUID.randomUUID().toString();
Map<String, Object> friendList = new HashMap<>();
friendList.put("id", id);
friendList.put("username", "schwiftytime");
friendList.put("name", "Rick Sanchez");
friendList.put("email", "rick@rick.com");
friendList.put("bizname", "Curse Purge Plus!");
friendList.put("website", "rickandmorty.com");
friendList.put("craft", "Science");
friendList.put("about", "*Burp*");
/* friendList.put("id", "0001");
friendList.put("username", "inferiorgenes");
friendList.put("name", "Abradolf Lincler");
friendList.put("email", "abe@rick.com");
friendList.put("bizname", "Emancipation");
friendList.put("website", "rickandmorty.com");
friendList.put("craft", "Wood Burning");
friendList.put("about", "Wood work is calming.");*/
Gson gson = new Gson();
return gson.toJson(friendList);
});
/*get("/users", (req, res) -> userService.getAllUsers(), json());
get("/users/:id", (req, res) -> {
String id = req.params(":id");
User user = userService.getUser(id);
if (user != null) {
return user;
}
res.status(400);
return new ResponseError("No user with id '%s' found", id);
}, json());
wrote similar code elsewhere
post("/users", (req, res) -> userService.createUser(
req.queryParams("name"),
req.queryParams("email"),
req.queryParams("bizname"),
req.queryParams("website")
), json());
exception(IllegalArgumentException.class, (e, req, res) -> {
res.status(400);
res.body(toJson(new ResponseError(e)));
});*/
}
}
|
package org.apidesign.gate.timing;
import net.java.html.json.ComputedProperty;
import net.java.html.json.Model;
import net.java.html.json.Property;
@Model(className = "Config", builder = "with", properties = {
@Property(name = "name", type = String.class),
@Property(name = "date", type = String.class),
@Property(name = "min", type = String.class),
@Property(name = "max", type = String.class),
@Property(name = "ui", type = UI.class),
})
final class ConfigModel {
@ComputedProperty(write = "url")
static String url(UI ui) {
return ui.getUrl();
}
static void url(Config model, String newUrl) {
model.getUi().setUrl(newUrl);
}
}
|
package com.eclipseop.discordbot;
import com.eclipseop.discordbot.util.Key;
import javax.security.auth.login.LoginException;
/**
* Created by Eclipseop.
* Date: 2/11/2019.
*/
public class Bootstrap {
private static Key KEYS;
private static Bot bot;
public static Bot getBot() {
return bot;
}
public static Key getKeys() {
return KEYS;
}
public static void main(String... args) {
if (args.length != 2) {
System.out.println("Please pass google and discord key, in that order.");
return;
}
KEYS = new Key(args[0], args[1]);
System.out.println("Reading keys as " + KEYS);
try {
Bootstrap.bot = new Bot();
} catch (LoginException e) {
e.printStackTrace();
}
}
}
|
/*
* The MIT License (MIT)
*
* Copyright (C) 2014 Squawkers13 <Squawkers13@pekkit.net>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.pekkit.feathereconomy.data;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import net.pekkit.feathereconomy.FeatherEconomy;
import net.pekkit.feathereconomy.locale.MessageSender;
/**
* Database Manager- Manages the database used to store economy data.
*
* @author Squawkers13
*/
public class DatabaseManager {
private final FeatherEconomy plugin;
private String dbPath;
private Connection connection;
private Statement statement;
private ResultSet results;
/**
*
* @param pl
*/
public DatabaseManager(FeatherEconomy pl) {
plugin = pl;
}
/**
* Initializes the database.
*
*/
protected void initDB() {
try {
Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
MessageSender.logStackTrace("Could not find driver!", e);
}
try {
dbPath = "jdbc:sqlite:" + plugin.getDataFolder() + File.separator + "FeatherEconomy.db";
connection = DriverManager.getConnection(dbPath);
} catch (SQLException ex) {
MessageSender.logStackTrace("Could not create connection!", ex);
}
}
/**
* Creates the default tables.
*/
protected void createTables() {
update("CREATE TABLE IF NOT EXISTS Econ (UUID TEXT UNIQUE NOT NULL PRIMARY KEY, balance FLOAT DEFAULT 0.0);");
}
/**
* Sends a query to the database and returns the results.
*
* @param query
* @param row
* @return results of query
* @throws java.sql.SQLException
*/
protected int query(String query, String row) throws SQLException {
statement = connection.createStatement();
results = statement.executeQuery(query);
int var = 0;
while (results.next()) {
var = results.getInt(row);
}
statement.close();
results.close();
return var;
}
/**
* Sends a query to the database. Must be a INSERT, UPDATE, or DELETE query!
*
* @param query
*/
protected void update(String query) {
try {
statement = connection.createStatement();
statement.executeUpdate(query);
statement.close();
} catch (SQLException ex) {
MessageSender.logStackTrace("Exception with the query!", ex);
}
}
/**
*
* @param player
* @param table
* @return whether the query was null or not
*/
protected boolean checkNull(String player, String table) {
try {
statement = connection.createStatement();
results = statement.executeQuery("SELECT * FROM " + table + " WHERE UUID='" + player + "';");
String UUID = null;
while (results.next()) {
UUID = results.getString("UUID");
}
statement.close();
results.close();
return UUID == null;
} catch (SQLException ex) {
//MessageSender.logStackTrace("Exception with the query!", ex);
return true;
}
}
}
|
package com.geniusgithub.lookaround.fragment;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.geniusgithub.lookaround.FragmentControlCenter;
import com.geniusgithub.lookaround.FragmentModel;
import com.geniusgithub.lookaround.LAroundApplication;
import com.geniusgithub.lookaround.R;
import com.geniusgithub.lookaround.activity.MainLookAroundActivity;
import com.geniusgithub.lookaround.adapter.NavChannelAdapter;
import com.geniusgithub.lookaround.model.BaseType;
import com.geniusgithub.lookaround.model.BaseType.ListItem;
import com.geniusgithub.lookaround.util.CommonLog;
import com.geniusgithub.lookaround.util.LogFactory;
import com.umeng.analytics.MobclickAgent;
public class NavigationFragment extends Fragment implements OnItemClickListener{
private static final CommonLog log = LogFactory.createLog();
private Context mContext;
private View mView;
private ListView mListView;
private List<BaseType.ListItem> mDataList = new ArrayList<BaseType.ListItem>();
private NavChannelAdapter mAdapter;
private FragmentControlCenter mControlCenter;
private boolean loginStatus = false;
public NavigationFragment(){
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.e("NavigationFragment onCreate");
mContext = LAroundApplication.getInstance();
mControlCenter = FragmentControlCenter.getInstance(getActivity());
loginStatus = LAroundApplication.getInstance().getLoginStatus();
}
@Override
public void onDestroy() {
super.onDestroy();
log.e("NavigationFragment onDestroy");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
log.e("NavigationFragment onCreateView");
mView = inflater.inflate(R.layout.listview_layout, null);
return mView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
log.e("NavigationFragment onActivityCreated");
if (loginStatus){
setupViews();
initData();
}
}
private void setupViews(){
mListView = (ListView) mView.findViewById(R.id.listview);
mListView.setOnItemClickListener(this);
}
private void initData(){
mDataList = LAroundApplication.getInstance().getUserLoginResult().mDataList;
mAdapter = new NavChannelAdapter(mContext, mDataList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> adapter, View view, int pos, long arg3) {
BaseType.ListItem item = (ListItem) adapter.getItemAtPosition(pos);
// log.e("pos = " + pos + ", item = " + "\n" + item.getShowString());
HashMap<String, String> map = new HashMap<String, String>();
map.put(BaseType.ListItem.KEY_TYPEID, item.mTypeID);
map.put(BaseType.ListItem.KEY_TITLE, item.mTitle);
LAroundApplication.getInstance().onEvent("UMID0020", map);
CommonFragmentEx fragmentEx = mControlCenter.getCommonFragmentEx(item);
if (getActivity() == null)
return;
if (getActivity() instanceof MainLookAroundActivity) {
MainLookAroundActivity ra = (MainLookAroundActivity) getActivity();
ra.switchContent(fragmentEx);
}
}
}
|
package com.kodilla.stream.world;
import java.math.BigDecimal;
public final class City {
private final String simpleCity;
private final BigDecimal peopleQuantity;
public City(final String simpleCity, final BigDecimal peopleQuantity) {
this.simpleCity = simpleCity;
this.peopleQuantity = peopleQuantity;
}
public BigDecimal getPeopleQuantity() {
return peopleQuantity;
}
@Override
public String toString() {
return simpleCity ;
}
}
|
package Pro18.FourSum;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 四数之和转换为三数之和
*/
public class Solution
{
public List<List<Integer>> fourSum(int[] nums, int target)
{
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (nums.length < 4)
{
return null;
}
for (int i = 0; i < nums.length - 3; i++)
{
for (int j = i + 1; j < nums.length - 2; j++)
{
int p = j + 1;
int q = nums.length - 1;
while (p < q)
{
if (nums[i] + nums[j] + nums[p] + nums[q] == target)
{
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[p]);
list.add(nums[q]);
res.add(list);
while (p < q && nums[p] == nums[p + 1])
{
i++;
}
while (p < q && nums[q] == nums[q - 1])
{
q--;
}
}
if (nums[i] + nums[j] + nums[p] + nums[q] < target)
{
p++;
}
else
{
q--;
}
}
while (j < nums.length - 2 && nums[j] == nums[j + 1])
{
j++;
}
}
while (i < nums.length - 3 && nums[i] == nums[i + 1])
{
i++;
}
}
return res;
}
} |
package com.ggwork.net.socket;
import java.util.LinkedList;
import java.util.Queue;
import android.util.Log;
/**
* 消息发送类
*
* @author zw.Bai
*
*/
public class Sender extends Thread {
private boolean stop;
private CimSocket socket;
private Object event = new Object();
private Queue<String> queue = new LinkedList<String>();
public Sender(CimSocket socket) {
this.socket = socket;
this.start();
}
public void send(String msg) {
synchronized (event) {
String message = msg + "\0";
Log.d("send", message);
queue.offer(message);
event.notifyAll();
}
}
public void run() {
while (!stop) {
try {
synchronized (event) {
if (queue.isEmpty()) {
event.wait();
}
}
} catch (Exception e) {
e.printStackTrace();
isStop();
}
try {
if (socket.isConnected()) {
while (!queue.isEmpty()) {
socket.write(queue.poll());
}
} else {
Log.d("connectStart", "socket准备重连");
if (!queue.isEmpty()) {
queue.clear();
socket.connect();
}
}
} catch (Exception e) {
e.printStackTrace();
isStop();
}
}
}
private void isStop() {
if (!stop) {
socket.close();
}
}
public void termniate() {
stop = true;
queue.clear();
// notify();
}
}
|
/*
* 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 modelo.bean;
/**
*
* @author DTI
*/
public class Funcionario {
private Integer matricula;
private String nome;
private String setor;
private String cargo;
private String lider;
private byte[] imagem;
private byte[] biometria;
public String getLider() {
return lider;
}
public void setLider(String lider) {
this.lider = lider;
}
public byte[] getBiometria() {
return biometria;
}
public void setBiometria(byte[] biometria) {
this.biometria = biometria;
}
public byte[] getImagem() {
return imagem;
}
public void setImagem(byte[] imagem) {
this.imagem = imagem;
}
/**
* @return the matricula
*/
public Integer getMatricula() {
return matricula;
}
/**
* @param matricula the matricula to set
*/
public void setMatricula(Integer matricula) {
this.matricula = matricula;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the setor
*/
public String getSetor() {
return setor;
}
/**
* @param setor the setor to set
*/
public void setSetor(String setor) {
this.setor = setor;
}
/**
* @return the cargo
*/
public String getCargo() {
return cargo;
}
/**
* @param cargo the cargo to set
*/
public void setCargo(String cargo) {
this.cargo = cargo;
}
}
|
package com.gome.manager.domain;
/**
*
* 会议投票结果实体类.
*
* <pre>
* 修改日期 修改人 修改原因
* 2015年11月6日 caowei 新建
* </pre>
*/
public class MeetingVoteResult {
//ID
private Long id;
//名称
private String num;
//签到时间
private String auswer;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getAuswer() {
return auswer;
}
public void setAuswer(String auswer) {
this.auswer = auswer;
}
}
|
package com.practice;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Mousemovement {
static WebDriver driver;
static String baseURL="https://www.hdfc.com/";
static String expectedurl="./drivers/chromedriver.exe";
static String expectedurls="./drivers/geckodriver.exe";
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",expectedurl);
driver = new ChromeDriver();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get(baseURL);
driver.findElement(By.id("navbarDropdown")).click();
Actions act1=new Actions(driver);
WebElement we=driver.findElement(By.linkText("For Home Loans"));
act1.moveToElement(we).perform();
System.out.println("Test case one Pass");
WebElement customerlogin=driver.findElement(By.linkText("Customer Login"));
Actions act2=new Actions(driver);
act2.moveToElement(customerlogin).perform();
System.out.println("Test case two pass");
driver.quit();
}
}
|
package net.kalpas.pitta.repository;
import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Value;
public abstract class AbstractMongoDbTest {
/**
* please store Starter or RuntimeConfig in a static final field
* if you want to use artifact store caching (or else disable caching)
*/
private static final MongodStarter starter = MongodStarter.getDefaultInstance();
private MongodExecutable mongodExe;
private MongodProcess mongod;
@Value("${mongo.embedded.port}")
private int port;
@Before
public void setUp() throws Exception {
mongodExe = starter.prepare(new MongodConfigBuilder()
.version(Version.Main.PRODUCTION)
.net(new Net(port, Network.localhostIsIPv6()))
.build());
mongod = mongodExe.start();
}
@After
public void tearDown() throws Exception {
mongod.stop();
mongodExe.stop();
}
}
|
/*
* @lc app=leetcode.cn id=138 lang=java
*
* [138] 复制带随机指针的链表
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
// <head,newNode>
Map<Node, Node> map = new HashMap<>();
public Node copyRandomList(Node head) {
if (head == null)
return null;
// 如果之前已经拷贝过该节点,则从map直接取出该节点的拷贝
if (map.containsKey(head))
return map.get(head);
Node newNode = new Node(head.val);
// 必须先将其加入map,再对newNode进行赋值。
map.put(head, newNode);
newNode.next = copyRandomList(head.next);
newNode.random = copyRandomList(head.random);
return newNode;
}
}
// @lc code=end
|
package controller;
import java.util.ArrayList;
import java.util.Calendar;
import model.ReplyWesternDTO;
public class ReplyWesternController {
private ArrayList<ReplyWesternDTO> list;
private int id;
public ReplyWesternController() {
id = 1;
list = new ArrayList<>();
ReplyWesternDTO r1 = new ReplyWesternDTO();
r1.setId(id++);
r1.setFoodId(1);
r1.setWriterId(1);
r1.setContent("나도 알고 있는 건데;;;");
r1.setWrittenDate(Calendar.getInstance());
list.add(r1);
r1 = new ReplyWesternDTO();
r1.setId(id++);
r1.setFoodId(2);
r1.setWriterId(2);
r1.setContent("구독 좋아요 즐겨찾기 부탁합니다.");
r1.setWrittenDate(Calendar.getInstance());
list.add(r1);
}
public ReplyWesternDTO selectOne(int id) {
for (ReplyWesternDTO r : list) {
if (r.getId() == id) {
return r;
}
}
return null;
}
// 푸드 id 받아서 해당 id 값과 일치하도록 하는 메소드
public ArrayList<ReplyWesternDTO> selectById(int foodId) {
ArrayList<ReplyWesternDTO> temp = new ArrayList<>();
for (ReplyWesternDTO r : list) {
if (r.getFoodId() == foodId) {
temp.add(r);
}
}
return temp;
}
public void add(ReplyWesternDTO r) {
r.setId(id++);
r.setWrittenDate(Calendar.getInstance());
list.add(r);
}
public void delete(ReplyWesternDTO r) {
list.remove(r);
}
// validateUserId
public boolean validateWriterId(int writerId) {
for(ReplyWesternDTO r : list) {
if(writerId == r.getWriterId()) {
return true;
}
}
return false;
}
}
|
package com.gestion.service.impression;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import com.gestion.entity.Bonlivraison;
import com.gestion.entity.CommandeFournisseur;
import com.gestion.entity.Livraison;
import com.gestion.service.ServiceBonLivraison;
import com.gestion.service.ServiceClientCortex2i;
import com.gestion.service.ServiceCommandeFournisseur;
import com.gestion.service.ServiceLivraison;
import com.itextpdf.text.Font;
import fr.cortex2i.utils.HibernateUtils;
/**
* Servlet implementation class ServletBonLivaison
*/
@WebServlet("/ServletBonLivaison")
public class ServletBonLivaison extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServletBonLivaison() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Session s = HibernateUtils.getSession();
Enumeration<String> lcc = request.getParameterNames();
ArrayList<Livraison> list = new ArrayList<Livraison>();
Bonlivraison bl = new Bonlivraison();
ArrayList<Bonlivraison> listBl = new ArrayList<Bonlivraison>();
listBl = ServiceBonLivraison.listeBonLivraison(s);
Integer num = new Integer(listBl.size() + 1);
String chaineini = "BL_";
String numBon = null ;
num = num + 1000 ;
numBon = String.valueOf(num);
numBon = chaineini + numBon ;
Livraison l =null;
while(lcc.hasMoreElements())
{
l = new Livraison();
String id = lcc.nextElement();
l.setIdLivraison(Integer.parseInt(id));
l = ServiceLivraison.rechercheLivraison(s, l);
list.add(l);
}
bl.setNumBonLivraison(numBon);
ServiceBonLivraison.addBonLivraison(s , bl);
bl = new Bonlivraison();
bl.setNumBonLivraison(numBon);
bl = ServiceBonLivraison.rechercheBonLivraison(s , bl);
for(Livraison l1 : list)
{
Livraison l2 = new Livraison();
l2 = l1 ;
l2.setBonlivraison(bl);
ServiceLivraison.update(s, l2);
}
String logo = request.getSession().getServletContext().getRealPath("/LogoCortexHD.jpg");
new HeaderFooterBonLivraison(bl , l , list , response , logo , Font.FontFamily.HELVETICA);
s.close();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
|
package com.forecast.weather.http.response;
import com.forecast.weather.http.model.Main;
import com.forecast.weather.http.model.Weather;
import java.util.List;
/**
* Created by Aleksei Romashkin
* on 03/02/16.
*/
public class CurrentWeather {
public List<Weather> weather;
public Main main;
public String name;
public String id;
}
|
package com.evjeny.hackersimulator.model;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.evjeny.hackersimulator.game.Task;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;
/**
* Created by evjeny on 11.03.2018 13:04.
*/
public class TaskDownloader {
private Context context;
private RequestQueue queue;
private File mainDir;
private File mainFile;
private File hashFile;
private final String hashTag = "hash";
private final String hashUrl = "http://silvertests.ru/XML/GetQuestionsHashPython.ashx";
private final String tasksUrl = "http://silvertests.ru/XML/GetQuestionsPython.ashx";
public String netHash = null;
public TaskDownloader(Context context) {
this.context = context;
mainDir = new File(context.getFilesDir(), "tasks");
if (!mainDir.exists()) mainDir.mkdir();
mainFile = new File(mainDir, "main.xml");
hashFile = new File(mainDir, "hash.xml");
queue = QueueSingleton.getInstance(context.getApplicationContext()).getRequestQueue();
}
public void makeHashRequest(final resInt ri) {
StringRequest hashRequest = new StringRequest(Request.Method.GET, hashUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
netHash = response;
ri.good();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ri.error();
}
});
queue.add(hashRequest);
}
public boolean need2dl(String hashXml) throws IOException {
boolean hashFileExists = hashFile.exists();
boolean mainFileExists = mainFile.exists();
logd("Hash file exists:", hashFileExists);
logd("Main file exists:", mainFileExists);
if (!hashFileExists || !mainFileExists) return true;
String hashFileContent = readFile(hashFile);
logd("Hash file content:", hashFileContent);
logd("Internet content:", hashXml);
boolean hashesAreEqual = hashXml.equals(hashFileContent);
logd("Hashes are equal:", hashesAreEqual);
return !hashesAreEqual;
}
public void downloadFile(final resInt ri) {
StringRequest tasksRequest = new StringRequest(Request.Method.GET, tasksUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
logd("Got file:", response);
writeTask(response.trim());
logd("File has been written: " + mainFile.exists());
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
ri.good();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
ri.error();
}
});
queue.add(tasksRequest);
}
private String readFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append('\n');
}
reader.close();
return builder.toString();
}
private void writeFile(File file, String content) throws IOException {
FileOutputStream fos = new FileOutputStream(file);
fos.write(content.getBytes());
fos.close();
}
private void writeTask(String content) throws IOException, XmlPullParserException {
content = content.replaceAll("<span .*?>", "")
.replaceAll("<\\/span?>", "")
.replaceAll("<br .*?\\/>", "");
FileOutputStream fos = new FileOutputStream(mainFile);
fos.write(content.getBytes());
fos.close();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(content));
int eventType = parser.getEventType();
ArrayList<Task> tasks = new ArrayList<>();
String name = null, text = null;
long id = 0;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
switch (parser.getName()) {
case "task":
name = parser.getAttributeValue(null, "name")
.replace("![CDATA[", "")
.replace("]]", "");
id = Long.parseLong(parser.getAttributeValue(null, "id"));
break;
case "text":
text = parser.nextText();
break;
}
} else if (parser.getEventType() == XmlPullParser.END_TAG) {
switch (parser.getName()) {
case "task":
tasks.add(new Task(name, id, text));
break;
}
}
eventType = parser.next();
}
parser = null;
for (Task task : tasks) {
File currentFile = new File(mainDir, task.name);
FileOutputStream tfos = new FileOutputStream(currentFile);
tfos.write(task.toString().getBytes());
tfos.close();
logd("Wrote file:", currentFile.getAbsolutePath(), ", content: ", task);
}
}
private void logd(Object... args) {
StringBuilder builder = new StringBuilder();
for (Object arg : args) {
builder.append(arg);
builder.append(" ");
}
Log.d("FileDownloader", builder.toString());
}
public interface resInt {
void good();
void error();
}
}
|
package com.sai.prog;
public class Vehicle implements InterfaceExample,Interface2{
public void move(){
System.out.println("Vehicle moves with average speed of "+AVG_SPEED);
}
public void Roll(){
System.out.println("The tyre of the vehicle can move per minute is "+ROLLSPER_MINUTE);
}
public void Start(){
if(GO){
System.out.println("The vehicle is moving on:"+Gears);
}else{
System.out.println("vehicle is in halt");
}
}
public boolean Obstacle(){
System.out.println("there is a obstacle in front emergency <<stop>>");
for(int i=100;i<0;i-=20){
System.out.println(i);
}
return true;
}
public boolean noObstacle(){
System.out.println("no obsatcles proceed");
return false;
}
public static void main(String[] args) {
String str3=str.concat(str2);
System.out.println("Vehicle is going to start from");
for(int i=0;i<=200;i+=50){
System.out.println(i);
}
Vehicle v=new Vehicle();
System.out.println(str3);
System.out.println(str4.compareTo(str5));
v.move();
v.Roll();
v.Start();
//v.Obstacle();
System.out.println(v.noObstacle());
System.out.println(v.Obstacle());
}
}
|
package com.yidao.module_lib.config;
/**
* Created by xiaochan on 2017/6/19.
*/
public class Config {
// public static final String VERSION = "v1.0.1";
public static final boolean ISDEBUG = true;
// public static final String ENVIRONMENT = "dev"; // 项目环境:dev, test, prod
// public static final String path = "http://ofjj1t0ai.bkt.clouddn.com/";
public static boolean isPublish = true;
public static boolean PublishTag = false; // 编辑页面点编辑返回后 将改值设为true, 代表在编辑页面已经save了,发布页面不需要再次save,否则添加的mv音乐都没
public static boolean isOnclick=true;
}
|
package com.rev.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "teachers")
public class Teacher {
@Id
@Column(columnDefinition = "serial primary key")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int tid;
@Column(nullable = false)
private String fname;
@Column(nullable = false)
private String lname;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "tid", referencedColumnName = "rid")
private Room homeRoom;
@OneToMany(mappedBy = "homeRoomTeacher", fetch = FetchType.EAGER)
private Set<Student> homeRoomStudents;
public Teacher() { }
public Teacher(String fname, String lname, Room homeRoom) {
this.fname = fname;
this.lname = lname;
this.homeRoom = homeRoom;
}
//region Getters and Setters
public int getId() {
return tid;
}
public void setId(int tid) {
this.tid = tid;
}
public String getFName() {
return fname;
}
public void setFName(String fname) {
this.fname = fname;
}
public String getLName() {
return lname;
}
public void setLName(String lname) {
this.lname = lname;
}
public Room getHomeRoom() {
return homeRoom;
}
public void setHomeRoom(Room homeRoom) {
this.homeRoom = homeRoom;
}
@JsonIgnore
public Set<Student> getStudents() {
return homeRoomStudents;
}
@JsonIgnore
public void setStudents(Set<Student> homeRoomStudents) {
this.homeRoomStudents = homeRoomStudents;
}
//endregion
@Override
public String toString() {
return "Teacher{" +
"tid=" + tid +
", fname='" + fname + '\'' +
", lname='" + lname + '\'' +
", homeRoom=" + homeRoom +
'}';
}
}
|
import java.util.Scanner;
public class BTJavaSlack {
static boolean isPrime(int number) {
if (number == 2)
return true;
else if (number % 2 == 0)
return false;
else {
for (int i = 3; i < Math.sqrt(number); i += 2) {
if (number % i == 0)
return false;
}
return true;
}
}
static boolean checkSCP(double x) {
double a = Math.sqrt(x);
double b = a - Math.floor(a);
return (b==0);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập số:");
int n = sc.nextInt();
System.out.println("1.SNT?");
System.out.println("2.Chẵn hay lẻ?");
System.out.println("3.SCP");
System.out.println("4.EXIT");
int a = sc.nextInt();
switch (a) {
case 1:
if (isPrime(n)) {
System.out.println("SNT");
} else {
System.out.println("Ko phải SNT");
}
break;
case 2:
if (n % 2 == 0) {
System.out.println(n + " là số chẵn");
} else {
System.out.println(n + " là số lẻ");
}
break;
case 3:
if (checkSCP(n)){
System.out.println(n+" là SCP");
}else {
System.out.println(n+" ko phải SCP");
}
case 4:
break;
}
}
}
|
package com.gaoshin.cloud.web.job.bean;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class JobDependencyList {
private List<JobDependency> list = new ArrayList<JobDependency>();
public List<JobDependency> getList() {
return list;
}
public void setList(List<JobDependency> list) {
this.list = list;
}
}
|
/*
* CacheType.java
* Written 2013 by M Koch
* Copyright abandoned. This file is in the public domain.
*/
package testcachesim;
public enum CacheType {
ICACHE, DCACHE, BOTH, IGNORE
// 0. Läsning av data för att utföra en Load-instruktion.
// 1. Skrivning av data för att utföra en Store-instruktion.
// 2. Instruktionshämning.
// 3. Escape Record (ska ignoreras av simulatorn).
// 4. Flush Cache, som nollställer alla giltig-bitar i både
// instruktionscache och datacache.
}
|
package com.utils.redis.command;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.SetOperations;
/**
* Set Command Operations.extends RedisCommandOperation.
* <p>
* http://doc.redisfans.com/
* </p>
*
* @author memory 2017年5月11日 下午9:02:26
* @version V1.0
* @modificationHistory=========================逻辑或功能性重大变更记录
* @modify by user: {修改人} 2017年5月11日
* @modify by reason:{方法名}:{原因}
*/
public class DefaultCommandSetOperation extends DefaultCommandRedisOperation implements CommandSetOperation {
/**
* Interface SetOperations<K,V>. Redis set specific operations.
*/
protected SetOperations<String, String> setOps = super.opsForSet();
@Override
public Long sAdd(String key, String... members) {
return setOps.add(key, members);
}
@Override
public Long sCard(String key) {
return setOps.size(key);
}
@Override
public Set<String> sDiff(String key, String otherKey) {
return setOps.difference(key, otherKey);
}
@Override
public Set<String> sDiff(String key, Collection<String> otherKeys) {
return setOps.difference(key, otherKeys);
}
@Override
public Long sDiffStore(String destinationKey, String key, String otherKey) {
return setOps.differenceAndStore(key, otherKey, destinationKey);
}
@Override
public Long sDiffStore(String destinationKey, String key, Collection<String> otherKeys) {
return setOps.differenceAndStore(key, otherKeys, destinationKey);
}
@Override
public Set<String> sInter(String key, String otherKey) {
return setOps.intersect(key, otherKey);
}
@Override
public Set<String> sInter(String key, Collection<String> otherKeys) {
return setOps.intersect(key, otherKeys);
}
@Override
public Long sInterStore(String destinationKey, String key, String otherKey) {
return setOps.intersectAndStore(key, otherKey, destinationKey);
}
@Override
public Long sInterStore(String destinationKey, String key, Collection<String> otherKeys) {
return setOps.intersectAndStore(key, otherKeys, destinationKey);
}
@Override
public Boolean sisMember(String key, String member) {
return setOps.isMember(key, member);
}
@Override
public Set<String> sMembers(String key) {
return setOps.members(key);
}
@Override
public Boolean sMove(String source, String destination, String member) {
return setOps.move(source, member, destination);
}
@Override
public String sPop(String key) {
return setOps.pop(key);
}
@Override
public String sRandMember(String key) {
return setOps.randomMember(key);
}
@Override
public List<String> sRandMember(String key, long count) {
return setOps.randomMembers(key, count);
}
@Override
public Long sRem(String key, Object... members) {
return setOps.remove(key, members);
}
@Override
public Set<String> sUnion(String key, String otherKey) {
return setOps.union(key, otherKey);
}
@Override
public Set<String> sUnion(String key, Collection<String> otherKeys) {
return setOps.union(key, otherKeys);
}
@Override
public Long sUnionStore(String destination, String key, String otherKey) {
return setOps.unionAndStore(key, otherKey, destination);
}
@Override
public Long sUnionStore(String destination, String key, Collection<String> otherKeys) {
return setOps.unionAndStore(key, otherKeys, destination);
}
@Override
public Cursor<String> sScan(String key, ScanOptions options) {
return setOps.scan(key, options);
}
}
|
package PageObject;
import java.util.List;
import javax.xml.xpath.XPath;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import org.openqa.selenium.support.PageFactory;
public class LazadaHome {
private WebDriver driver;
public LazadaHome(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
@FindBy(xpath = "//div[@id=\"topActionHeader\"]//div[@class=\"lzd-nav-search\"]//input[@type=\"search\"]")
public WebElement txtSearch;
@FindBy(xpath = "//div[@id=\"topActionHeader\"]//div[@class=\"lzd-nav-search\"]//button")
public WebElement btnSearch;
@FindBy(xpath="//div[@class=\"lzd-nav-search\"]//form//div[contains(@class, \"suggest-list\")]//a[contains(@class, \"suggest-common\")]//b")
public List<WebElement> suggestLst;
@FindBy(xpath="//div[@data-qa-locator=\"general-products\" and @data-spm=\"list\"]//div[@class=\"c16H9d\"]//a")
public List<WebElement> searchtLst;
@FindBy(xpath="//div[@id=\"root\"]//li[contains(@class,\"ant-pagination-next\")]")
public WebElement nextPage;
@FindBy(xpath="//div[@id=\"root\"]//span[contains(text(),\"items found for\")]")
public WebElement noResultLbl;
}
|
package org.gracejvc.vanrin.controllers;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.gracejvc.vanrin.model.Admins;
import org.gracejvc.vanrin.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@Resource(name="adminService")
private AdminService adminService;
@RequestMapping("/home")
public String goHome(Model model,HttpServletRequest request){
List<Admins> admins = adminService.allAdmins();
Admins admin = (Admins) request.getSession().getAttribute("LOGGEDIN");
model.addAttribute("admins",admins);
model.addAttribute("admin",admin);
return "home";
}
}
|
package com.ifeng.recom.mixrecall.common.service.handler.remove;
import com.ifeng.recom.mixrecall.common.cache.FilterDocsCache;
import com.ifeng.recom.mixrecall.common.cache.LowTagInfoCache;
import com.ifeng.recom.mixrecall.common.cache.WeMediaSourceNameCache;
import com.ifeng.recom.mixrecall.common.constant.DocType;
import com.ifeng.recom.mixrecall.common.model.Document;
import com.ifeng.recom.mixrecall.common.model.request.MixRequestInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class SimpleCacheContaintsRemoveHandlerConfig {
@Autowired
private FilterDocsCache filterDocsCache;
@Autowired
private LowTagInfoCache lowTagInfoCache;
@Autowired
private WeMediaSourceNameCache weMediaSourceNameCache;
/**
* 过滤低品质文章,数据来源:张阳
*/
@Bean("idRemover")
public IItemRemoveHandler<Document> idRemover() {
return new IItemRemoveHandler<Document>() {
@Override
public boolean remove(MixRequestInfo info, Document item) {
return filterDocsCache.containsKey(item.getSimId());
}
@Override
public String handlerName() {
return "id";
}
};
}
/**
* 过滤审核low标签
*
* @return
*/
@Bean("lowTagRemover")
public IItemRemoveHandler<Document> lowTagRemover() {
return new IItemRemoveHandler<Document>() {
@Override
public boolean remove(MixRequestInfo info, Document item) {
return lowTagInfoCache.containsKey(item.getSimId());
}
@Override
public String handlerName() {
return "lowTag";
}
};
}
/**
* 过滤特定媒体名称
* 视频不用进行机构媒体过滤
*
* @return
*/
@Bean("sourceNameRemover")
public IItemRemoveHandler<Document> sourceNameRemover() {
return new IItemRemoveHandler<Document>() {
@Override
public boolean remove(MixRequestInfo info, Document item) {
return (
!DocType.VIDEO.getValue().equals(item.getDocType()) &&
!weMediaSourceNameCache.containsKey(item.getSource())
);
}
@Override
public String handlerName() {
return "sourceName";
}
};
}
}
|
package com.sample.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.sample.entity.Article;
import com.sample.form.PostForm;
import com.sample.service.PostService;
@Controller
public class PostController {
@Autowired
private PostService postService;
@RequestMapping(value = "/post", method = RequestMethod.GET)
public String post_form(
Model model,
@ModelAttribute("postForm")
PostForm postForm
) {
model.addAttribute("postForm", postForm);
return "post_form";
}
@RequestMapping(value = "/post/create", method = RequestMethod.POST)
public String post_create(
Model model,
RedirectAttributes redirectAttributes,
@ModelAttribute("postForm")
@Validated
PostForm postForm,
BindingResult result
) {
if(result.hasErrors()) {
model.addAttribute("postForm", postForm);
return "post_form";
}
redirectAttributes.addFlashAttribute("messageType", "success");
redirectAttributes.addFlashAttribute("message", "register successed");
postService.createArticle(postForm);
return "redirect:/admin";
}
@RequestMapping(value = "/post/edit/{id}", method = RequestMethod.GET)
public String post_edit(
Model model,
@PathVariable("id") int id,
@ModelAttribute("postForm")
PostForm postForm
) {
Optional<Article> resultArticle = postService.getArticleById(id);
if(resultArticle.isPresent()) {
model.addAttribute("postForm", new PostForm(resultArticle.get()));
return "post_form";
}
return "error/404";
}
@RequestMapping(value = "/post/delete/confirm/{id}", method = RequestMethod.GET)
public String post_delete_confirm(
Model model,
@PathVariable("id") int id
) {
Optional<Article> resultArticle = postService.getArticleById(id);
if(resultArticle.isPresent()) {
model.addAttribute("article", resultArticle.get());
return "delete_confirm";
}
return "error/404";
}
@RequestMapping(value = "/post/delete/complete", method = RequestMethod.POST)
public String post_delete_complete(
Model model,
RedirectAttributes redirectAttributes,
@ModelAttribute("id")
Integer id
) {
postService.deleteArticle(id);
redirectAttributes.addFlashAttribute("messageType", "success");
redirectAttributes.addFlashAttribute("message", "delete successed");
return "redirect:/admin";
}
} |
package com.example.SpringApp.controller;
import com.example.SpringApp.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDetailsRepo extends JpaRepository<User, String> {
}
|
package com.xuchengpu.shoppingmall.home.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.xuchengpu.shoppingmall.R;
import com.xuchengpu.shoppingmall.home.bean.HomeBean;
import com.xuchengpu.shoppingmall.utils.Constants;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by 许成谱 on 2017/2/25 16:20.
* qq:1550540124
* for:
*/
public class RecommendGridAdapter extends BaseAdapter {
private final Context mContext;
private final List<HomeBean.ResultBean.RecommendInfoBean> recommend_info;
public RecommendGridAdapter(Context mContext, List<HomeBean.ResultBean.RecommendInfoBean> recommend_info) {
this.mContext = mContext;
this.recommend_info = recommend_info;
}
@Override
public int getCount() {
return recommend_info.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = View.inflate(mContext, R.layout.recommand_grid, null);
viewHolder=new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvName.setText(recommend_info.get(position).getName());
viewHolder.tvPrice.setText(recommend_info.get(position).getCover_price());
Glide.with(mContext).load(Constants.BASE_URL_IMAGE+recommend_info.get(position).getFigure()).into(viewHolder.ivRecommend);
return convertView;
}
class ViewHolder {
@BindView(R.id.iv_recommend)
ImageView ivRecommend;
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.tv_price)
TextView tvPrice;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
|
package symbolic;
/**
* @file Binary.java
* Binary is a part of the Sexpr hierarchy (see Sexpr.java).
* Binary is an abstract class that is responsible for building binary mathematical expressions.
* A binary expression has a left and a right symbolic expression. The binary expressions are addition, subtraction,
* multiplication, division and asssignment.
*
* @author Nurhussen Saleh
* @author Christoffer Gustafsson
*/
public abstract class Binary extends Sexpr{
protected Sexpr left;
protected Sexpr right;
/**
* @brief Constructs a binary expression.
* @param left The left symbolic expression.
* @param right The right symbolic expression.
*/
public Binary(Sexpr left, Sexpr right){
this.left = left;
this.right = right;
}
/**
* @brief Creates a string that represents a binary expression. Examples:
* An addition with a left expression '5.0' and right expression '4.0' would be printed out as:
* @code 5.0+4.0
* @endcode
* A multiplication with a left expression 'x' and right expression '4.0' would be printed out as:
* @code x*4.0
* @endcode
* @return Returns the string.
*/
public String toString(){
if(this.priority == 1)
return "(" + left + getName() + right + ")";
return left + getName() + right;
}
@Override
/**
* signal this Sexpr for later parenthesis evaluation
*/
public void priority(){
super.parenthesis = true;
}
@Override
public boolean hasLeftBinary(){ return left.isBinary(); }
@Override
public boolean hasRightBinary() { return right.isBinary(); }
@Override
public boolean isBinary() { return true; }
@Override
public void evaluateParenthesis() {
if(this.left.parenthesis && this.left.isBinary() && this.priority < this.left.priority){
this.left.priority = 1;
}
if(this.right.parenthesis && this.right.isBinary() && this.priority < this.right.priority){
this.right.priority = 1;
}
this.left.evaluateParenthesis();
this.right.evaluateParenthesis();
}
}
|
package net.tanpeng.database.jdbc;
import java.sql.*;
/**
* Created by peng.tan on 17/10/20.
*/
public class SelectDemo {
public static void main(String[] args) throws SQLException {
String serverName = "127.0.0.1";
int port = 3306;
String databaseName = "";
String dbname = "";
String url = String.format("jdbc:mysql://%s:%d/%s", serverName, port, databaseName);
String username = "";
String password = "";
String sql = String.format("select * from %s where id>%s and id<=%s", dbname,20,30);
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.last()){
System.out.println("lenth = "+resultSet.getRow());
System.out.println(resultSet.getString(1));
System.out.println(resultSet.getRow());
System.out.println();
resultSet.beforeFirst();
}
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
|
package com.capstone.videoeffect;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.capstone.videoeffect.utils.ImageLoadingUtils;
import com.edmodo.cropper.CropImageView;
public class CropActivity extends Activity implements OnClickListener {
RelativeLayout back_main;
LinearLayout btnCrop16_9;
LinearLayout btnCrop4_3;
LinearLayout btnCrop4_5;
LinearLayout btnCrop5_6;
LinearLayout btnCropCustom;
LinearLayout btnCropOriginal;
LinearLayout btnCropSquare;
CropImageView cropView;
TextView custom_size;
TextView org_size;
RelativeLayout rLayout;
TextView size4_3;
TextView size_16_9;
TextView size_4_5;
TextView size_5_6;
TextView square_size;
ImageLoadingUtils utils;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
Log.d("myname1", String.valueOf(PhotoHomeActivity.bitmap.getHeight()));
Log.d("myname2", String.valueOf(PhotoHomeActivity.bitmap.getWidth()));
this.cropView = (CropImageView) findViewById(R.id.CropImageView);
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(1, 1);
this.utils = new ImageLoadingUtils(getApplicationContext());
this.cropView.setImageBitmap(PhotoHomeActivity.bitmap);
this.rLayout = (RelativeLayout) findViewById(R.id.next_main);
this.back_main = (RelativeLayout) findViewById(R.id.back_main);
this.org_size = (TextView) findViewById(R.id.org_size);
this.square_size = (TextView) findViewById(R.id.square_size);
this.custom_size = (TextView) findViewById(R.id.custom_size);
this.size_4_5 = (TextView) findViewById(R.id.size_4_5);
this.size_5_6 = (TextView) findViewById(R.id.size_5_6);
this.size_16_9 = (TextView) findViewById(R.id.size_16_9);
this.size4_3 = (TextView) findViewById(R.id.size4_3);
this.btnCropOriginal = (LinearLayout) findViewById(R.id.btnCropOriginal);
this.btnCropSquare = (LinearLayout) findViewById(R.id.btnCropSquare);
this.btnCrop4_5 = (LinearLayout) findViewById(R.id.btnCrop4_5);
this.btnCrop5_6 = (LinearLayout) findViewById(R.id.btnCrop5_6);
this.btnCrop4_3 = (LinearLayout) findViewById(R.id.btnCrop4_3);
this.btnCropCustom = (LinearLayout) findViewById(R.id.btnCropCustom);
this.btnCrop16_9 = (LinearLayout) findViewById(R.id.btnCrop16_9);
back_main.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CropActivity.this.onBackPressed();
}
});
rLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
PhotoHomeActivity.bitmap = CropActivity.this.cropView.getCroppedImage();
CropActivity.this.startActivity(new Intent(CropActivity.this, ImageEditingActivity.class));
CropActivity.this.finish();
}
});
}
protected void onResume() {
super.onResume();
}
public boolean isOnline() {
NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
return false;
}
return true;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCropOriginal:
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(PhotoHomeActivity.bitmap.getWidth(), PhotoHomeActivity.bitmap.getHeight());
changebackground(R.id.btnCropOriginal);
return;
case R.id.btnCropSquare:
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(1, 1);
changebackground(R.id.btnCropSquare);
return;
case R.id.btnCropCustom:
this.cropView.setFixedAspectRatio(false);
changebackground(R.id.btnCropCustom);
return;
case R.id.btnCrop4_5:
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(4, 5);
changebackground(R.id.btnCrop4_5);
return;
case R.id.btnCrop5_6:
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(5, 6);
changebackground(R.id.btnCrop5_6);
return;
case R.id.btnCrop16_9:
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(16, 9);
changebackground(R.id.btnCrop16_9);
return;
case R.id.btnCrop4_3:
this.cropView.setFixedAspectRatio(true);
this.cropView.setAspectRatio(4, 3);
changebackground(R.id.btnCrop4_3);
return;
default:
return;
}
}
private void changebackground(int id) {
this.btnCropOriginal.setBackgroundColor(0);
this.btnCropSquare.setBackgroundColor(0);
this.btnCrop4_5.setBackgroundColor(0);
this.btnCrop5_6.setBackgroundColor(0);
this.btnCrop4_3.setBackgroundColor(0);
this.btnCrop16_9.setBackgroundColor(0);
this.btnCropCustom.setBackgroundColor(0);
this.org_size.setTextColor(getResources().getColor(R.color.crop_op_text));
this.square_size.setTextColor(getResources().getColor(R.color.crop_op_text));
this.custom_size.setTextColor(getResources().getColor(R.color.crop_op_text));
this.size_4_5.setTextColor(getResources().getColor(R.color.crop_op_text));
this.size_5_6.setTextColor(getResources().getColor(R.color.crop_op_text));
this.size_16_9.setTextColor(getResources().getColor(R.color.crop_op_text));
this.size4_3.setTextColor(getResources().getColor(R.color.crop_op_text));
switch (id) {
case R.id.btnCropOriginal:
this.btnCropOriginal.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.org_size.setTextColor(-1);
return;
case R.id.btnCropSquare:
this.btnCropSquare.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.square_size.setTextColor(-1);
return;
case R.id.btnCropCustom:
this.btnCropCustom.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.custom_size.setTextColor(-1);
return;
case R.id.btnCrop4_5:
this.btnCrop4_5.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.size_4_5.setTextColor(-1);
return;
case R.id.btnCrop5_6:
this.btnCrop5_6.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.size_5_6.setTextColor(-1);
return;
case R.id.btnCrop16_9:
this.btnCrop16_9.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.size_16_9.setTextColor(-1);
return;
case R.id.btnCrop4_3:
this.btnCrop4_3.setBackgroundColor(getResources().getColor(R.color.crop_op_bg));
this.size4_3.setTextColor(-1);
return;
default:
return;
}
}
}
|
package aula_0401;
public abstract class CalculadoraTradicional extends Object implements ICalculadora, ICalculadora2 {
private String nome;
private int versao;
public CalculadoraTradicional(String nome, int versao){
this.nome = nome;
this.versao = BASE;
}
public abstract double divide(int x, int y);
public double potencia(int x, int base) {
return 0;
}
public int soma(int x, int y) {
return 0;
}
public double geraAleatorio(){
return 0;
}
@Override
public double multiplica(double x, double y) {
// TODO Auto-generated method stub
return 0;
}
@Override
public double novoMetodo() {
// TODO Auto-generated method stub
return 0;
}
}
|
package com.bharath.tasks.autoscout24;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Autoscout24Application {
public static void main(String[] args) {
SpringApplication.run(Autoscout24Application.class, args);
}
}
|
package org.lfy.jwt.interceptor;
import io.jsonwebtoken.Claims;
import lfy.constants.BaseConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lfy.jwt.config.JwtConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* JwtAuthTokenInterceptor
* 配置Token拦截器
* ① :preHandle:调用Controller某个方法之前
* ② :postHandle:Controller之后调用,视图渲染之前,如果控制器Controller出现了异常,则不会执行此方法
* ③ :afterCompletion:不管有没有异常,这个afterCompletion都会被调用,用于资源清理
* ④ :@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
* 备注 : Spring中Constructor、@Autowired、@PostConstruct的顺序
*
* @author lfy
* @date 2021/3/29
**/
@Slf4j
@Component
public class JwtAuthTokenInterceptor extends HandlerInterceptorAdapter {
/**
* URL 缓存
*/
private static final Map<String, Boolean> URI_CACHE_MAP = new ConcurrentHashMap<>();
/**
* permit url
*/
private List<String> permitAllUriList = new ArrayList<>();
/**
* auth uri
*/
private List<String> authAllUriList = new ArrayList<>();
@Autowired
private JwtConfig jwtConfig;
@PostConstruct
public void init() {
this.permitAllUriList = Arrays.asList(jwtConfig.getPermitAll().split(BaseConstants.SPLIT_COMMA));
this.authAllUriList = Arrays.asList(jwtConfig.getAuthUri().split(BaseConstants.SPLIT_COMMA));
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
if (!isAllowUri(request)) {
final String token = request.getHeader(jwtConfig.getToken());
log.info("Auth Token :【{}】", token);
if (StringUtils.isBlank(token)) {
throw new RuntimeException("Unable to get JWT Token");
}
if (!jwtConfig.validateToken(token)) {
throw new RuntimeException("Invalid Token");
}
Claims claims = jwtConfig.getTokenClaim(token);
request.setAttribute("username", claims.getSubject());
}
return true;
}
private boolean isAllowUri(HttpServletRequest request) {
String uri = request.getServletPath();
if (URI_CACHE_MAP.containsKey(uri)) {
//缓存中有数据,直接取
return URI_CACHE_MAP.get(uri);
}
boolean flag = checkRequestUri(uri);
//将数据存入缓存
URI_CACHE_MAP.put(uri, flag);
return flag;
}
private boolean checkRequestUri(String uri) {
AtomicBoolean filter = new AtomicBoolean(true);
final PathMatcher pathMatcher = new AntPathMatcher();
permitAllUriList.forEach(e -> {
if (pathMatcher.match(e, uri)) {
// permit all的链接直接放行
filter.set(true);
}
});
authAllUriList.forEach(e -> {
if (pathMatcher.match(e, uri)) {
filter.set(false);
}
});
return filter.get();
}
}
|
class birtwise_lift_shift_opr
{
public static void main (String args[])
{
byte a=5,b=2;
a=(byte)(a<<1);//bit liftshift
System.out.println("Sefted value in var a:-"+a);
b=(byte)(b<<4);//bit lift shift
System.out.println("Sefited value in var b:-"+b);
}
} |
/* ~~ The ExcelExamplePOI is part of BusinessProfit. ~~
*
* The BusinessProfit's classes and any part of the code
* cannot be copied/distributed without
* the permission of Sotiris Doudis
*
* Github - RiflemanSD - https://github.com/RiflemanSD
*
* Copyright © 2016 Sotiris Doudis | All rights reserved
*
* License for BusinessProfit project - in GREEK language
*
* Οποιοσδήποτε μπορεί να χρησιμοποιήσει το πρόγραμμα για προσωπική του χρήση.
* Αλλά απαγoρεύεται η πώληση ή διακίνηση του προγράμματος σε τρίτους.
*
* Aπαγορεύεται η αντιγραφή ή διακίνηση οποιοδήποτε μέρος του κώδικα χωρίς
* την άδεια του δημιουργού.
* Σε περίπτωση που θέλετε να χρεισημοποιήσετε κάποια κλάση ή μέρος του κώδικα.
* Πρέπει να συμπεριλάβεται στο header της κλάσης τον δημιουργό και link στην
* αυθεντική κλάση (στο github).
*
* ~~ Information about BusinessProfit project - in GREEK language ~~
*
* Το BusinessProfit είναι ένα project για την αποθήκευση και επεξεργασία
* των εσόδων/εξόδων μίας επιχείρησης με σκοπό να μπορεί ο επιχειρηματίας να καθορήσει
* το καθαρό κέρδος της επιχείρησης. Καθώς και να κρατάει κάποια σημαντικά
* στατιστικά στοιχεία για τον όγκο της εργασίας κτλ..
*
* Το project δημιουργήθηκε από τον Σωτήρη Δούδη. Φοιτητή πληροφορικής του Α.Π.Θ
* για προσωπική χρήση. Αλλά και για όποιον άλλον πιθανόν το χρειαστεί.
*
* Το project προγραμματίστηκε σε Java (https://www.java.com/en/download/).
* Με χρήση του NetBeans IDE (https://netbeans.org/)
* Για να το τρέξετε πρέπει να έχετε εγκαταστήσει την java.
*
* Ο καθένας μπορεί δωρεάν να χρησιμοποιήσει το project αυτό. Αλλά δεν επιτρέπεται
* η αντιγραφή/διακήνηση του κώδικα, χωρίς την άδεια του Δημιουργού (Δείτε την License).
*
* Github - https://github.com/RiflemanSD/BusinessProfit
*
*
* Copyright © 2016 Sotiris Doudis | All rights reserved
*/
package org.riflemansd.businessprofit.excel;
import java.awt.Desktop;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
/** <h1>ExcelExamplePOI</h1>
*
* <p></p>
*
* <p>Last Update: 29/01/2016</p>
* <p>Author: <a href=https://github.com/RiflemanSD>RiflemanSD</a></p>
*
* <p>Copyright © 2016 Sotiris Doudis | All rights reserved</p>
*
* @version 1.0.7
* @author RiflemanSD
*/
public class ExcelExamplePOI {
public static void main(String[] args) throws Throwable {
SXSSFWorkbook wb = new SXSSFWorkbook(1000); // keep 100 rows in memory, exceeding rows will be flushed to disk
if (wb.getNumberOfSheets() == 0) {
wb.createSheet("MySheet");
}
Sheet sh = wb.getSheetAt(0);
Row row = sh.createRow(3);
for (int i = 0; i < 10; i++) {
Cell cell = row.createCell(i);
//String address = new CellReference(cell).formatAsString();
cell.setCellValue("Καλημέρα " + i);
//row.setHeightInPoints(50);
//sh.setColumnWidth(5, 1200); //4, 33 pixels
wb.getSheetAt(0).autoSizeColumn(i);
}
FileOutputStream out = new FileOutputStream("test.xlsx");
wb.write(out);
out.close();
// dispose of temporary files backing this workbook on disk
wb.dispose();
Desktop.getDesktop().open(new File("test.xlsx"));
}
}
|
package com.santander;
import com.santander.controller.AccountController;
import com.santander.entity.AccountDto;
import com.santander.entity.Account;
import com.santander.exception.AccountNotFoundResponse;
import com.santander.exception.InvalidAccountIdResponse;
import com.santander.service.AccountServiceImpl;
import org.junit.Rule;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Collections;
import java.util.List;
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@SpringBootTest
@RunWith(SpringRunner.class)
public class AccountTest {
@Autowired
private AccountController accountController;
@Autowired
private Account account;
@Rule
public ExpectedException exception = ExpectedException.none();
private ResponseEntity<Account> responseAccount;
private ResponseEntity<Object> responseObject;
@Autowired
private AccountServiceImpl accountServiceImpl;
@Test
public void testGetAccountByIdSuccess() {
ResponseEntity<AccountDto> accountDto = accountController.getAccountById(1L);
assertEquals(accountDto.getBody().getName(), "leonardo");
}
@Test(expected = InvalidAccountIdResponse.class)
public void testGetAccountByIdWithInvalidId() {
ResponseEntity<AccountDto> accountDto = accountController.getAccountById(-1L);
}
@Test(expected = AccountNotFoundResponse.class)
public void testGetAccountByIdWithNonexistentAccount() {
ResponseEntity<AccountDto> accountDto = accountController.getAccountById(5L);
}
@Test
public void testGetAllAccountsSuccess() {
accountController.setAccountServiceImpl(accountServiceImpl);
assertNotEquals(accountController.getAllAccounts().getBody().size(), 0);
}
@Test
public void testGetAllAccountsNoRecordsFound() {
accountServiceImpl = mock(AccountServiceImpl.class);
when(accountServiceImpl.getAllAccounts()).thenReturn(Collections.emptyList());
accountController.setAccountServiceImpl(accountServiceImpl);
ResponseEntity<List<AccountDto>> accountList = accountController.getAllAccounts();
assertTrue(accountList.getBody().isEmpty());
}
@Test(expected = AccountNotFoundResponse.class)
public void testUpdateAccountByIdWithNonexistentAccount() {
account.setId(4L);
account.setName("leonardo");
account.setSurname("davinci");
account.setAge(99);
accountController.updateAccountById(account, account.getId());
}
@Test
public void testUpdateAccountByIdSuccess() {
account.setId(3L);
account.setName("michael");
account.setSurname("jackson");
account.setAge(99);
responseAccount = accountController.updateAccountById(account, account.getId());
assertEquals(responseAccount.getStatusCode().value(),200);
ResponseEntity<AccountDto> accountDto = accountController.getAccountById(account.getId());
assertEquals(accountDto.getBody().getName(),account.getName());
}
@Test(expected = AccountNotFoundResponse.class)
public void testDeleteAccountByIdNonexistingId() {
responseObject = accountController.deleteAccountById(5L);
}
@Test
public void testDeleteAccountByIdSuccess() {
responseObject = accountController.deleteAccountById(3L);
assertEquals("Deleting record",responseObject.getStatusCode().value(),200);
/* Checking deleted record */
exception.expect( AccountNotFoundResponse.class);
ResponseEntity<AccountDto> accountDto = accountController.getAccountById(3L);
}
}
|
package com.ziaan.library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* Sms의 전송내역을 기록 조회 하는 빈
* @author Seunghyeon
*
*/
public class SmsLogBean {
private ConfigSet conf;
private int row;
private int adminrow;
public SmsLogBean(){
try {
conf = new ConfigSet();
} catch (Exception e) {
e.printStackTrace();
}
row = Integer.parseInt(conf.getProperty("page.bulletin.row")); // 이 모듈의 페이지당 row 수를 셋팅한다
adminrow = Integer.parseInt(conf.getProperty("page.bulletin.adminrow")); // 이 모듈의 페이지당 row 수를 셋팅한다
}
/**
*
* @param box
* @return
* @throws Exception
*/
public List getSMSLogList(RequestBox box)throws Exception{
List logList=new ArrayList();
DBConnectionManager connMgr=null;
ListSet ls=null;
String sql=null;
DataBox dbox=null;
int v_pageno = box.getInt("p_pageno");
String v_startdt=FormatDate.getFormatDate(box.getString("p_startdt"), "yyyyMMdd") ;
String v_enddt=FormatDate.getFormatDate(box.getString("p_enddt"),"yyyyMMdd");
try {
connMgr=new DBConnectionManager();
sql="select tabseq,SND_MSG,to_char(to_date(WRT_DTTM,'yyyymmddHH24miss'),'yyyymmdd') WRT_DTTM,count(seq) cnt from arreo_sms_log \n";
if(!v_startdt.equals("")&&!v_enddt.equals("")){
sql+="where to_char(to_date(WRT_DTTM,'yyyymmddHH24miss'),'yyyymmdd') between "+StringManager.makeSQL(v_startdt)+" and "+StringManager.makeSQL(v_enddt)+"\n";
}
sql+="Group by tabseq,SND_MSG,to_char(to_date(WRT_DTTM,'yyyymmddHH24miss'),'yyyymmdd') \n";
sql+= " order by tabseq desc \n";
ls=connMgr.executeQuery(sql);
System.out.println("SmsLogBean.getSMSLogList");
System.out.println("sql======>"+sql);
ls.setPageSize(row); // 페이지당 row 갯수를 세팅한다
ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다.
int totalpagecount = ls.getTotalPage(); // 전체 페이지 수를 반환한다
int totalrowcount = ls.getTotalCount(); // 전체 row 수를 반환한다
while(ls.next()){
dbox=ls.getDataBox();
dbox.put("d_dispnum", new Integer(totalrowcount - ls.getRowNum() + 1));
dbox.put("d_totalpage", new Integer(totalpagecount));
dbox.put("d_rowcount", new Integer(row));
logList.add(dbox);
}
} catch (Exception e) {
e.printStackTrace();
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("sql = " + sql + "\r\n" + e.getMessage());
}finally{
try {
if(ls!=null)ls.close();
if(connMgr!=null)connMgr.freeConnection();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return logList;
}
/**
*
* @param box
* @return
* @throws Exception
*/
public List getSMSDetailLogList(RequestBox box)throws Exception{
List logList=new ArrayList();
DBConnectionManager connMgr=null;
ListSet ls=null;
String sql=null;
DataBox dbox=null;
int v_pageno = box.getInt("p_pageno");
int v_tabseq=box.getInt("p_tabseq");
String v_smdMsg=box.getString("p_smdMsg");
String v_searchtext = "";
String v_search = "";
String p_RSLT_VAL=null;
String v_CMP_MSG_ID=null;
try {
connMgr=new DBConnectionManager();
sql="SELECT SEQ,TABSEQ,USERID,SND_PHN_ID,RCV_PHN_ID,SND_MSG,WRT_DTTM,SND_DTTM,RSLT_VAL,CMP_MSG_ID,STATUS \n";
sql+="FROM arreo_sms_log \n";
sql+="WHERE tabseq="+v_tabseq +"\n";
sql+=" and SND_MSG like "+StringManager.makeSQL("%"+v_smdMsg+"%");
v_searchtext = box.getString("p_searchtext");
v_search = box.getString("p_search");
if (!v_searchtext.equals("")) { // 검색어가 있으면
if (v_search.equals("receiverPhoneNumber")) { // 수신자 이름으로 검색할때
sql+=" and RCV_PHN_ID like ";
sql+=StringManager.makeSQL("%" + v_searchtext + "%");
}else if(v_search.equals("userId")){//수신자 이메일로 검색할 때
sql+=" and USERID like ";
sql+=StringManager.makeSQL("%" + v_searchtext + "%");
}
}
System.out.println("SmsLogBean.getSMSDetailLogList");
System.out.println("seq======================>"+sql);
ls=connMgr.executeQuery(sql);
ls.setPageSize(row); // 페이지당 row 갯수를 세팅한다
ls.setCurrentPage(v_pageno); // 현재페이지번호를 세팅한다.
int totalpagecount = ls.getTotalPage(); // 전체 페이지 수를 반환한다
int totalrowcount = ls.getTotalCount(); // 전체 row 수를 반환한다
while(ls.next()){
p_RSLT_VAL=ls.getString("RSLT_VAL");
v_CMP_MSG_ID=ls.getString("CMP_MSG_ID");
// SMS전송 상태에 대한 값을 업데이트 해준다.
// insert 직후에 값을 가져오면 변경전 상태값인 99를 가져오므로 상세리스트를 조회할 때 전송상태를 검사하여 update 한다.
if(p_RSLT_VAL.equals("99")){
updateRSLT_VAL(v_CMP_MSG_ID);
}
dbox=ls.getDataBox();
dbox.put("d_dispnum", new Integer(totalrowcount - ls.getRowNum() + 1));
dbox.put("d_totalpage", new Integer(totalpagecount));
dbox.put("d_rowcount", new Integer(row));
logList.add(dbox);
}
} catch (Exception e) {
e.printStackTrace();
ErrorManager.getErrorStackTrace(e, box, sql);
throw new Exception("sql = " + sql + "\r\n" + e.getMessage());
}finally{
try {
if(ls!=null)ls.close();
if(connMgr!=null)connMgr.freeConnection();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return logList;
}
/**
*
* @param box
* @return
* @throws Exception
*/
public DataBox retrieveSMSLogList(RequestBox box)throws Exception{
DBConnectionManager connMgr=null;
ListSet ls=null;
String sql=null;
DataBox dbox=null;
int v_seq=box.getInt("p_seq");
try {
connMgr=new DBConnectionManager();
sql="SELECT * FROM arreo_sms_log WHERE seq="+v_seq;
ls=connMgr.executeQuery(sql);
while(ls.next()){
dbox=ls.getDataBox();
}
} catch (Exception e) {
}
return dbox;
}
/**
* sms data가 insert 될 때 로그를 기록한다.
* @param box
* @return
* @throws Exception
*/
public int insertSmsLog(RequestBox box)throws Exception{
DBConnectionManager connMgr=null;
PreparedStatement pstmt=null;
StringBuffer sql=new StringBuffer();
int v_seq=getMaxSeq();
int v_tabseq=box.getInt("p_tabseq");//그룹seq
String v_userid=box.getString("p_userid");//사용자 ID
String v_sendPhoneId=box.getString("p_sendPhoneId");//보내는 사람 전화번호
String v_receiverPhoneId=box.getString("p_receiverPhoneId");//받는 사람 전화번호
String v_sendMessage=box.getString("p_sendMessage");//보내는 메시지
String v_sendDateTime=box.getString("p_sendDateTime");//전송할 날짜 시간
String v_status=box.getString("p_status");//전송상태
String v_CMP_MSG_ID=box.getString("p_CMP_MSG_ID");//sms 고유 키
String v_writeDateTime=box.getString("p_writeDateTime");// 작성시간
String v_RSLT_VAL=getRSLT_VAL(v_CMP_MSG_ID);
//파라미터 값 확인
System.out.println("SmsLogBean.insertSmsLog");
System.out.println("v_tabseq==========>"+v_tabseq);
System.out.println("v_userid==========>"+v_userid);
System.out.println("v_sendPhoneId==========>"+v_sendPhoneId);
System.out.println("v_receiverPhoneId==========>"+v_receiverPhoneId);
System.out.println("v_sendMessage==========>"+v_sendMessage);
System.out.println("v_sendDateTime==========>"+v_sendDateTime);
System.out.println("p_CMP_MSG_ID==========>"+v_CMP_MSG_ID);
System.out.println("v_RSLT_VAL==========>"+v_RSLT_VAL);
int isOk=0;
try {
connMgr =new DBConnectionManager();
connMgr.setAutoCommit(false);
sql.append("INSERT INTO arreo_sms_log( \n");
sql.append("SEQ, \n");//기본키
sql.append("TABSEQ, \n");//그룹키
sql.append("USERID, \n");//수신자의 아이디
sql.append("SND_PHN_ID, \n");// 보내는 이 전화번호
sql.append("RCV_PHN_ID, \n");// 받는이 전화번호
sql.append("SND_MSG, \n");// 보내는 메시지
sql.append("WRT_DTTM, \n");// 쓴 날짜 시간
sql.append("SND_DTTM, \n");// 전송될 날짜 시간
sql.append("CMP_MSG_ID, \n");// arreo_sms 테이블의 기본키
sql.append("RSLT_VAL, \n"); // 전송 상태
sql.append("STATUS) \n");// arreo_sms에 insert 성공 여부
//sql.append("VALUES(arreo_sms_log_seq.nextval,\n");//SEQ
sql.append("VALUES(?,\n");//SEQ
sql.append("?, \n");//TABSEQ
sql.append("?, \n");//USERID
sql.append("?, \n");//SND_PHN_ID
sql.append("?, \n");//RCV_PHN_ID
sql.append("?, \n");//SND_MSG
sql.append("?, \n");//WRT_DTTM
sql.append("?, \n");//SND_DTTM
sql.append("?, \n");//CMP_MSG_ID
sql.append("?, \n");//RSLT_VAL
sql.append("? \n");//STATUS
sql.append(") \n");
pstmt=connMgr.prepareStatement(sql.toString());
int idx = 1;
pstmt.setInt(idx++, v_seq);//SEQ
pstmt.setInt(idx++, v_tabseq);//TABSEQ
pstmt.setString(idx++,v_userid );//USERID
pstmt.setString(idx++,v_sendPhoneId );//SND_PHN_ID
pstmt.setString(idx++,v_receiverPhoneId );//RCV_PHN_ID
pstmt.setString(idx++,v_sendMessage );//SND_MSG
pstmt.setString(idx++,v_writeDateTime );//WRT_DTTM
pstmt.setString(idx++,v_sendDateTime );//WRT_DTTM
pstmt.setString(idx++,v_CMP_MSG_ID);//CMP_MSG_ID
pstmt.setString(idx++,v_RSLT_VAL);//RSLT_VAL
pstmt.setString(idx++,v_status );//STATUS
isOk=pstmt.executeUpdate();
System.out.println("sql==============>"+sql.toString());
if(isOk==1){
connMgr.commit();
System.out.println("Logging SMS Succeeded");
}else{
connMgr.rollback();
System.out.println("Logging SMS Failed");
}
} catch (Exception e) {
e.printStackTrace();
ErrorManager.getErrorStackTrace(e, box, sql.toString());
throw new Exception("sql = " + sql.toString() + "\r\n" + e.getMessage());
}finally{
try{
if(pstmt!=null)pstmt.close();
if(connMgr!=null)connMgr.freeConnection();
}catch (Exception e) {
e.printStackTrace();
}
}
return isOk;
}
/**
* sms의 전송 결과를 sms 데이터베이스 서버에서 가져온 후 업데이트 한다.
* @param p_CMP_MSG_ID
* @param tabseq
* @throws Exception
*/
public void updateRSLT_VAL(String p_CMP_MSG_ID)throws Exception{
DBConnectionManager connMgr=null;
PreparedStatement pstmt=null;
String sql=null;
String p_RSLT_VAL=getRSLT_VAL(p_CMP_MSG_ID);
int isOk=0;
try {
connMgr=new DBConnectionManager();
connMgr.setAutoCommit(false);
sql="UPDATE arreo_sms_log SET RSLT_VAL="+StringManager.makeSQL(p_RSLT_VAL);
sql+="WHERE CMP_MSG_ID="+StringManager.makeSQL(p_CMP_MSG_ID);
System.out.println();
pstmt=connMgr.prepareStatement(sql);
isOk=pstmt.executeUpdate();
if(isOk==1){
connMgr.commit();
System.out.println("Update RSLT_VAL from arreo_sms_log Succeeded");
}else{
connMgr.rollback();
System.out.println("Update RSLT_VAL from arreo_sms_log Failed");
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("sql = " + sql.toString() + "\r\n" + e.getMessage());
}finally{
try{
if(pstmt!=null)pstmt.close();
if(connMgr!=null)connMgr.freeConnection();
}catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* sms의 전송결과를 sms 데이터베이스 서버에서 가져온다.
* @param p_CMP_MSG_ID
* @return
* @throws Exception
*/
public String getRSLT_VAL(String p_CMP_MSG_ID)throws Exception{
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
String url="jdbc:oracle:thin:@172.16.1.51:1521:akis01";
String user="arreo_sms";
String password="akissms";
String sql=null;
String p_RSLT_VAL=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection(url, user, password);
sql="select RSLT_VAL FROM arreo_sms where CMP_MSG_ID="+StringManager.makeSQL(p_CMP_MSG_ID);
pstmt=conn.prepareStatement(sql);
rs=pstmt.executeQuery();
while (rs.next()) {
p_RSLT_VAL=rs.getString("RSLT_VAL");
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("sql = " + sql.toString() + "\r\n" + e.getMessage());
}finally{
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
if(conn!=null)conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return p_RSLT_VAL;
}
/**
* Tabseq의 최대값을 가져와서 +1한 값을 반환한다.
* @return
* @throws Exception
*/
public int getMaxTabseq() throws Exception {
DBConnectionManager connMgr=null;
ListSet ls=null;
String sql=null;
int v_tabseq=0;
try{
connMgr = new DBConnectionManager();
//connMgr.setAutoCommit(false);
sql="select nvl(max(tabseq),0)+1 max_tabseq from arreo_sms_log";
ls=connMgr.executeQuery(sql);
while (ls.next()) {
v_tabseq=Integer.parseInt(ls.getString("max_tabseq"));
}
System.out.println("SmsLogBean.getMaxTabseq");
System.out.println("v_tabseq==========>"+v_tabseq);
}catch (Exception e) {
e.printStackTrace();
System.out.println("sql:"+sql);
throw new Exception("sql = " + sql + "\r\n" + e.getMessage());
}finally{
try{
if(ls!=null)ls.close();
if(connMgr!=null)connMgr.freeConnection();
}catch (Exception e) {
e.printStackTrace();
}
}
return v_tabseq;
}
public int getMaxSeq() throws Exception {
DBConnectionManager connMgr=null;
ListSet ls=null;
String sql=null;
int v_seq=0;
try{
connMgr = new DBConnectionManager();
//connMgr.setAutoCommit(false);
sql="select nvl(max(seq),0)+1 max_seq from arreo_sms_log";
ls=connMgr.executeQuery(sql);
while (ls.next()) {
v_seq=Integer.parseInt(ls.getString("max_seq"));
}
System.out.println("SmsLogBean.getMaxSeq");
System.out.println("v_seq==========>"+v_seq);
}catch (Exception e) {
e.printStackTrace();
System.out.println("sql:"+sql);
throw new Exception("sql = " + sql + "\r\n" + e.getMessage());
}finally{
try{
if(ls!=null)ls.close();
if(connMgr!=null)connMgr.freeConnection();
}catch (Exception e) {
e.printStackTrace();
}
}
return v_seq;
}
}
|
package dk.webbies.tscreate.analysis.declarations.types;
import java.util.Set;
/**
* Created by Erik Krogh Kristensen on 06-09-2015.
*/
public abstract class ObjectType extends DeclarationType {
public ObjectType(Set<String> names) {
super(names);
}
}
|
package com.isban.javaapps.reporting.util;
public class Tupla {
private String firstMember;
private String secondMember;
public Tupla(String firstMember, String secondMember) {
super();
this.firstMember = firstMember;
this.secondMember = secondMember;
}
public String getFirstMember() {
return firstMember;
}
public void setFirstMember(String firstMember) {
this.firstMember = firstMember;
}
public String getSecondMember() {
return secondMember;
}
public void setSecondMember(String secondMember) {
this.secondMember = secondMember;
}
}
|
/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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.
*/
public class Main {
public static void assertIntEquals(int expected, int result) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
public static void assertLongEquals(long expected, long result) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result);
}
}
/// CHECK-START-X86_64: long Main.and_not_64(long, long) instruction_simplifier_x86_64 (before)
/// CHECK-DAG: Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: Not loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Not loop:none
/// CHECK-DAG: And loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: long Main.and_not_64(long, long) instruction_simplifier_x86_64 (after)
// CHECK-DAG: X86AndNot loop:<<Loop:B\d+>> outer_loop:none
// CHECK-DAG: X86AndNot loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: long Main.and_not_64(long, long) instruction_simplifier_x86_64 (after)
// CHECK-NOT: Not loop:<<Loop>> outer_loop:none
// CHECK-NOT: And loop:<<Loop>> outer_loop:none
// CHECK-NOT: Not loop:none
// CHECK-NOT: And loop:none
public static long and_not_64( long x, long y) {
long j = 1;
long k = 2;
for (long i = -64 ; i < 64; i++ ) {
x = x & ~i;
y = y | i;
}
return x & ~y;
}
/// CHECK-START-X86_64: int Main.and_not_32(int, int) instruction_simplifier_x86_64 (before)
/// CHECK-DAG: Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: Not loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Not loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Not loop:none
/// CHECK-DAG: And loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: int Main.and_not_32(int, int) instruction_simplifier_x86_64 (after)
// CHECK-DAG: X86AndNot loop:<<Loop:B\d+>> outer_loop:none
// CHECK-DAG: X86AndNot loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86AndNot loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: int Main.and_not_32(int, int) instruction_simplifier_x86_64 (after)
// CHECK-NOT: Not loop:<<Loop>> outer_loop:none
// CHECK-NOT: And loop:<<Loop>> outer_loop:none
// CHECK-NOT: Not loop:none
// CHECK-NOT: And loop:none
public static int and_not_32( int x, int y) {
int j = 1;
int k = 2;
for (int i = -64 ; i < 64; i++ ) {
x = x & ~i;
y = y | i;
}
return x & ~y;
}
/// CHECK-START-X86_64: int Main.reset_lowest_set_bit_32(int) instruction_simplifier_x86_64 (before)
/// CHECK-DAG: Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Add loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: int Main.reset_lowest_set_bit_32(int) instruction_simplifier_x86_64 (after)
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop:B\d+>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: int Main.reset_lowest_set_bit_32(int) instruction_simplifier_x86_64 (after)
// CHECK-NOT: And loop:<<Loop>> outer_loop:none
public static int reset_lowest_set_bit_32(int x) {
int y = x;
int j = 5;
int k = 10;
int l = 20;
for (int i = -64 ; i < 64; i++) {
y = i & i-1;
j += y;
j = j & j-1;
k +=j;
k = k & k-1;
l +=k;
l = l & l-1;
}
return y + j + k + l;
}
/// CHECK-START-X86_64: long Main.reset_lowest_set_bit_64(long) instruction_simplifier_x86_64 (before)
/// CHECK-DAG: Phi loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: Sub loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Sub loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Sub loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
/// CHECK-DAG: Sub loop:<<Loop>> outer_loop:none
/// CHECK-DAG: And loop:<<Loop>> outer_loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: long Main.reset_lowest_set_bit_64(long) instruction_simplifier_x86_64 (after)
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop:B\d+>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:<<Loop>> outer_loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: long Main.reset_lowest_set_bit_64(long) instruction_simplifier_x86_64 (after)
// CHECK-NOT: And loop:<<Loop>> outer_loop:none
// CHECK-NOT: Sub loop:<<Loop>> outer_loop:none
public static long reset_lowest_set_bit_64(long x) {
long y = x;
long j = 5;
long k = 10;
long l = 20;
for (long i = -64 ; i < 64; i++) {
y = i & i-1;
j += y;
j = j & j-1;
k +=j;
k = k & k-1;
l +=k;
l = l & l-1;
}
return y + j + k + l;
}
/// CHECK-START-X86_64: int Main.get_mask_lowest_set_bit_32(int) instruction_simplifier_x86_64 (before)
/// CHECK-DAG: Add loop:none
/// CHECK-DAG: Xor loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: int Main.get_mask_lowest_set_bit_32(int) instruction_simplifier_x86_64 (after)
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: int Main.get_mask_lowest_set_bit_32(int) instruction_simplifier_x86_64 (after)
// CHECK-NOT: Add loop:none
// CHECK-NOT: Xor loop:none
public static int get_mask_lowest_set_bit_32(int x) {
return (x-1) ^ x;
}
/// CHECK-START-X86_64: long Main.get_mask_lowest_set_bit_64(long) instruction_simplifier_x86_64 (before)
/// CHECK-DAG: Sub loop:none
/// CHECK-DAG: Xor loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: long Main.get_mask_lowest_set_bit_64(long) instruction_simplifier_x86_64 (after)
// CHECK-DAG: X86MaskOrResetLeastSetBit loop:none
// TODO:re-enable when checker supports isa features
// CHECK-START-X86_64: long Main.get_mask_lowest_set_bit_64(long) instruction_simplifier_x86_64 (after)
// CHECK-NOT: Sub loop:none
// CHECK-NOT: Xor loop:none
public static long get_mask_lowest_set_bit_64(long x) {
return (x-1) ^ x;
}
public static void main(String[] args) {
int x = 50;
int y = x/2;
long a = Long.MAX_VALUE;
long b = Long.MAX_VALUE/2;
assertIntEquals(0,and_not_32(x,y));
assertLongEquals(0L, and_not_64(a,b));
assertIntEquals(-20502606, reset_lowest_set_bit_32(x));
assertLongEquals(-20502606L, reset_lowest_set_bit_64(a));
assertLongEquals(-20502606L, reset_lowest_set_bit_64(b));
assertIntEquals(1, get_mask_lowest_set_bit_32(y));
assertLongEquals(1L, get_mask_lowest_set_bit_64(b));
}
}
|
package com.piggymetrics.account;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactBroker;
import au.com.dius.pact.provider.junit.loader.PactBrokerAuth;
import au.com.dius.pact.provider.junit5.HttpTestTarget;
import au.com.dius.pact.provider.junit5.PactVerificationContext;
import au.com.dius.pact.provider.junit5.PactVerificationInvocationContextProvider;
import com.piggymetrics.account.client.StatisticsServiceClient;
import com.piggymetrics.account.domain.Account;
import com.piggymetrics.account.repository.AccountRepository;
import org.apache.http.HttpRequest;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.net.URI;
import java.net.URISyntaxException;
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {AccountApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,
properties = "server.port=8081")
@Provider("accountservice")
@PactBroker(host = "citi.pactflow.io", port="443", scheme = "https",
authentication = @PactBrokerAuth(token = "663-sCQYf_VxQQ0nPew8sg"))
@ContextConfiguration(classes = {StatisticsServiceClient.class})
public class AccountServiceApplicationProviderPactTest {
@MockBean
AccountRepository accountRepository;
@MockBean
StatisticsServiceClient statisticsClient;
@TestTemplate
@ExtendWith(PactVerificationInvocationContextProvider.class)
void testTemplate(PactVerificationContext context, HttpRequest request) {
URI uri = ((HttpUriRequest) request).getURI();
String host = uri.getHost();
int port = uri.getPort();
String path = uri.getPath();
try{
((HttpRequestBase) request).setURI(new URI("http", null, host, port, path.replaceFirst("/accounts", "/"), null, null));
} catch (URISyntaxException e) {
e.printStackTrace();
}
context.verifyInteraction();
}
@BeforeEach
void setupTestTarget(PactVerificationContext context) {
System.setProperty("pact.verifier.publishResults", "true");
System.setProperty("pact.provider.version", "4.0.0");
context.setTarget(new HttpTestTarget("localhost", 8081, "/"));
Account account = new Account();
Mockito.when(accountRepository.save(Mockito.any())).thenReturn(account);
}
@State("provider accepts a new account")
public void setupForNewAccount(){
}
@State("demo_acct exists")
public void setupForUpdateAccount() {
Account account = new Account();
Mockito.when(accountRepository.save(Mockito.any())).thenReturn(account);
Mockito.when(accountRepository.findByName(Mockito.anyString())).thenReturn(account);
Mockito.when(statisticsClient.updateStatistics(Mockito.anyString(), Mockito.any())).thenReturn(new Object());
}
}
|
import java.util.*;
class ArrayL{
int num,i,n;
ArrayList<Integer> arr=new ArrayList<Integer>(n);
Scanner sc=new Scanner(System.in);
void create()
{
System.out.print("Enter the num of node in array to be created:");
num=sc.nextInt();
for (i=1;i<=num;i++)
{
System.out.print("Enter the node at ("+i+"):");
n=sc.nextInt();
arr.add(n);
}
System.out.println(arr);
}
void copy()
{
System.out.print("Copying the array list.");
arr.clone();
System.out.println(arr);
}
void remove()
{
System.out.print("Enter the node_loc to be remove:");
n=sc.nextInt();
arr.remove(n);
System.out.println("After removing node at loc"+arr);
}
void size()
{
for(i=0;i<arr.size();i++)
System.out.print("Array size is"+arr.get(i)+" ");
System.out.println();
}
void clear()
{
System.out.println("Before clearing array"+arr);
arr.clear();
System.out.println("After clearing array"+arr);
}
public static void main (String args[]) //throws IOException
{
ArrayL al=new ArrayL();
al.create();
al.copy();
al.remove();
al.size();
al.clear();
}
} |
package cl.sportapp.evaluation.config.service;
import cl.sportapp.evaluation.dao.UsuarioDao;
import cl.sportapp.evaluation.entitie.Usuario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UsuarioDao usuarioDao;
@Override
@Transactional
public UserDetails loadUserByUsername(String email)
throws UsernameNotFoundException {
Usuario usuario = usuarioDao.findByEmail(email)
.orElseThrow(() ->
new UsernameNotFoundException("User Not Found with -> username or email : " + email)
);
return UserPrinciple.build(usuario);
}
} |
package karolinakaminska.github.com;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
public class GetReadableDbTask extends AsyncTask<SQLiteOpenHelper, Void, SQLiteDatabase>{
@Override
protected SQLiteDatabase doInBackground(SQLiteOpenHelper... sqLiteOpenHelpers) { //i tak będzie tylko 1 XD
for(SQLiteOpenHelper i : sqLiteOpenHelpers) {
return i.getReadableDatabase();
}
return null;
}
}
|
package org.bitbucket.alltra101ify.advancedsatelliteutilization.moditems;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.ModInfo;
import org.bitbucket.alltra101ify.advancedsatelliteutilization.reference.moditemblockreference.ModBasicItemTemplate;
public class ASHADBrick extends ModBasicItemTemplate {
public ASHADBrick() {
setUnlocalizedName("ASHADBrick");
setTextureName(ModInfo.MODID + ":" + getUnlocalizedName().substring(5));
}
}
|
package Models;
import java.time.*;
import java.util.*;
public class SaleOrder extends GenericOrder {
private int customerId;
private ArrayList<SalesOrderLine> saleOrderLines;
private Discount discount;
public SaleOrder(LocalDateTime deliveryDate, LocalDateTime orderDate, String deliveryAddress, boolean isDelivered, double amount, EmployeeRole employee, int customerId)
{
super(deliveryDate, orderDate, deliveryAddress, isDelivered, amount, employee, "Sale");
this.customerId = customerId;
saleOrderLines = new ArrayList<>();
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public void setSalesOrderLine(SalesOrderLine SaleOrderLine)
{
saleOrderLines.add(SaleOrderLine);
}
public void removeSalesOrderLine(SalesOrderLine SalesOrderLine)
{
saleOrderLines.remove(SalesOrderLine);
}
public ArrayList<SalesOrderLine> readSalesOrderLine()
{
return saleOrderLines;
}
public void setTotalPriceForPerson() {
double amount = super.getAmount();
if(saleOrderLines.size()!=0) {
for(SalesOrderLine r: saleOrderLines) {
amount += r.getProduct().getPrice() * r.getQuantity();
}
if(amount < 2500) {
amount += amount +45;
}
}
super.setAmount(amount);
}
public void setTotalPriceForOrganization() {
double amount = super.getAmount();
if(saleOrderLines.size()!=0) {
for(SalesOrderLine r: saleOrderLines) {
amount += r.getProduct().getPrice() * r.getQuantity();
}
if(amount > 1500) {
amount += amount * discount.getDiscountValue();
}
super.setAmount(amount);
}
}
}
|
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.List;
public class BSTMapTest {
@Test
public void basicTest() {
BSTMap<Integer, Integer> test = new BSTMap<Integer, Integer>();
test.put(5, 5);
test.put(6, 6);
test.put(4, 4);
test.put(10, 10);
test.put(100, 100);
test.put(1, 1);
test.put(25, 25);
test.put(36, 36);
test.put(49, 49);
}
@Test
public void testSize() {
BSTMap<Integer, Integer> test = new BSTMap<Integer, Integer>();
test.put(5, 5);
test.put(6, 6);
test.put(4, 4);
test.put(10, 10);
test.put(100, 100);
test.put(5, 4);
test.put(25, 25);
test.put(36, 36);
test.put(49, 49);
assertEquals((Integer) 8,(Integer) test.size());
}
@Test
public void testPrint() {
BSTMap<Integer, Integer> test = new BSTMap<Integer, Integer>();
test.put(5, 5);
test.put(6, 6);
test.put(4, 4);
test.put(10, 10);
test.put(100, 100);
test.put(1, 1);
test.put(25, 25);
test.put(36, 36);
test.put(49, 49);
test.printInOrder();
}
@Test
public void testGet() {
BSTMap<Integer, Integer> test = new BSTMap<Integer, Integer>();
test.put(5, 5);
test.put(6, 6);
test.put(4, 4);
test.put(10, 10);
test.put(100, 100);
test.put(5, 4);
test.put(25, 25);
test.put(36, 36);
test.put(49, 49);
assertEquals((Integer) 25,(Integer) test.get(25));
assertEquals((Integer) 4,(Integer) test.get(5));
assertEquals(null, test.get(7));
}
/** Runs tests. */
public static void main(String[] args) {
jh61b.junit.textui.runClasses(BSTMapTest.class);
}
} |
package com.citibank.newcpb.vo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import com.citibank.newcpb.enums.TableTypeEnum;
public class ErEmVO implements Serializable{
private static final long serialVersionUID = 1L;
private String erNbr; // Numero do ER
private String emNbr; // Numero do ER AMC
private String roleCustCode; // Codigo do Papel do Relaciomento
private String roleCustDesc; // Codigo do Papel do Relaciomento
private Date lastAuthDate; // Data e hora da última autorizacao
private String lastAuthUser; // Usuario que realizou a ultima autorizacao
private Date lastUpdDate; // Data e hora da última atualização
private String lastUpdUser; // Usuario que realizou a ultima atualizacao
private String recStatCode; // Status do Registro
private TableTypeEnum tableOrigin; // Tipo da Tabela de Origem (CAD/MOV/HIST)
public String getErNbr() {
return erNbr;
}
public void setErNbr(String erNbr) {
this.erNbr = erNbr;
}
public String getEmNbr() {
return emNbr;
}
public void setEmNbr(String emNbr) {
this.emNbr = emNbr;
}
public String getRoleCustCode() {
return roleCustCode;
}
public void setRoleCustCode(String roleCustCode) {
this.roleCustCode = roleCustCode;
}
public Date getLastAuthDate() {
return lastAuthDate;
}
public void setLastAuthDate(Date lastAuthDate) {
this.lastAuthDate = lastAuthDate;
}
public String getLastAuthUser() {
return lastAuthUser;
}
public void setLastAuthUser(String lastAuthUser) {
this.lastAuthUser = lastAuthUser;
}
public Date getLastUpdDate() {
return lastUpdDate;
}
public void setLastUpdDate(Date lastUpdDate) {
this.lastUpdDate = lastUpdDate;
}
public String getLastUpdUser() {
return lastUpdUser;
}
public void setLastUpdUser(String lastUpdUser) {
this.lastUpdUser = lastUpdUser;
}
public TableTypeEnum getTableOrigin() {
return tableOrigin;
}
public void setTableOrigin(TableTypeEnum tableOrigin) {
this.tableOrigin = tableOrigin;
}
public String getRecStatCode() {
return recStatCode;
}
public void setRecStatCode(String recStatCode) {
this.recStatCode = recStatCode;
}
public ArrayList<String> equals(ErEmVO other) {
ArrayList<String> idDiffList = new ArrayList<String>();
if (other != null){
if (this.erNbr != null && other.erNbr != null) {
if (!this.erNbr.equals(other.erNbr)) {
idDiffList.add("er_em.erNbr");
}
} else if ((this.erNbr == null && other.erNbr != null) || (other.erNbr == null && this.erNbr != null)) {
idDiffList.add("er_em.erNbr");
}
if (this.emNbr != null && other.emNbr != null) {
if (!this.emNbr.equals(other.emNbr)) {
idDiffList.add("er_em.emNbr");
}
} else if ((this.emNbr == null && other.emNbr != null) || (other.emNbr == null && this.emNbr != null)) {
idDiffList.add("er_em.emNbr");
}
if (this.roleCustCode != null && other.roleCustCode != null) {
if (!this.roleCustCode.equals(other.roleCustCode)) {
idDiffList.add("er_em.roleCustCode");
}
} else if ((this.roleCustCode == null && other.roleCustCode != null) || (other.roleCustCode == null && this.roleCustCode != null)) {
idDiffList.add("er_em.roleCustCode");
}
}
return idDiffList;
}
public String getRoleCustDesc() {
return roleCustDesc;
}
public void setRoleCustDesc(String roleCustDesc) {
this.roleCustDesc = roleCustDesc;
}
}
|
package com.mycompany.sentenciasdecontrol2;
public class FOR {
public static void main(String[] args) {
int total = 0;
for (int numero = 2; numero <= 20; numero += 2)
total += numero;
System.out.println("La suma es: "+total);
}
}
|
package com.javakc.fms.file.service;
import com.javakc.fms.file.entity.FileEntity;
import java.util.List;
public interface FileService {
//添加
public int insert(FileEntity entity);
//删除
public int delete(String id);
//改
public int update(FileEntity entity);
//查 (分页,条件)
public List<FileEntity> queryByPage(FileEntity entity,int start,int end);
//根据主键查
public FileEntity queryId(String Id);
//下载次数加一
public void downnumCount(String id);
}
|
package com.eu.fpms.bbap;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class UserDrinksheetActivity extends AppCompatActivity {
//DECLARATION
//int[] imageId = {R.drawable.orval, R.drawable.chimay_bleue, R.drawable.rochefort};
ImageButton imageButton;
ArrayList<String> drinkArrayList = new ArrayList<String>();;
AlertDialog alert;
ArrayList<String> drinkList;
ArrayAdapter<String> adapter;
ListView listView;
MyListAdapter adapter2;
Button calculAlcool;
Button calculCaL;
Button calculTemps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drinksheet);
//INITIALIZATION
imageButton = (ImageButton)findViewById(R.id.btn_alert_dialog);
listView = (ListView) findViewById(R.id.dynamicListView);
drinkList = new ArrayList<String>();
//adapter = new ArrayAdapter<String>(UserDrinksheetActivity.this, android.R.layout.simple_list_item_1, drinkList);
//listView.setAdapter(adapter);
adapter2 = new MyListAdapter(this, R.layout.row_item ,drinkList);
listView.setAdapter(adapter2);
//DATABASE
final DatabaseHelper myDb = new DatabaseHelper(this);
//ON CLICK FOR ALERT DIALOG BUTTON
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drinkArrayList.clear();
//RETRIEVE DATA FROM DB TO PUT IN ALERTDIALOG
Cursor cursor = myDb.fetchDrinkInfo();
while (cursor.moveToNext()){
String drinkName = cursor.getString(1);
drinkArrayList.add(drinkName);
}
//METHOD: CREATE + SET UP ALERTDIALOG IN THE LAYOUT
showDialog();
}
});
//ON CLICK FOR ALCOHOL CALCUL BUTTON
calculAlcool = (Button)findViewById(R.id.button_calcul_alcool);
calculAlcool.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"EN COURS DE CONSTRUCTION",Toast.LENGTH_SHORT).show();
//focntionCalculAlcool(myDb);
//double resultat = algorithmeAlcoolemie(150,5,69,181,22,"Homme");
//Toast.makeText(getApplicationContext(),"TAUX CALCULE = " + resultat,Toast.LENGTH_LONG).show();
}
});
//ON CLICK FOR CALORIE BUTTON
calculCaL = (Button)findViewById(R.id.button_calcul_calorie);
calculCaL.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"EN COURS DE CONSTRUCTION",Toast.LENGTH_SHORT).show();
}
});
//ON CLICK FOR CALCUL TIME BUTTON
calculTemps = (Button)findViewById(R.id.button_calcul_temps);
calculTemps.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"EN COURS DE CONSTRUCTION",Toast.LENGTH_SHORT).show();
}
});
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private void showDialog(){
AlertDialog.Builder theBuilder = new AlertDialog.Builder(UserDrinksheetActivity.this);
//add data
int numberOfDrinks = drinkArrayList.size();
final String[] names = new String[numberOfDrinks];
for(int i=0; i<numberOfDrinks; i++){
names[i] = drinkArrayList.get(i);
}
theBuilder.setItems(names, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),names[which] + " ajoutée à votre drinksheet", Toast.LENGTH_SHORT).show();
drinkList.add(names[which]);
//adapter.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
}
});
theBuilder.setNegativeButton("Stop! je suis déjà charette!",null);
alert = theBuilder.create();
alert.setTitle("Fils,une bière se déguste avec Sagesse!");
alert.show();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {
super(context, resource, objects);
layout = resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
ViewHolder mainViewHolder = null;
if(convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout,parent,false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.title = (TextView) convertView.findViewById(R.id.tvBeername);
viewHolder.quantity = (EditText) convertView.findViewById(R.id.etQuantity);
viewHolder.tv_time = (TextView) convertView.findViewById(R.id.tvTime);
//setTag allow to store any objet
convertView.setTag(viewHolder);
}
else {
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.title.setText(getItem(position));
mainViewHolder.tv_time.setText(getCurrentTime());
}
return convertView;
}
}
public class ViewHolder{
TextView title;
EditText quantity;
TextView tv_time;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public String getCurrentTime(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String time = format.format(calendar.getTime());
return time;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public double algorithmeAlcoolemie(double volume, double taux, int poids, int taille, int age, String sexe){
double taux_alco = 0.0;
double masse_ethanol = 0.0;
double K = 0.0;
double C = 0.0;
double IMC;
double IMG;
masse_ethanol = (volume * taux);
IMC = poids / (taille*taille);
if(sexe == "Homme") {
IMG = (1.2 * IMC) + (0.23 * age) - 16.2;
K = 0.7;
if(IMG < 15.0){
C = 0.9;
}
else if (IMG >= 15.0 && IMG <= 20 ){
C = 1.0;
}
else if (IMG > 20){
C = 1.1;
}
}
else if(sexe == "Femme"){
IMG = (1.2 * IMC) + (0.23 * age) - 5.4;
K = 0.6;
if(IMG < 25.0){
C = 0.9;
}
else if (IMG >= 25.0 && IMG <= 30 ){
C = 1.0;
}
else if (IMG > 30){
C = 1.1;
}
}
else{
System.out.println("ERREUR SEXE INDÉFINI OU ENDOMMAGÉ !");
}
taux_alco = masse_ethanol / (poids * K * C);
return taux_alco;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CETTE FONCTION EST EN COURS DE CONSTRUCTION
public void focntionCalculAlcool(DatabaseHelper db){
int sizeDrinkList = drinkList.size();
Drink boisson;
String userName = "ju";
User nomUtilisateur;
double volume = 5;
double tauxTotalTemp = 0;
nomUtilisateur = db.fetchUserInfo(userName);
for(int i=0;i<sizeDrinkList;i++) {
String beerName = drinkList.get(i);
boisson = db.getAllDrinkInfo(beerName);
//tauxTotalTemp = tauxTotalTemp + algorithmeAlcoolemie(volume,boisson.getVol(), nomUtilisateur.getWeight(),nomUtilisateur.getHeight(),nomUtilisateur.getAge(),nomUtilisateur.getSex());
}
Toast.makeText(getApplicationContext(),"Taux Calculé = " + tauxTotalTemp,Toast.LENGTH_LONG).show();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public double algorithmeCalories(int poids, int taille, int age, String sexe, double kcal){
double kcal_quot = 0.0;
double kcal_pourcent = 0.0;
if(sexe == "Homme") {
kcal_quot = ( 9.99*poids + 6.25*taille - 5*age + 5 ) * 1.3;
}
else if(sexe == "Femme") {
kcal_quot = ( 9.99*poids + 6.25*taille - 5*age - 161 ) * 1.3;
}
kcal_pourcent = kcal / kcal_quot;
return kcal_pourcent;
}
public double algorithmeTemps(String sexe, double taux_alco){
double temps = 0.0;
if(sexe == "Homme"){
if(taux_alco > 0.5){
temps = ( taux_alco - 0.5 ) / 0.1;
}
else{
temps = 0.0;
}
}
else if(sexe == "Femme"){
if(taux_alco > 0.5){
temps = ( taux_alco - 0.5 ) / 0.085;
}
else{
temps = 0.0;
}
}
return temps;
// Le temps est en heures !
}
}
|
package uk.nhs.hee.web.mockserver.service.bean;
public class KeyStaff {
private String name;
private String displayName;
private String imageUrl;
private String department;
private String title;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
|
/**
* generated by Xtext 2.10.0
*/
package com.fun.gantt.example;
import com.fun.gantt.example.SMDSLStandaloneSetupGenerated;
/**
* Initialization support for running Xtext languages without Equinox extension registry.
*/
@SuppressWarnings("all")
public class SMDSLStandaloneSetup extends SMDSLStandaloneSetupGenerated {
public static void doSetup() {
SMDSLStandaloneSetup _sMDSLStandaloneSetup = new SMDSLStandaloneSetup();
_sMDSLStandaloneSetup.createInjectorAndDoEMFRegistration();
}
}
|
package com.app.nokia.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author Burak KILINC
* @since 3/4/2021
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PhoneBillPaymentTransaction extends Transaction {
private String payee;
private String phoneNumber;
public PhoneBillPaymentTransaction(String payee, String phoneNumber, double amount) {
super(amount);
this.payee = payee;
this.phoneNumber = phoneNumber;
}
@Override
public String toString() {
return "PhoneBillPaymentTransaction{" +
"payee='" + payee + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
|
package asylumdev.adgresources.api.materialsystem.part;
public class Dust {
}
|
package db;
import java.util.List;
import Models.GenericOrder;
public interface OrderDBIF {
List<GenericOrder> findAll() throws DataAccessException;
GenericOrder findById(int id) throws DataAccessException;
GenericOrder insert(GenericOrder order) throws DataAccessException;
}
|
package hk.ust.felab.rase;
import hk.ust.felab.rase.master.impl.MasterImpl;
import hk.ust.felab.rase.ras.Ras;
import hk.ust.felab.rase.sim.Sim;
import hk.ust.felab.rase.util.ArraysUtil;
import hk.ust.felab.rase.util.RaseClassLoader;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.helpers.LogLog;
public class Headquarters {
public static final String RAS_PKG = "hk.ust.felab.rase.ras.impl";
public static void main(String[] args) throws IOException,
ClassNotFoundException, IllegalAccessException,
InstantiationException, ExecutionException, InterruptedException {
int argsI = 0;
String altsStr = args[argsI++];
String rasClassFile = args[argsI++];
String rasArgsStr = args[argsI++];
String simClassFile = args[argsI++];
String simArgsStr = args[argsI++];
String repeatTimeStr = args[argsI++];
String logDirStr = args[argsI++];
double[][] alts = loadAltsFromFile(altsStr);
String rasClassName = getClassName(rasClassFile);
RaseClassLoader classLoader = new RaseClassLoader(rasClassName,
rasClassFile);
classLoader.loadClass(rasClassName);
Ras ras = (Ras) Class.forName(rasClassName, true, classLoader)
.newInstance();
double[] rasArgs = ArraysUtil.stringToDoubleArray(rasArgsStr);
int simThreadNum;
if (argsI < args.length) {
simThreadNum = Integer.parseInt(args[argsI++]);
} else {
simThreadNum = Runtime.getRuntime().availableProcessors();
}
double[] simArgs = ArraysUtil.stringToDoubleArray(simArgsStr);
LogLog.setQuietMode(true);
int repeatTime = Integer.parseInt(repeatTimeStr);
for (int i = 0; i < repeatTime; i++) {
String logDir = logDirStr + "/" + i;
int res = repeatOnce(alts, ras, rasArgs, simClassFile,
simThreadNum, simArgs, logDir);
System.out.println(i + ", " + res);
}
}
private static String getClassName(String fileName) {
String[] fields = fileName.split("/");
String className = fields[fields.length - 1];
className = className.split("\\.")[0];
return className;
}
private static int repeatOnce(double[][] alts, Ras ras, double[] rasArgs,
String simClassFile, int simThreadNum, double[] simArgs,
String logDir) throws IOException, ClassNotFoundException,
IllegalAccessException, InstantiationException, ExecutionException,
InterruptedException {
System.setProperty("log.dir", logDir);
PropertyConfigurator.configure(ClassLoader
.getSystemResourceAsStream("log4j.properties"));
List<Sim> sims = new LinkedList<Sim>();
String simClassName = getClassName(simClassFile);
for (int i = 0; i < simThreadNum; i++) {
RaseClassLoader classLoader = new RaseClassLoader(simClassName,
simClassFile);
classLoader.loadClass(simClassName);
sims.add((Sim) Class.forName(simClassName, true, classLoader)
.newInstance());
}
MasterImpl master = new MasterImpl(alts, sims);
int result = ras.ras(alts, rasArgs, master);
master.stopSlaves();
LogManager.shutdown();
return result;
}
private static double[][] loadAltsFromFile(String file) throws IOException {
ArrayList<double[]> altsArgs = new ArrayList<double[]>();
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String line = null;
int len = 0;
while ((line = br.readLine()) != null) {
double[] altArgs = ArraysUtil.stringToDoubleArray(line);
if (altArgs.length < len) {
System.err.println("arg count not equal\nlast line is empty?");
System.exit(-1);
}
len = altArgs.length;
altsArgs.add(altArgs);
}
br.close();
return altsArgs.toArray(new double[][] {});
}
}
|
package com.example.tech4gt.restapi.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.tech4gt.restapi.api.apiService;
import com.example.tech4gt.restapi.R;
import com.example.tech4gt.restapi.models.Post;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.POST;
/**
* Created by tech4GT on 12/22/17.
*/
public class postsAdapter extends RecyclerView.Adapter<postsAdapter.postViewHolder> {
public static final String TAG = "mytag";
Context context;
ArrayList<Post> posts = new ArrayList<>();
public postsAdapter(Context context) {
Log.d(TAG, "postsAdapter: ");
this.context = context;
Call<ArrayList<Post>> getPostsCall = apiService.getInstance().getPosts();
getPostsCall.enqueue(new Callback<ArrayList<Post>>() {
@Override
public void onResponse(Call<ArrayList<Post>> call, Response<ArrayList<Post>> response) {
posts.addAll(response.body());
Log.d(TAG, String.valueOf(response.body().size()));
postsAdapter.this.notifyDataSetChanged();
}
@Override
public void onFailure(Call<ArrayList<Post>> call, Throwable t) {
t.printStackTrace();
}
});
}
@Override
public postViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.d(TAG, "onCreateViewHolder: ");
return new postViewHolder(((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.list_item_post, parent, false));
}
@Override
public void onBindViewHolder(postViewHolder holder, int position) {
holder.tvTitle.setText(posts.get(position).getTitle());
holder.tvUserId.setText(posts.get(position).getUserId().toString());
holder.tvBody.setText(posts.get(position).getBody());
}
@Override
public int getItemCount() {
return this.posts.size();
}
class postViewHolder extends RecyclerView.ViewHolder {
TextView tvUserId, tvTitle, tvBody;
public postViewHolder(View itemView) {
super(itemView);
tvUserId = itemView.findViewById(R.id.tvPostUserId);
tvBody = itemView.findViewById(R.id.tvPostBody);
tvTitle = itemView.findViewById(R.id.tvPostTitle);
}
}
}
|
package com.hcl.neo.eloader.dao;
import org.springframework.data.mongodb.repository.MongoRepository;
import com.hcl.neo.eloader.model.TransportServerMaster;
public interface TransportServerRepository extends MongoRepository<TransportServerMaster, String> {
public TransportServerMaster findByServerId(long serverId);
public TransportServerMaster findByType(String type);
}
|
package com.javaee.ebook1.mybatis.entity;
import java.io.Serializable;
public class UserRole implements Serializable {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_role.uid
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
private Integer uid;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column user_role.rid
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
private Integer rid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table user_role
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_role.uid
*
* @return the value of user_role.uid
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
public Integer getUid() {
return uid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_role.uid
*
* @param uid the value for user_role.uid
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
public void setUid(Integer uid) {
this.uid = uid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column user_role.rid
*
* @return the value of user_role.rid
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
public Integer getRid() {
return rid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column user_role.rid
*
* @param rid the value for user_role.rid
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
public void setRid(Integer rid) {
this.rid = rid;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table user_role
*
* @mbg.generated Wed Apr 14 14:41:41 CST 2021
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", uid=").append(uid);
sb.append(", rid=").append(rid);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.